src/Security/Voter/TaskVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use App\Entity\Accessmeister\User;
  6. use App\Entity\Taskmeister\Task;
  7. class TaskVoter extends Voter
  8. {
  9.     private const VIEW 'view';
  10.     private const EDIT 'edit';
  11.     protected function supports(string $attribute$subject): bool
  12.     {
  13.         return in_array($attribute, [self::VIEWself::EDIT])
  14.             && $subject instanceof Task;
  15.     }
  16.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  17.     {
  18.         /**
  19.          * @var Task $subject
  20.          */
  21.         $user $token->getUser();
  22.         // if the user is anonymous, do not grant access
  23.         if (!$user instanceof User) {
  24.             return false;
  25.         }
  26.         $task $subject;
  27.         switch ($attribute) {
  28.             case self::VIEW:
  29.                 return $this->canView($task$user);
  30.             case self::EDIT:
  31.                 return $this->canEdit($task$user);
  32.         }
  33.         return false;
  34.     }
  35.     // TODO: This doesn't account for subcompanies and other complexities.
  36.     //       Go through main.php 'case "task_edit":' and 'case "task_view"'
  37.     //       and create correct voting logic here.
  38.     private function canView(Task $taskUser $user): bool
  39.     {
  40.         // If they can edit, they can view
  41.         if ($this->canEdit($task$user)) {
  42.             return true;
  43.         }
  44.         return $user->getCompany() === $subject->getCompany();
  45.     }
  46.     private function canEdit(Task $taskUser $user): bool
  47.     {
  48.         if (
  49.             $user === $task->getAssignedToUser()
  50.             || $user === $task->getAssignedByUser()
  51.         ) {
  52.             return true;
  53.         }
  54.         return false;
  55.     }
  56. }