src/Security/Voter/AdminUserVoter.php line 11

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