src/Security/Voter/ParentVoter.php line 11

  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Enum\RoleType;
  4. use Symfony\Bundle\SecurityBundle\Security;
  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 ParentVoter extends Voter
  9. {
  10.     public const EDIT 'PARENT_EDIT';
  11.     public const SHOW 'PARENT_SHOW';
  12.     private $security;
  13.     public function __construct(Security $security)
  14.     {
  15.         $this->security $security;
  16.     }
  17.     protected function supports(string $attributemixed $subject): bool
  18.     {
  19.         return in_array($attribute, [self::EDITself::SHOW]);
  20.     }
  21.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         // if the user is anonymous, do not grant access
  25.         if (!$user instanceof UserInterface) {
  26.             return false;
  27.         }
  28.         $accessIsGranted = match ($attribute) {
  29.             'PARENT_SHOW' =>
  30.                 $user->getId() === $subject['user_id']
  31.                 ||
  32.                 $this->security->isGranted(RoleType::ROLE_EMPLOYEE) ||
  33.                 $this->security->isGranted(RoleType::ROLE_PEDAGOGICAL_DIRECTOR),
  34.             'PARENT_EDIT' =>
  35.                 $user === $subject->getUser()
  36.                 ||
  37.                 $this->security->isGranted('ROLE_ADMIN'),
  38.         };
  39.         return $accessIsGranted;
  40.     }
  41. }