src/Security/Voter/AnimalVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\Security;
  6. class AnimalVoter extends Voter
  7. {
  8.     public const EDIT 'POST_EDIT';
  9.     public const VIEW 'POST_VIEW';
  10.     public const ADD 'POST_ADD';
  11.     public const DELETE 'POST_DELETE';
  12.     public function __construct( private readonly Security $security ) {}
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         return in_array($attribute, [self::EDITself::VIEWself::ADDself::DELETE])
  16.             && $subject instanceof \App\Entity\Animal;
  17.     }
  18.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  19.     {
  20.         $isMyOrganization $this->security->getUser()->getOrganization() == $subject->getOrganization();
  21.         if ($this->security->isGranted('ROLE_ADMIN'))
  22.             return true;
  23.         if ($this->security->isGranted('ROLE_MANAGER')) {
  24.             switch ( $attribute ) {
  25.                 case self::EDIT:
  26.                     return false;
  27.                 case self::VIEW:
  28.                 case self::DELETE:
  29.                      if ($isMyOrganization)
  30.                         return true;
  31.                 default:
  32.                     return true;
  33.             }
  34.         }
  35.         if ($this->security->isGranted('ROLE_USER')) {
  36.             switch ( $attribute ) {
  37.                 case self::VIEW:
  38.                     return true;
  39.                 default:
  40.                     return false;
  41.             }
  42.         }
  43.         return false;
  44.     }
  45. }