src/Security/Voter/ProjectVoter.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Absence;
  4. use App\Entity\Project;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. /**
  11.  * Class AbsenceVoter
  12.  *
  13.  * @package App\Security\Voter
  14.  * @author Lukasz Krakowiak <lukasz94krakowiak@gmail.com>
  15.  */
  16. class ProjectVoter extends Voter
  17. {
  18.     const CAN_SHOW_PROJECT "CAN_SHOW_PROJECT";
  19.     /**
  20.      * @var Security
  21.      */
  22.     private Security $security;
  23.     /**
  24.      * @param Security $security
  25.      */
  26.     public function __construct(Security $security)
  27.     {
  28.         $this->security $security;
  29.     }
  30.     /**
  31.      * @param string $attribute
  32.      * @param $subject
  33.      * @return bool
  34.      */
  35.     protected function supports(string $attribute$subject): bool
  36.     {
  37.         if(!$subject instanceof Project) {
  38.             return false;
  39.         }
  40.         if (!in_array($attribute, [self::CAN_SHOW_PROJECT])) {
  41.             return false;
  42.         }
  43.         return true;
  44.     }
  45.     /**
  46.      * @param string $attribute
  47.      * @param $subject
  48.      * @param TokenInterface $token
  49.      * @return bool
  50.      */
  51.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  52.     {
  53.         $user $token->getUser();
  54.         if (!$user instanceof UserInterface) {
  55.             return false;
  56.         }
  57.         switch ($attribute) {
  58.             case self::CAN_SHOW_PROJECT:
  59.                 return $this->canShowProject($user$subject);
  60.         }
  61.         return false;
  62.     }
  63.     /**
  64.      * @param User|UserInterface $user
  65.      * @param Project            $project
  66.      *
  67.      * @return bool
  68.      */
  69.     private function canShowProject(User $userProject $project): bool
  70.     {
  71.         return $this->isAdminOrOwner($user$project);
  72.     }
  73.     /**
  74.      * @param User    $user
  75.      * @param Project $project
  76.      *
  77.      * @return bool
  78.      */
  79.     private function isAdminOrOwner(User $userProject $project): bool
  80.     {
  81.         if ($this->security->isGranted("ROLE_ADMIN") || $this->security->isGranted("ROLE_EMPLOYER")) {
  82.             return true;
  83.         }
  84.         if($project->getClient()->contains($user)) {
  85.             return true;
  86.         }
  87.         return false;
  88.     }
  89. }