<?php
namespace App\Security\Voter\Adherent;
use App\Entity\Registration;
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 RegistrationVoter extends Voter
{
public const EDIT = 'edit';
public function __construct(private RegistrationRepository $repo)
{
}
protected function supports(string $attribute, $subject): bool
{
return $attribute === self::EDIT
&& $subject instanceof Registration;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if ($attribute === self::EDIT) {
return $this->canAccess($user, $subject);
}
return false;
}
private function canAccess(User $user, Registration $registration): bool
{
$allowedRegistrations = $this->repo->findByAllowedUser($user);
foreach ($allowedRegistrations as $allowedRegistration) {
if ($registration->getId() === $allowedRegistration->getId()) {
return true;
}
}
return false;
}
}