src/Security/Voter/UserVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Task;
  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\UserInterface;
  9. class UserVoter extends Voter
  10. {
  11.     const USER_CAN_EDIT_TASK "USER_CAN_EDIT_TASK";
  12.     /**
  13.      * @var Security
  14.      */
  15.     private $security;
  16.     /**
  17.      * @param Security $security
  18.      */
  19.     public function __construct(Security $security)
  20.     {
  21.         $this->security $security;
  22.     }
  23.     /**
  24.      * @param string $attribute
  25.      * @param $subject
  26.      * @return bool
  27.      */
  28.     protected function supports(string $attribute$subject): bool
  29.     {
  30.         if(!$subject instanceof Task) {
  31.             return false;
  32.         }
  33.         if (!in_array($attribute, [self::USER_CAN_EDIT_TASK])) {
  34.             return false;
  35.         }
  36.         return true;
  37.     }
  38.     /**
  39.      * @param string $attribute
  40.      * @param $subject
  41.      * @param TokenInterface $token
  42.      * @return bool
  43.      */
  44.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  45.     {
  46.         $user $token->getUser();
  47.         if (!$user instanceof UserInterface) {
  48.             return false;
  49.         }
  50.         switch ($attribute) {
  51.             case self::USER_CAN_EDIT_TASK:
  52.                 return $this->canEditTask($user$subject);
  53.                 break;
  54.         }
  55.         return false;
  56.     }
  57.     /**
  58.      * @param User|UserInterface $user
  59.      * @param Task $task
  60.      * @return bool
  61.      */
  62.     private function canEditTask(User $userTask $task): bool
  63.     {
  64.         if ($this->security->isGranted("ROLE_ADMIN")) {
  65.             return true;
  66.         }
  67.         foreach($task->getUsers() as $taskUser) {
  68.             if ($user === $taskUser) {
  69.                 return true;
  70.             }
  71.         }
  72.         return false;
  73.     }
  74. }