src/Security/Voter/ServiceVoter.php line 10

  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Admin\Parameter\Service;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class ServiceVoter extends Voter
  8. {
  9.     public const EDIT 'POST_EDIT';
  10.     public const VIEW 'POST_VIEW';
  11.     public const IS_RESPONSABLE 'IS_RESPONSABLE';
  12.     protected function supports(string $attributemixed $subject): bool
  13.     {
  14.         // IS_RESPONSABLE ne nĂ©cessite pas de $subject
  15.         if ($attribute === self::IS_RESPONSABLE) {
  16.             return true;
  17.         }
  18.         return in_array($attribute, [self::EDITself::VIEW])
  19.             && $subject instanceof Service;
  20.     }
  21.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         if (!$user instanceof UserInterface) {
  25.             return false;
  26.         }
  27.         if ($attribute === self::IS_RESPONSABLE) {
  28.             return $this->isResponsable($user);
  29.         }
  30.         if (!$subject instanceof Service) {
  31.             return false;
  32.         }
  33.         return match ($attribute) {
  34.             self::EDIT => $this->canEdit($subject$user),
  35.             self::VIEW => $this->canView($subject$user),
  36.             default => false,
  37.         };
  38.     }
  39.     private function canEdit(Service $serviceUserInterface $user): bool
  40.     {
  41.         return $user === $service->getUser();
  42.     }
  43.     private function canView(Service $serviceUserInterface $user): bool
  44.     {
  45.         return $this->canEdit($service$user) || $service->getUsers()->contains($user);
  46.     }
  47.     private function isResponsable(UserInterface $user): bool
  48.     {
  49.         return $user->getService() !== null && $user === $user->getService()->getUser();
  50.     }
  51. }