src/Security/Voter/UserVoter.php line 8

Open in your IDE?
  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 UserVoter 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 the user is anonymous, do not grant access
  26.         if (!$user instanceof UserInterface) {
  27.             return false;
  28.         }
  29.         if (!$subject instanceof User) {
  30.             throw new \LogicException('Subject is not an instance of User?');
  31.         }
  32.         // ... (check conditions and return true to grant permission) ...
  33.         switch ($attribute) {
  34.             case 'ADMIN_USER_EDIT':
  35.                 return $user === $subject || $this->security->isGranted('ROLE_SUPER_ADMIN');;
  36.         }
  37.         return false;
  38.     }
  39. }