src/Security/Voter/ProfileVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\AbstractCollaborator;
  4. use Exception;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. class ProfileVoter extends Voter
  10. {
  11.     public const PROFILE_UPDATE 'PROFILE_UPDATE';
  12.     /**
  13.      * @var Security
  14.      */
  15.     private Security $security;
  16.     /**
  17.      * @param Security $security
  18.      */
  19.     public function __construct(Security $security)
  20.     {
  21.         $this->security $security;
  22.     }
  23.     /**
  24.      * @param string $attribute
  25.      * @param mixed $subject
  26.      * @return bool
  27.      */
  28.     protected function supports(string $attribute$subject): bool
  29.     {
  30.         return $attribute === self::PROFILE_UPDATE && $subject instanceof AbstractCollaborator;
  31.     }
  32.     /**
  33.      * @param string $attribute
  34.      * @param $subject
  35.      * @param TokenInterface $token
  36.      * @return bool
  37.      * @throws Exception
  38.      */
  39.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token)
  40.     {
  41.         /** @var UserInterface $user */
  42.         $user $token->getUser();
  43.         // Deny anonymous users
  44.         if (!$user instanceof UserInterface) {
  45.             return false;
  46.         }
  47.         /** @var AbstractCollaborator $subject */
  48.         if ($attribute == self::PROFILE_UPDATE) {
  49.             if ($subject->getUserIdentifier() === $user->getUserIdentifier() || $this->security->isGranted(AbstractCollaborator::ROLE_MANAGER)) {
  50.                 return true;
  51.             }
  52.             return false;
  53.         }
  54.         throw new Exception(sprintf('Unhandled attribute "%s"'$attribute));
  55.     }
  56. }