src/Security/Voter/SurveyVoter.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 SurveyVoter extends Voter
  8. {
  9.     private $security;
  10.     public function __construct(Security $security)
  11.     {
  12.         $this->security $security;
  13.     }
  14.     protected function supports($attribute$subject): bool
  15.     {
  16.         // replace with your own logic
  17.         // https://symfony.com/doc/current/security/voters.html
  18.         return in_array($attribute, ['POST_EDIT''POST_VIEW'])
  19.             && $subject instanceof \App\Entity\Survey;
  20.     }
  21.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         // if the user is anonymous, do not grant access
  25.         if (!$user instanceof UserInterface) {
  26.             return false;
  27.         }
  28.         if($this->security->isGranted('ROLE_SUPERADMIN')) {
  29.             return true;
  30.         }
  31.         // ... (check conditions and return true to grant permission) ...
  32.         switch ($attribute) {
  33.             case 'POST_EDIT':
  34.                 // logic to determine if the user can EDIT
  35.                 // return true or false
  36.                 break;
  37.             case 'POST_VIEW':
  38.                 // logic to determine if the user can VIEW
  39.                 // return true or false
  40.                 break;
  41.         }
  42.         return false;
  43.     }
  44. }