<?php
namespace App\ApiPlatform\Voter;
use App\Entity\ActionPlan;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ActionPlanVoter extends Voter
{
public const CREATE = 'CREATE';
public const EDIT = 'EDIT';
public const DELETE = 'DELETE';
public function __construct(private readonly Security $security)
{
}
protected function supports(string $attribute, $subject): bool
{
if (!$subject instanceof ActionPlan) {
return false;
}
return in_array($attribute, [self::CREATE, self::EDIT, self::DELETE]);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
switch ($attribute) {
case self::CREATE:
return $this->canCreate($user, $subject);
case self::EDIT:
case self::DELETE:
return $this->canEditOrDelete($user, $subject);
}
return false;
}
private function canCreate(User $user,ActionPlan $actionPlan): bool
{
if (!$actionPlan->getSite()) {
return false;
}
foreach ($user->getUserSites() as $userSite) {
if ($userSite->getSite()->getId() === $actionPlan->getSite()->getId()) {
return true;
}
}
return false;
}
private function canEditOrDelete(User $user, ActionPlan $actionPlan): bool
{
// Check if user is associated with the action plan's site
foreach ($user->getUserSites() as $userSite) {
if ($userSite->getSite()->getId() === $actionPlan->getSite()->getId()) {
return true;
}
}
return false;
}
}