src/ApiPlatform/Voter/ActionPlanVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\ApiPlatform\Voter;
  3. use App\Entity\ActionPlan;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class ActionPlanVoter extends Voter
  9. {
  10.     public const CREATE 'CREATE';
  11.     public const EDIT 'EDIT';
  12.     public const DELETE 'DELETE';
  13.     public function __construct(private readonly Security $security)
  14.     {
  15.     }
  16.     protected function supports(string $attribute$subject): bool
  17.     {
  18.         if (!$subject instanceof ActionPlan) {
  19.             return false;
  20.         }
  21.         return in_array($attribute, [self::CREATEself::EDITself::DELETE]);
  22.     }
  23.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  24.     {
  25.         $user $token->getUser();
  26.         if (!$user instanceof User) {
  27.             return false;
  28.         }
  29.         switch ($attribute) {
  30.             case self::CREATE:
  31.                 return $this->canCreate($user$subject);
  32.             case self::EDIT:
  33.             case self::DELETE:
  34.                 return $this->canEditOrDelete($user$subject);
  35.         }
  36.         return false;
  37.     }
  38.     private function canCreate(User $user,ActionPlan $actionPlan): bool
  39.     {
  40.         if (!$actionPlan->getSite()) {
  41.             return false;
  42.         }
  43.         foreach ($user->getUserSites() as $userSite) {
  44.             if ($userSite->getSite()->getId() === $actionPlan->getSite()->getId()) {
  45.                 return true;
  46.             }
  47.         }
  48.         return false;
  49.     }
  50.     private function canEditOrDelete(User $userActionPlan $actionPlan): bool
  51.     {
  52.         // Check if user is associated with the action plan's site
  53.         foreach ($user->getUserSites() as $userSite) {
  54.             if ($userSite->getSite()->getId() === $actionPlan->getSite()->getId()) {
  55.                 return true;
  56.             }
  57.         }
  58.         return false;
  59.     }
  60. }