src/AppBundle/Security/EntityActionsVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Security;
  3. use AppBundle\Entity\EntityActionsInterface;
  4. use AppBundle\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. /**
  9.  * Class EntityActionsVoter.
  10.  */
  11. class EntityActionsVoter extends Voter
  12. {
  13.     /**
  14.      * @var AuthorizationCheckerInterface
  15.      */
  16.     private $authorizationChecker;
  17.     /**
  18.      * EntityActionVoter constructor.
  19.      *
  20.      * @param AuthorizationCheckerInterface $authorizationChecker
  21.      */
  22.     public function __construct(AuthorizationCheckerInterface $authorizationChecker)
  23.     {
  24.         $this->authorizationChecker $authorizationChecker;
  25.     }
  26.     /**
  27.      * {@inheritdoc}
  28.      */
  29.     protected function supports($attribute$subject)
  30.     {
  31.         if (!in_array($attribute$this->getSupportedAttributes())) {
  32.             return false;
  33.         }
  34.         return $subject instanceof EntityActionsInterface;
  35.     }
  36.     /**
  37.      * {@inheritdoc}
  38.      * @param EntityActionsInterface $subject
  39.      */
  40.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  41.     {
  42.         $user $token->getUser();
  43.         if (!$user instanceof User) {
  44.             return false;
  45.         }
  46.         foreach ($subject->getDeleteActionRoles() as $role) {
  47.             if (!$this->authorizationChecker->isGranted($role$subject)) {
  48.                 return false;
  49.             }
  50.         }
  51.         return true;
  52.     }
  53.     /**
  54.      * @return array
  55.      */
  56.     private function getSupportedAttributes(): array
  57.     {
  58.         return [
  59.             EntityActionsInterface::DELETE_ACTION,
  60.         ];
  61.     }
  62. }