src/AppBundle/Security/Voter/HolidayVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Security\Voter;
  3. use AppBundle\Entity\Customer;
  4. use AppBundle\Entity\Holiday;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class HolidayVoter extends Voter
  9. {
  10.     // these consts are the action that are voted on
  11.     public const EDIT 'edit';
  12.     private $decisionManager;
  13.     public function __construct(AccessDecisionManagerInterface $decisionManager)
  14.     {
  15.         $this->decisionManager $decisionManager;
  16.     }
  17.     protected function supports($attribute$subject)
  18.     {
  19.         // if the attribute isn't one we support, return false
  20.         if (!in_array($attribute, [self::EDIT])) {
  21.             return false;
  22.         }
  23.         // only vote on Holiday objects inside this voter
  24.         if (!$subject instanceof Holiday) {
  25.             return false;
  26.         }
  27.         return true;
  28.     }
  29.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  30.     {
  31.         $customer $token->getUser();
  32.         if (!$customer instanceof Customer) {
  33.             // the customer must be logged in; if not, deny access
  34.             return false;
  35.         }
  36.         // you know $subject is a Holiday object, thanks to supports
  37.         /** @var Holiday $holiday */
  38.         $holiday $subject;
  39.         switch ($attribute) {
  40.             case self::EDIT:
  41.                 return $this->canEdit($holiday$customer$token);
  42.         }
  43.         throw new \LogicException('This code should not be reached!');
  44.     }
  45.     private function canEdit(Holiday $holidayCustomer $customerTokenInterface $token)
  46.     {
  47.         // check if the customer is a admin
  48.         if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) {
  49.             return true;
  50.         }
  51.         return false;
  52.     }
  53. }