src/Security/Voter/TeamVoter.php line 18

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\Team;
  5. use App\Entity\User;
  6. use App\Repository\TeamUserRepository;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. /**
  11.  * TEAM_MEMBER : l'utilisateur est inscrit dans la team (TeamUser), ou il est admin.
  12.  * TEAM_MANAGE : l'utilisateur est le compte de l'entreprise de la team (back-office manager), ou il est admin.
  13.  */
  14. class TeamVoter extends Voter
  15. {
  16.     public const MEMBER = 'TEAM_MEMBER';
  17.     public const MANAGE = 'TEAM_MANAGE';
  18.     private Security $security;
  19.     private TeamUserRepository $teamUserRepository;
  20.     public function __construct(Security $security, TeamUserRepository $teamUserRepository)
  21.     {
  22.         $this->security = $security;
  23.         $this->teamUserRepository = $teamUserRepository;
  24.     }
  25.     protected function supports(string $attribute, $subject): bool
  26.     {
  27.         return in_array($attribute, [self::MEMBER, self::MANAGE], true) && $subject instanceof Team;
  28.     }
  29.     /**
  30.      * @param Team $subject
  31.      */
  32.     protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  33.     {
  34.         if ($this->security->isGranted(User::ROLE_ADMIN)) {
  35.             return true;
  36.         }
  37.         $user = $token->getUser();
  38.         if (self::MANAGE === $attribute) {
  39.             return $this->security->isGranted(User::ROLE_COMPANY)
  40.                 && $user instanceof User
  41.                 && null !== $user->getCompany()
  42.                 && null !== $subject->getCompany()
  43.                 && $user->getCompany()->getId() === $subject->getCompany()->getId();
  44.         }
  45.         return $user instanceof User && null !== $this->teamUserRepository->findOneBy(['team' => $subject, 'user' => $user]);
  46.     }
  47. }