src/Security/Voter/DocumentVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Document;
  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 DocumentVoter extends Voter
  10. {
  11.     public const VIEW 'view';
  12.     public function __construct(private readonly RegistrationRepository $repository)
  13.     {
  14.     }
  15.     protected function supports(string $attribute$subject): bool
  16.     {
  17.         return $attribute === self::VIEW && $subject instanceof Document;
  18.     }
  19.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  20.     {
  21.         $user $token->getUser();
  22.         if (!$user instanceof UserInterface) {
  23.             return false;
  24.         }
  25.         if ($user->hasRole('ROLE_ADMIN')) {
  26.             return true;
  27.         }
  28.         if ($attribute === self::VIEW) {
  29.             return $this->canAccess($user$subject);
  30.         }
  31.         return false;
  32.     }
  33.     private function canAccess(User $userDocument $document): bool
  34.     {
  35.         $allowedRegistrations $this->repository->findByAllowedUser($user);
  36.         foreach ($allowedRegistrations as $allowedRegistration) {
  37.             if ($allowedRegistration->getId() === $document->getRegistration()?->getId()) {
  38.                 return true;
  39.             }
  40.         }
  41.         return false;
  42.     }
  43. }