src/Security/Voter/Customer/EventVoter.php line 12

  1. <?php
  2. namespace App\Security\Voter\Customer;
  3. use App\Entity\Customer\Event;
  4. use App\Entity\Admin\CustomerUser;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Bundle\SecurityBundle\Security;
  9. class EventVoter extends Voter
  10. {
  11.     final public const EDIT   'EVENT_ENTITY_EDIT';
  12.     final public const VIEW   'EVENT_ENTITY_VIEW';
  13.     final public const DELETE 'EVENT_ENTITY_DELETE';
  14.     
  15.     public function __construct(
  16.             private readonly Security $security)
  17.     {
  18.     }
  19.     
  20.     protected function supports(string $attributemixed $subject): bool
  21.     {
  22.         if(!in_array($attribute, [self::EDITself::VIEW])){
  23.             return false;
  24.         }
  25.         return $subject instanceof Event;
  26.     }
  27.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  28.     {
  29.         $user $token->getUser();
  30.         // if the user is anonymous, do not grant access
  31.         if (!$user instanceof UserInterface) {
  32.             return false;
  33.         }
  34.         
  35.         if (!$this->security->isGranted('ROLE_STAFF')){
  36.             return false;
  37.         }
  38.         
  39.         return match($attribute) {
  40.             self::VIEW => $this->canView($subject$user),
  41.             self::EDIT => $this->canEdit(),
  42.             self::DELETE => $this->canDelete(),
  43.             default => throw new \LogicException('This code should not be reached!')
  44.         };
  45.     }
  46.     
  47.     private function canView(Event $entityCustomerUser $user): bool
  48.     {
  49.         $participants $entity->getInvites();
  50.         
  51.         foreach($participants as $participant){
  52.             if($participant->getStaff()->getId() == $user->getStaff()){
  53.                 return true;
  54.             }
  55.         }
  56.         return false;
  57.     }
  58.     private function canEdit(): bool
  59.     {
  60.         return $this->security->isGranted('ROLE_ADMIN');
  61.     }
  62.     
  63.     private function canDelete(): bool
  64.     {
  65.         if ($this->security->isGranted('ROLE_ADMIN')) {
  66.             return true;
  67.         }
  68.         
  69.         return false;
  70.     }
  71. }