src/Security/Voter/PermissionVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Permission;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. use Symfony\Component\Security\Core\Security;
  10. class PermissionVoter extends Voter
  11. {
  12.     private $entityManager;
  13.     private $security;
  14.     public function __construct(EntityManagerInterface $entityManagerSecurity $security)
  15.     {
  16.         $this->entityManager $entityManager;
  17.         $this->security $security;
  18.     }
  19.     protected function supports($attribute$subject)
  20.     {
  21.         // replace with your own logic
  22.         // https://symfony.com/doc/current/security/voters.html
  23.         return $subject instanceof User;
  24.     }
  25.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  26.     {
  27.         $user $token->getUser();
  28.         // if the user is anonymous, do not grant access
  29.         if (!$user instanceof UserInterface) {
  30.             return false;
  31.         }
  32.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  33.              return true;
  34.         }
  35.         $permissionCount $this->entityManager->getRepository(Permission::class)->findUserPermissionsCount($attribute$subject);
  36.         return $permissionCount 0;
  37.     }
  38. }