src/Backoffice/Security/BackofficeFeatureVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Backoffice\Security;
  3. use App\Backoffice\Enum\BackofficeFeatureAccessEnum;
  4. use AppBundle\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. class BackofficeFeatureVoter extends Voter
  10. {
  11.     private EntityManagerInterface $em;
  12.     public function __construct(EntityManagerInterface $em)
  13.     {
  14.         $this->em $em;
  15.     }
  16.     protected function supports($attribute$subject): bool
  17.     {
  18.         return \in_array($attributeBackofficeFeatureAccessEnum::getChoices(), true);
  19.     }
  20.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         if ($token instanceof SwitchUserToken) {
  24.             $user $token->getOriginalToken()->getUser();
  25.         }
  26.         if (!$user instanceof User) {
  27.             return false;
  28.         }
  29.         // User hasn't data during a switch
  30.         $user $this->em->getRepository(User::class)->find($user->getId());
  31.         if ($user === null || $user->getBackofficeProfile() === null) {
  32.             return false;
  33.         }
  34.         return $user->getBackofficeProfile()->hasRole($attribute);
  35.     }
  36. }