src/Domain/User/Voter/UserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Domain\User\Voter;
  3. use App\Domain\Application\Voter\AbstractVoter;
  4. use App\Domain\User\Entity\User;
  5. use App\Domain\User\Security\RoleChecker;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Security;
  8. class UserVoter extends AbstractVoter
  9. {
  10.     public const VIEW 'view';
  11.     public const EDIT 'edit';
  12.     public const DELETE 'delete';
  13.     public function __construct(
  14.         Security $security,
  15.         private readonly RoleChecker $roleChecker,
  16.     ) {
  17.         parent::__construct($security);
  18.     }
  19.     public function supportsType(string $subjectType): bool
  20.     {
  21.         return is_a($subjectTypeUser::class, true);
  22.     }
  23.     public function supportsAttribute(string $attribute): bool
  24.     {
  25.         return \in_array($attribute, [
  26.             self::VIEW,
  27.             self::EDIT,
  28.             self::DELETE,
  29.         ]);
  30.     }
  31.     /**
  32.      * @param User $subject
  33.      */
  34.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  35.     {
  36.         $user $token->getUser();
  37.         if (!$user instanceof User) {
  38.             return false;
  39.         }
  40.         return match ($attribute) {
  41.             self::VIEW => $this->canView($user$subject),
  42.             self::EDIT => $this->canEdit($user$subject),
  43.             self::DELETE => $this->canDelete($user$subject),
  44.             default => false,
  45.         };
  46.     }
  47.     private function canView(User $userUser $subject): bool
  48.     {
  49.         return true;
  50.     }
  51.     private function canEdit(User $userUser $subject): bool
  52.     {
  53.         if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
  54.             return true;
  55.         }
  56.         if ($this->roleChecker->isGranted($subjectUser::ROLE_SUPER_ADMIN) && $user !== $subject) {
  57.             return false;
  58.         }
  59.         return true;
  60.     }
  61.     private function canDelete(User $userUser $subject): bool
  62.     {
  63.         return $this->security->isGranted(User::ROLE_SUPER_ADMIN)
  64.             && !$this->roleChecker->isGranted($subjectUser::ROLE_SUPER_ADMIN);
  65.     }
  66. }