src/ApiPlatform/Voter/ActionPlanVoter.php line 12

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\Authorization\Voter\VoterInterface;
  8. use Symfony\Component\Security\Core\Security;
  9. class ActionPlanVoter extends Voter implements VoterInterface
  10. {
  11.     public const CREATE 'CREATE';
  12.     public const EDIT 'EDIT';
  13.     public const DELETE 'DELETE';
  14.     public function __construct(private readonly Security $security)
  15.     {
  16.     }
  17.     protected function supports(string $attribute$subject): bool
  18.     {
  19.         if (!$subject instanceof ActionPlan) {
  20.             return false;
  21.         }
  22.         return in_array($attribute, [self::CREATEself::EDITself::DELETE]);
  23.     }
  24.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  25.     {
  26.         $user $token->getUser();
  27.         if (!$user instanceof User) {
  28.             return false;
  29.         }
  30.         if ($user->isMasterAdmin()) {
  31.             return true;
  32.         }
  33.         switch ($attribute) {
  34.             case self::CREATE:
  35.                 return $this->canCreate($user$subject);
  36.             case self::EDIT:
  37.             case self::DELETE:
  38.                 return $this->canEditOrDelete($user$subject);
  39.         }
  40.         return false;
  41.     }
  42.     private function canCreate(User $userActionPlan $actionPlan): bool
  43.     {
  44.         if (!$actionPlan->getSite()) {
  45.             return false;
  46.         }
  47.         $actionPlanSiteId $actionPlan->getSite()->getId();
  48.         $userHasAccess false;
  49.         foreach ($user->getUserSites() as $userSite) {
  50.             if ($userSite->getSite()->getId() === $actionPlanSiteId) {
  51.                 $userHasAccess true;
  52.                 break;
  53.             }
  54.         }
  55.         return $userHasAccess;
  56.     }
  57.     private function canEditOrDelete(User $userActionPlan $actionPlan): bool
  58.     {
  59.         if (!$actionPlan->getSite()) {
  60.             return false;
  61.         }
  62.         $actionPlanSiteId $actionPlan->getSite()->getId();
  63.         $userHasAccess false;
  64.         // Check if user is associated with the action plan's site
  65.         foreach ($user->getUserSites() as $userSite) {
  66.             if ($userSite->getSite()->getId() === $actionPlanSiteId) {
  67.                 $userHasAccess true;
  68.                 break;
  69.             }
  70.         }
  71.         return $userHasAccess;
  72.     }
  73. }