src/Security/Voter/Adherent/RegistrationVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\Adherent;
  3. use App\Entity\Registration;
  4. use App\Entity\User;
  5. use App\Repository\RegistrationRepository;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. class RegistrationVoter extends Voter
  10. {
  11.     public const EDIT 'edit';
  12.     public function __construct(private RegistrationRepository $repo)
  13.     {
  14.     }
  15.     protected function supports(string $attribute$subject): bool
  16.     {
  17.         return $attribute === self::EDIT
  18.             && $subject instanceof Registration;
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         if (!$user instanceof UserInterface) {
  24.             return false;
  25.         }
  26.         if ($attribute === self::EDIT) {
  27.             return $this->canAccess($user$subject);
  28.         }
  29.         return false;
  30.     }
  31.     private function canAccess(User $userRegistration $registration): bool
  32.     {
  33.         $allowedRegistrations $this->repo->findByAllowedUser($user);
  34.         foreach ($allowedRegistrations as $allowedRegistration) {
  35.             if ($registration->getId() === $allowedRegistration->getId()) {
  36.                 return true;
  37.             }
  38.         }
  39.         return false;
  40.     }
  41. }