<?php
namespace App\EventListener;
use App\Entity\SonataUserUser;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class CheckAccountStateListener implements EventSubscriberInterface
{
use TargetPathTrait;
private TokenStorageInterface $tokenStorage;
private RouterInterface $router;
public function __construct(
TokenStorageInterface $tokenStorage,
RouterInterface $router
) {
$this->tokenStorage = $tokenStorage;
$this->router = $router;
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
// Přeskoč API nebo veřejné routy (můžeš upravit dle projektu)
$excludedRoutes = ['account_active', 'account_inactive', 'app_logout', 'app_login'];
$currentRoute = $request->attributes->get('_route');
if (!$currentRoute || in_array($currentRoute, $excludedRoutes, true)) {
return;
}
$token = $this->tokenStorage->getToken();
if (!$token || !$token->getUser() instanceof SonataUserUser) {
return;
}
/** @var SonataUserUser $user */
$user = $token->getUser();
if (!$user->getAccountState() || $user->getAccountState()->getIdentifier() !== 'active') {
$event->setResponse(new RedirectResponse($this->router->generate('account_inactive')));
}
}
}