src/Security/Voter/ResourceAccessVoter.php line 11

  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authorization\Voter\Voter,
  4.     Symfony\Component\Security\Core\Role\RoleHierarchyInterface,
  5.     Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use App\Lib\Roles,
  7.     App\Entity\Admin;
  8. final class ResourceAccessVoter extends Voter
  9. {
  10.     private RoleHierarchyInterface $roleHierarchy;
  11.     public function __construct(RoleHierarchyInterface $roleHierarchy)
  12.     {
  13.         $this->roleHierarchy $roleHierarchy;
  14.     }
  15.     protected function supports($attribute$subject): bool
  16.     {
  17.         if ($attribute && str_starts_with($attribute'App')) {
  18.             return true;
  19.         }
  20.         return false;
  21.     }
  22.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  23.     {
  24.         /** @var Admin */
  25.         $admin $token->getUser();
  26.         if ($admin->getIsPasswordResetRequired()) {
  27.             return false;
  28.         }
  29.         $accessable array_intersect(
  30.             $this->getRoles($admin),
  31.             [Roles::ROLE_SUPER_ADMIN$attribute]
  32.         );
  33.         if (count($accessable) < 1) {
  34.             return false;
  35.         }
  36.         return true;
  37.     }
  38.     private function getRoles(Admin $admin): array
  39.     {
  40.         return $this->roleHierarchy->getReachableRoleNames($admin->getRoles());
  41.     }
  42. }