src/Security/Voter/ProjectListVoter.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 ProjectListVoter
  12.  *
  13.  * @package App\Security\Voter
  14.  * @author Lukasz Krakowiak <lukasz94krakowiak@gmail.com>
  15.  */
  16. class ProjectListVoter extends Voter
  17. {
  18.     const CAN_SHOW_PROJECT_LIST "CAN_SHOW_LIST";
  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) {
  38.             return true;
  39.         }
  40.         if(!$subject instanceof Project) {
  41.             return false;
  42.         }
  43.         if (!in_array($attribute, [self::CAN_SHOW_PROJECT_LIST])) {
  44.             return false;
  45.         }
  46.         return true;
  47.     }
  48.     /**
  49.      * @param string $attribute
  50.      * @param $subject
  51.      * @param TokenInterface $token
  52.      * @return bool
  53.      */
  54.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  55.     {
  56.         $user $token->getUser();
  57.         if (!$user instanceof UserInterface) {
  58.             return false;
  59.         }
  60.         switch ($attribute) {
  61.             case self::CAN_SHOW_PROJECT_LIST:
  62.                 return $this->canShowProjectList($user$subject);
  63.         }
  64.         return false;
  65.     }
  66.     /**
  67.      * @param User|UserInterface $user
  68.      * @param Project            $project
  69.      *
  70.      * @return bool
  71.      */
  72.     private function canShowProjectList(User $user, ?Project $project): bool
  73.     {
  74.         return $this->isAdminOrOwner($user$project);
  75.     }
  76.     /**
  77.      * @param User    $user
  78.      * @param Project $project
  79.      *
  80.      * @return bool
  81.      */
  82.     private function isAdminOrOwner(User $user, ?Project $project): bool
  83.     {
  84.         if ($this->security->isGranted("ROLE_ADMIN")) {
  85.             return true;
  86.         }
  87.         if(in_array($user->getId(), [211,365,366,364])) {
  88.             return true;
  89.         }
  90.         return false;
  91.     }
  92. }