src/Security/UserVoter.php line 12

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security;
  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. use Symfony\Contracts\Service\Attribute\Required;
  9. class UserVoter extends Voter{
  10.     const EDIT 'edit';
  11.     #[Required]
  12.     public Security $security;
  13.     protected function supports(string $attributemixed $subject): bool
  14.     {
  15.         // if the attribute isn't one we support, return false
  16.         if (!in_array($attribute, [self::EDIT])) {
  17.             return false;
  18.         }
  19.         // only vote on `User` objects
  20.         if (!$subject instanceof User) {
  21.             return false;
  22.         }
  23.         return true;
  24.     }
  25.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  26.     {
  27.         $userConnected $token->getUser();
  28.         if (!$userConnected instanceof User) {
  29.             return false;
  30.         }
  31.         /** @var User $user */
  32.         $user $subject;
  33.         switch ($attribute) {
  34.             case self::EDIT:
  35.                 return $this->canEdit($user$userConnected);
  36.         }
  37.         throw new \LogicException('This code should not be reached!');
  38.     }
  39.     private function canEdit(User $userUser $userConnected): bool
  40.     {
  41.         if($this->security->isGranted('ROLE_ADMIN')){
  42.             return true;
  43.         }
  44.         return false;
  45.     }
  46. }