src/Security/Voter/CandidateVoter.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\AbstractCollaborator;
  4. use App\Entity\Candidate;
  5. use App\Entity\Agent;
  6. use Exception;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. /**
  12.  * @package App\Security\Voter
  13.  * @class CandidateVoter
  14.  *
  15.  */
  16. class CandidateVoter extends Voter
  17. {
  18.     public const POST 'POST';
  19.     public const PUT 'PUT';
  20.     public const GET 'GET';
  21.     public const STATUS 'STATUS';
  22.     /**
  23.      * @var Security
  24.      */
  25.     private Security $security;
  26.     /**
  27.      * @param Security $security
  28.      */
  29.     public function __construct(Security $security)
  30.     {
  31.         $this->security $security;
  32.     }
  33.     /**
  34.      * @param string $attribute
  35.      * @param mixed $subject
  36.      * @return bool
  37.      */
  38.     protected function supports(string $attribute$subject): bool
  39.     {
  40.         return in_array($attribute, [self::POSTself::PUT,self::GET,self::STATUS], true) && $subject instanceof Candidate;
  41.     }
  42.     /**
  43.      * @throws Exception
  44.      */
  45.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  46.     {
  47.         /** @var UserInterface $user */
  48.         $user $token->getUser();
  49.         // Deny anonymous users
  50.         if (!$user instanceof UserInterface) {
  51.             return false;
  52.         }
  53.         /** @var Candidate $subject */
  54.         switch ($attribute) {
  55.             case self::STATUS:
  56.             case self::GET:
  57.                 if ($this->security->isGranted(AbstractCollaborator::ROLE_MANAGER) || $this->security->isGranted(AbstractCollaborator::ROLE_AGENT)) {
  58.                     return true;
  59.                 }
  60.                 break;
  61.             case self::PUT:
  62.                 if ($subject->getSponsor() === $user) {
  63.                     return true;
  64.                 }
  65.                 break;
  66.             case self::POST:
  67.                 if ($this->security->isGranted(AbstractCollaborator::ROLE_AGENT)) {
  68.                     return true;
  69.                 }
  70.                 return false;
  71.         }
  72.         throw new Exception(sprintf('Unhandled attribute "%s"'$attribute));
  73.     }
  74. }