src/Security/Voter/BoardVoter.php line 10

  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\User\UserInterface;
  6. use Symfony\Component\Security\Core\Security;
  7. class BoardVoter extends Voter
  8. {
  9.     private $security;
  10.     public function __construct(Security $security)
  11.     {
  12.         $this->security $security;
  13.     }
  14.     public const EDIT 'BOARD_EDIT';
  15.     public const VIEW 'BOARD_DELETE';
  16.     public const LIST = 'BOARD_LIST';
  17.     protected function supports(string $attribute$subject): bool
  18.     {
  19.         // replace with your own logic
  20.         // https://symfony.com/doc/current/security/voters.html
  21.         return in_array($attribute, [self::EDITself::VIEWself::LIST])
  22.             && $subject instanceof \App\Entity\Board;
  23.     }
  24.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  25.     {
  26.         if ($this->security->isGranted('ROLE_ADMIN')) {
  27.             return true;
  28.         }
  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 self::EDIT:
  38.                 // logic to determine if the user can EDIT
  39.                 // return true or false
  40.                 break;
  41.             case self::VIEW:
  42.                 // logic to determine if the user can VIEW
  43.                 // return true or false
  44.                 break;
  45.             case self::LIST:
  46.                 // logic to determine if the user can VIEW
  47.                 // return true or false
  48.                 break;
  49.         }
  50.         return false;
  51.     }
  52. }