src/Security/Voter/UserRoleVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Component\UserRole\Manager\UserRoleManager;
  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\User\UserInterface;
  8. class UserRoleVoter extends Voter
  9. {
  10.     private UserRoleManager $userRoleManager;
  11.     /**
  12.      * UserRoleVoter constructor.
  13.      */
  14.     public function __construct(UserRoleManager $userRoleManager)
  15.     {
  16.         $this->userRoleManager $userRoleManager;
  17.     }
  18.     protected function supports($attribute$subject): bool
  19.     {
  20.         if (=== mb_strpos($attribute'ROLE_')) {
  21.             return false;
  22.         }
  23.         return true;
  24.     }
  25.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  26.     {
  27.         /** @var User $user */
  28.         $user $token->getUser();
  29.         // if the user is anonymous, do not grant access
  30.         if (!$user instanceof UserInterface) {
  31.             return false;
  32.         }
  33.         if (!$token->hasAttribute('user_role_entries')) {
  34.             return false;
  35.         }
  36.         $roles $user->getUserRoles();
  37.         if (!\in_array($attributearray_keys($this->userRoleManager->getMasks()), true)) {
  38.             return false;
  39.         }
  40.         $entries $token->getAttribute('user_role_entries');
  41.         if (!\array_key_exists($subject$entries) || $entries[$subject] & $attribute) {
  42.             return true;
  43.         }
  44.         return false;
  45.     }
  46. }