src/Security/Voter/EmailingVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\Security;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class EmailingVoter extends Voter
  8. {
  9.     /**
  10.      * @var Security
  11.      */
  12.     private $security;
  13.     /**
  14.      * EmailingVoter constructor.
  15.      * @param Security $security
  16.      */
  17.     public function __construct(Security $security)
  18.     {
  19.         $this->security $security;
  20.     }
  21.     protected function supports(string $attribute$subject): bool
  22.     {
  23.         // replace with your own logic
  24.         // https://symfony.com/doc/current/security/voters.html
  25.         return in_array($attribute, ['CAN_EDIT_EMAILING'])
  26.             && $subject instanceof \App\Entity\Emailing;
  27.     }
  28.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  29.     {
  30.         $user $token->getUser();
  31.         // if the user is anonymous, do not grant access
  32.         if (!$user instanceof UserInterface) {
  33.             return false;
  34.         }
  35.         // ... (check conditions and return true to grant permission) ...
  36.         switch ($attribute) {
  37.             case 'CAN_EDIT_EMAILING':
  38.                 if ($this->security->isGranted('ROLE_ADMIN')) {
  39.                     return true;
  40.                 }
  41.                 return $user->getAccountingFirm() === $subject->getAccountingFirm();
  42.         }
  43.         return false;
  44.     }
  45. }