src/Security/Voter/UserRankVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Service\RoleRankService;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class UserRankVoter extends Voter
  8. {
  9.     public const VIEW 'VIEW';
  10.     public const EDIT 'EDIT';
  11.     public const DELETE 'DELETE';
  12.     public function __construct(private RoleRankService $roleRankService)
  13.     {
  14.     }
  15.     protected function supports(string $attributemixed $subject): bool
  16.     {
  17.         return \in_array($attribute, [self::VIEWself::EDITself::DELETE], true)
  18.             && $subject instanceof User;
  19.     }
  20.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         if (!$user instanceof User) {
  24.             return false;
  25.         }
  26.         if (\in_array(User::ROLE_SUPER_ADMIN$user->getRoles(), true)) {
  27.             return true;
  28.         }
  29.         /** @var User $target */
  30.         $target $subject;
  31.         return match ($attribute) {
  32.             self::VIEW => $this->roleRankService->canView($user$target),
  33.             self::EDIT => $this->roleRankService->canEdit($user$target),
  34.             self::DELETE => $this->roleRankService->canDelete($user$target),
  35.             default => false,
  36.         };
  37.     }
  38. }