src/Security/Voter/UserVoter.php line 12

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\User;
  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. class UserVoter extends Voter
  9. {
  10.     private const ATTRIBUTES = ['READ''UPDATE''DELETE'];
  11.     private Security $security;
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     /**
  17.      * @param mixed $subject
  18.      * @return bool
  19.      */
  20.     protected function supports(string $attribute$subject)
  21.     {
  22.         return ($subject instanceof User);
  23.     }
  24.     /**
  25.      * @param User $subject
  26.      * @return bool
  27.      */
  28.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token)
  29.     {
  30.         if (!in_array($attributeself::ATTRIBUTEStrue)) {
  31.             return false;
  32.         }
  33.         /** @var User $currentUser */
  34.         $currentUser $token->getUser();
  35.         if (!$currentUser instanceof User) {
  36.             return false;
  37.         }
  38.         return (
  39.             $attribute === 'READ'
  40.             || $subject->getId() === $currentUser->getId()
  41.             || $this->security->isGranted('ROLE_ADMIN')
  42.         );
  43.     }
  44. }