src/Security/Voter/AdminUserVoter.php line 12

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