src/Security/Voter/AppVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Helper\PermissionsHandlerInterface;
  5. use App\Repository\UserRepository;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class AppVoter extends Voter
  10. {
  11.     /**
  12.      * @var UserRepository
  13.      */
  14.     protected UserRepository $userRepository;
  15.     /**
  16.      * @var PermissionsHandlerInterface
  17.      */
  18.     protected PermissionsHandlerInterface $permissionsHandler;
  19.     /**
  20.      * @var User|null
  21.      */
  22.     protected $loggedUser;
  23.     /**
  24.      * @var array
  25.      */
  26.     protected $permissions;
  27.     public function __construct(
  28.         UserRepository $userRepository,
  29.         PermissionsHandlerInterface $permissionsHandler,
  30.         Security $security
  31.     ) {
  32.         $this->userRepository $userRepository;
  33.         $this->permissionsHandler $permissionsHandler;
  34.         $this->permissions array_keys($permissionsHandler->getPermissions());
  35.         $this->loggedUser $security->getUser();
  36.     }
  37.     protected function supports($attribute$subject)
  38.     {
  39.         if (!empty($this->loggedUser) && in_array('ROLE_ADMIN'$this->loggedUser->getRoles())) {
  40.             return true;
  41.         }
  42.         return in_array(strtoupper($attribute), $this->permissions);
  43.     }
  44.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  45.     {
  46.         if (!empty($this->loggedUser) && in_array('ROLE_ADMIN'$this->loggedUser->getRoles())) {
  47.             return true;
  48.         }
  49.         $attribute strtoupper($attribute);
  50.         if (empty($this->loggedUser) || !in_array($attribute$this->permissions)) {
  51.             return false;
  52.         }
  53.         $user $this->userRepository->findOneBy(['email' => $this->loggedUser->getUsername()]);
  54.         return $user->getRole()->hasPermission($attribute);
  55.     }
  56. }