src/Security/Voter/AdminUserVoter.php line 11

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 AdminUserVoter extends Voter
  9. {
  10.     const CREATE 'CREATE';
  11.     private Security $security;
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     protected function supports(string $attribute$subject): bool
  17.     {
  18.         return in_array($attribute, ['OWN_USER_EDIT']);
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         // if the user is anonymous, do not grant access
  24.         if (!$user instanceof UserInterface) {
  25.             return false;
  26.         }
  27.         //this causes error in Create User
  28. //        if (!$subject instanceof User) {
  29. //            throw new \LogicException('Subject is not an instance of User?');
  30. //        }
  31.         // ... (check conditions and return true to grant permission) ...
  32.         switch ($attribute) {
  33.             case 'OWN_USER_EDIT':
  34.                 return $user === $subject || $this->security->isGranted('ROLE_ADMIN_USER');
  35.         }
  36.         return false;
  37.     }
  38. }