<?php
namespace App\EventSubscriber;
use Throwable;
use App\Adapter\AuthAdapter;
use App\Model\Appointment;
use App\Service\AppointmentService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Event\LogoutEvent;
class LogoutSubscriber implements EventSubscriberInterface
{
private UrlGeneratorInterface $urlGenerator;
private AuthAdapter $authAdapter;
private Security $security;
private AppointmentService $appointmentService;
private ?Appointment $appointment = null;
private ?bool $gon = null;
/**
* @var mixed
*/
private ?array $vehicles = [];
public function __construct(UrlGeneratorInterface $urlGenerator, AuthAdapter $authAdapter, Security $security, AppointmentService $appointmentService)
{
$this->urlGenerator = $urlGenerator;
$this->authAdapter = $authAdapter;
$this->security = $security;
$this->appointmentService = $appointmentService;
}
public function onLogoutEvent(LogoutEvent $event): void
{
// get the security token of the session that is about to be logged out
$token = $event->getToken();
$logoutOK = true;
if ($this->security->isGranted('ROLE_CLIENT')) {
try {
$client = $token->getUser();
$this->authAdapter->logout($client->getToken());
} catch (Throwable $exception) {
$logoutOK = false;
}
}
if ($logoutOK) {
$request = $event->getRequest();
$session = $request->getSession();
if ($this->appointment && !$this->gon) {
$this->appointmentService->removeNextStep($this->appointment, 'garage');
$session->set('logout', true);
}
$session->set('appointment', $this->appointment);
$session->set('vehicles', $this->vehicles);
$session->set('gon', $this->gon);
// configure a custom logout response to the homepage
$response = new RedirectResponse(
$this->urlGenerator->generate('front_index_page'),
RedirectResponse::HTTP_SEE_OTHER
);
$event->setResponse($response);
}
}
public function onPreLogoutEvent(LogoutEvent $event)
{
$request = $event->getRequest();
$session = $request->getSession();
$this->appointment = $session->get('appointment');
$this->gon = $session->get('gon', false);
$this->vehicles = $session->get('vehicles', []);
}
public static function getSubscribedEvents(): array
{
return [
LogoutEvent::class => [
['onLogoutEvent'],
['onPreLogoutEvent', 99],
],
];
}
}