src/ApiPlatform/Voter/AffectationVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\ApiPlatform\Voter;
  3. use App\Entity\Affectation;
  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 AffectationVoter 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 Affectation) {
  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.         
  30.         if ($user->isMasterAdmin()) {
  31.             return true;
  32.         }
  33.         
  34.         switch ($attribute) {
  35.             case self::CREATE:
  36.                 return $this->canCreate($user$subject);
  37.             case self::EDIT:
  38.             case self::DELETE:
  39.                 return $this->canEditOrDelete($user$subject);
  40.         }
  41.         return false;
  42.     }
  43.     private function canCreate(User $userAffectation $affectation): bool
  44.     {
  45.         if (!$affectation->getSite()) {
  46.             return false;
  47.         }
  48.         
  49.         $siteId $affectation->getSite()->getId();
  50.         $userHasAccess false;
  51.         
  52.         foreach ($user->getUserSites() as $userSite) {
  53.             if ($userSite->getSite()->getId() === $siteId) {
  54.                 $userHasAccess true;
  55.                 break;
  56.             }
  57.         }
  58.         
  59.         return $userHasAccess;
  60.     }
  61.     private function canEditOrDelete(User $userAffectation $affectation): bool
  62.     {
  63.         if (!$affectation->getSite()) {
  64.             return false;
  65.         }
  66.         
  67.         $siteId $affectation->getSite()->getId();
  68.         $userHasAccess false;
  69.         
  70.         foreach ($user->getUserSites() as $userSite) {
  71.             if ($userSite->getSite()->getId() === $siteId) {
  72.                 $userHasAccess true;
  73.                 break;
  74.             }
  75.         }
  76.         
  77.         return $userHasAccess;
  78.     }
  79. }