src/Security/Voter/NotificationReceiptVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\NotificationReceipt;
  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\User\UserInterface;
  8. class NotificationReceiptVoter extends Voter
  9. {
  10.     public const READ 'NOTIFICATION_RECEIPT_READ';
  11.     public const VIEW 'NOTIFICATION_RECEIPT_VIEW';
  12.     protected function supports(string $attributemixed $subject): bool
  13.     {
  14.         return in_array($attribute, [self::READself::VIEW])
  15.             && $subject instanceof NotificationReceipt;
  16.     }
  17.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  18.     {
  19.         /**
  20.          * @var User $user
  21.          */
  22.         $user $token->getUser();
  23.         // if the user is anonymous, do not grant access
  24.         if (!$user instanceof UserInterface) {
  25.             return false;
  26.         }
  27.         // ... (check conditions and return true to grant permission) ...
  28.         switch ($attribute) {
  29.             case self::READ:
  30.                 return $this->isUserTheReceiver($user$subject);
  31.             case self::VIEW:
  32.                 return $this->isUserTheReceiver($user$subject)
  33.                     || in_array('SUPER_ADMIN'$token->getRoleNames())
  34.                     ;
  35.         }
  36.         return false;
  37.     }
  38.     private function isUserTheReceiver(User $userNotificationReceipt $subject): bool
  39.     {
  40.         return $user->getId() === $subject->getUser()->getId();
  41.     }
  42. }