src/Security/EmployeeVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Employee;
  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\Security;
  8. use Symfony\Component\Security\Core\User\InMemoryUser;
  9. use Symfony\Component\Security\Core\User\UserCheckerInterface;
  10. class EmployeeVoter extends Voter
  11. {
  12.     // these strings are just invented: you can use anything
  13.     const VIEW 'view';
  14.     private $security;
  15.     public function __construct(Security $security)
  16.     {
  17.         $this->security $security;
  18.     }
  19.     /**
  20.      * @inheritDoc
  21.      */
  22.     protected function supports(string $attribute$subject)
  23.     {
  24.         // if the attribute isn't one we support, return false
  25.         if (!in_array($attribute, [self::VIEW]))
  26.             return false;
  27.         // only vote on `Post` objects
  28.         if (!$subject instanceof Employee)
  29.             return false;
  30.         return true;
  31.     }
  32.     /**
  33.      * @inheritDoc
  34.      */
  35.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token)
  36.     {
  37.         if ($this->security->isGranted('ROLE_SUPER_ADMIN'))
  38.             return true;
  39.         if ($this->security->isGranted('ROLE_ADMIN'))
  40.             return true;
  41.         /** @var User $user */
  42.         $user $token->getUser();
  43.         if (!$user instanceof User)
  44.             return false;
  45.         // you know $subject is a Post object, thanks to `supports()`
  46.         /** @var Employee $employee */
  47.         $employee $subject;
  48.         switch ($attribute) {
  49.             case self::VIEW:
  50.                 $userVisiblitaUnitaOrganizzativa $user->getVisibilitaUnitaOrganizzativa();
  51.                 $employeeAttualeUnitaOrganizzativa $employee->getAttualeUnitaOrganizzativa();
  52.                 if (str_contains($employeeAttualeUnitaOrganizzativa$userVisiblitaUnitaOrganizzativa))
  53.                     return true;
  54.                 return false;
  55.         }
  56.         throw new \LogicException('This code should not be reached!');
  57.     }
  58. }