src/Security/Voter/UserRoleVoter.php line 13

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\User;
  5. use App\Enum\BaseRoleEnum;
  6. use App\Enum\RoleEnum;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. final class UserRoleVoter extends Voter
  10. {
  11.     private const ROLE_ADMIN BaseRoleEnum::ROLE_ADMIN;
  12.     private const EXTERNAL_PARTNER RoleEnum::EXTERNAL_PARTNER;
  13.     private const EXTERNAL_STAKEHOLDER RoleEnum::EXTERNAL_STAKEHOLDER;
  14.     private const GENERAL_MANAGER RoleEnum::GENERAL_MANAGER;
  15.     private const PROJECT_EMPLOYEE RoleEnum::PROJECT_EMPLOYEE;
  16.     private const PROJECT_MANAGER RoleEnum::PROJECT_MANAGER;
  17.     protected function supports(string $attribute$subject): bool
  18.     {
  19.         return in_array($attribute,
  20.             [
  21.                 self::EXTERNAL_PARTNER,
  22.                 self::EXTERNAL_STAKEHOLDER,
  23.                 self::GENERAL_MANAGER,
  24.                 self::PROJECT_EMPLOYEE,
  25.                 self::PROJECT_MANAGER
  26.             ]
  27.         );
  28.     }
  29.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  30.     {
  31.         /** @var ?User $loggedUser */
  32.         $loggedUser $token->getUser();
  33.         if (!$loggedUser) {
  34.             return false;
  35.         }
  36.         if (in_array(self::ROLE_ADMIN$loggedUser->getRoles())) {
  37.             return false;
  38.         }
  39.         $currentRole $loggedUser
  40.             ->getCurrentRoleInstitution()
  41.             ->getRole()
  42.             ->getKeyName();
  43.         return $attribute === $currentRole;
  44.     }
  45. }