<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Security\Core\Security;
class LogoutSubscriber implements EventSubscriberInterface
{
public function __construct(private Security $security)
{
}
public function onKernelResponse(ResponseEvent $event): void
{
$request = $event->getRequest();
$session = $request->getSession();
$unauthentified = $session->get('unauthentified');
if ($this->security->getUser() && isset($unauthentified)) {
$targetUrl = $request->getBaseUrl()."/logout";
if ($request->getPathInfo() != "/logout") {
$redirectUrl = new RedirectResponse($targetUrl);
$event->setResponse($redirectUrl);
}
}
}
public static function getSubscribedEvents(): array
{
return [
'kernel.response' => 'onKernelResponse',
];
}
}