<?php
namespace App\Security\Voter;
use App\Entity\Document;
use App\Entity\User;
use App\Repository\RegistrationRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class DocumentVoter extends Voter
{
public const VIEW = 'view';
public function __construct(private readonly RegistrationRepository $repository)
{
}
protected function supports(string $attribute, $subject): bool
{
return $attribute === self::VIEW && $subject instanceof Document;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if ($user->hasRole('ROLE_ADMIN')) {
return true;
}
if ($attribute === self::VIEW) {
return $this->canAccess($user, $subject);
}
return false;
}
private function canAccess(User $user, Document $document): bool
{
$allowedRegistrations = $this->repository->findByAllowedUser($user);
foreach ($allowedRegistrations as $allowedRegistration) {
if ($allowedRegistration->getId() === $document->getRegistration()?->getId()) {
return true;
}
}
return false;
}
}