src/Security/Voter/NewsVoter.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 NewsVoter 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_NEWS''CAN_ADD_NEWS']);
  26.     }
  27.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  28.     {
  29.         $user $token->getUser();
  30.         // if the user is anonymous, do not grant access
  31.         if (!$user instanceof UserInterface) {
  32.             return false;
  33.         }
  34.         // ... (check conditions and return true to grant permission) ...
  35.         switch ($attribute) {
  36.             case 'CAN_EDIT_NEWS':
  37.                 if (!$subject instanceof \App\Entity\Actualitecabinet) {
  38.                     return false;
  39.                 }
  40.                 if ($this->security->isGranted('ROLE_ADMIN')) {
  41.                     return true;
  42.                 }
  43.                 return $user->getAccountingFirm() === $subject->getAccountingFirm();
  44.                 case 'CAN_ADD_NEWS':
  45.                     return true;
  46.         }
  47.         return false;
  48.     }
  49. }