src/Security/Voter/UserVoter.php line 11

  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Enum\Admin\RolesEnum;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class UserVoter extends Voter
  9. {
  10.     public const EDIT 'USER_EDIT';
  11.     public const VIEW 'USER_VIEW';
  12.     /**
  13.      * @param string $attribute
  14.      * @param mixed $subject
  15.      * @return bool
  16.      */
  17.     protected function supports(string $attributemixed $subject): bool
  18.     {
  19.         return in_array($attribute, [self::EDITself::VIEW])
  20.             && $subject instanceof User;
  21.     }
  22.     /**
  23.      * @param string $attribute
  24.      * @param mixed $subject
  25.      * @param TokenInterface $token
  26.      * @return bool
  27.      */
  28.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  29.     {
  30.         $user $token->getUser();
  31.         // if the user is anonymous, do not grant access
  32.         if (!$user instanceof UserInterface) {
  33.             return false;
  34.         }
  35.         if (!$subject instanceof User) {
  36.             return false;
  37.         }
  38.         switch ($attribute) {
  39.             case self::EDIT:
  40.                 if (in_array(RolesEnum::ROLE_SUPER_ADMIN->name$user->getRoles(), true)) {
  41.                     return true;
  42.                 }
  43.                 if (in_array(RolesEnum::ROLE_ADMIN->name$user->getRoles(), true)
  44.                     && !in_array(RolesEnum::ROLE_SUPER_ADMIN->name$subject->getRoles(), true)) {
  45.                     return true;
  46.                 }
  47.                 break;
  48.             case self::VIEW:
  49.                 return in_array(RolesEnum::ROLE_SUPER_ADMIN->name$user->getRoles(), true)
  50.                     || in_array(RolesEnum::ROLE_ADMIN->name$user->getRoles(), true);
  51.         }
  52.         return false;
  53.     }
  54. }