src/Security/Voter/GuardianVoter.php line 13

  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Guardian;
  4. use App\Repository\GuardianRepository;
  5. use Doctrine\ORM\NonUniqueResultException;
  6. use Symfony\Bundle\SecurityBundle\Security;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class GuardianVoter extends Voter
  11. {
  12.     public const EDIT 'GUARDIAN_EDIT';
  13.     public const SHOW 'GUARDIAN_SHOW';
  14.     public const DELETE 'GUARDIAN_DELETE';
  15.     private $security;
  16.     public function __construct(Security $security)
  17.     {
  18.         $this->security $security;
  19.     }
  20.     protected function supports(string $attributemixed $subject): bool
  21.     {
  22.         return in_array($attribute, [self::EDITself::SHOWself::DELETE]);
  23.     }
  24.     /**
  25.      * @param string $attribute
  26.      * @param Guardian $subject
  27.      * @param TokenInterface $token
  28.      * @return bool
  29.      * @throws NonUniqueResultException
  30.      */
  31.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  32.     {
  33.         $user $token->getUser();
  34.         // if the user is anonymous, do not grant access
  35.         if (!$user instanceof UserInterface) {
  36.             return false;
  37.         }
  38.         /**
  39.          * Checks if requesting User is the Guardian
  40.          * Admin has general access
  41.          */
  42.         $accessIsGranted = match ($attribute) {
  43.             'GUARDIAN_SHOW' =>
  44.                 $user->getId() === $subject['user_id']
  45.                 ||
  46.                 $this->security->isGranted('ROLE_ADMIN'),
  47.             'GUARDIAN_EDIT' =>
  48.                 $user === $subject->getUser()
  49.                 ||
  50.                 $this->security->isGranted('ROLE_ADMIN'),
  51.             'GUARDIAN_DELETE' => $this->security->isGranted('ROLE_ADMIN'),
  52.         };
  53.         return $accessIsGranted;
  54.     }
  55. }