src/Security/Voter/UserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class UserVoter extends Voter
  9. {
  10.     private $security;
  11.     public function __construct(Security $security)
  12.     {
  13.         $this->security $security;
  14.     }
  15.     protected function supports($attribute$subject)
  16.     {
  17.         return in_array($attribute, ['GET''EDIT'])
  18.             && $subject instanceof User;
  19.     }
  20.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  21.     {
  22.         $user $token->getUser();
  23.         // if the user is anonymous, do not grant access
  24.         if (!$user instanceof UserInterface) {
  25.             return false;
  26.         }
  27.         switch ($attribute) {
  28.             case 'GET':
  29.             case 'EDIT':
  30.                 if ($this->security->isGranted('ROLE_HR') || $this->security->isGranted('ROLE_PM') || $subject->getId() === $user->getId()) {
  31.                     return true;
  32.                 }
  33.                 break;
  34.         }
  35.         return false;
  36.     }
  37. }