<?php
namespace App\EventListener;
use App\Entity\PrivateUser;
use App\Event\UserEvents;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\SecurityEvents;
class RegistrationListener implements EventSubscriberInterface
{
public const VEHICLE_ID = 'registration_vehicle_id';
public const REDIRECT_VEHICLE_ID = 'registration_redirect_id';
public function __construct(private readonly SessionInterface $session, private readonly TokenStorageInterface $tokenStorage, private readonly RouterInterface $router)
{
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::REGISTRATION_CONFIRMED => 'onUserRegistrationConfirmed',
];
}
public function onKernelRequest(RequestEvent $event)
{
if ($event->isMainRequest()) {
// Get value from URL in auth popin and store it in the session.
if ($origin = $event->getRequest()->query->get(self::VEHICLE_ID)) {
$this->session->set(self::VEHICLE_ID, $origin);
}
// Get value from URL sent in the email and store it in the session.
if ($vehicleId = $event->getRequest()->query->get(self::REDIRECT_VEHICLE_ID)) {
$this->session->set(self::REDIRECT_VEHICLE_ID, $vehicleId);
}
// Once the user is logged in, redirect it to the vehicle
if (
null !== $this->tokenStorage->getToken()
&& $this->tokenStorage->getToken()->getUser() instanceof PrivateUser
&& $vehicleId = $this->session->get(self::REDIRECT_VEHICLE_ID, false)) {
$response = new RedirectResponse($this->router->generate(
'frontend_vehicle_view',
['id' => $vehicleId]
));
$event->setResponse($response);
$this->session->remove(self::REDIRECT_VEHICLE_ID);
return $response;
}
}
}
public function onUserRegistrationConfirmed($event): void
{
$this->session->getFlashBag()->add('popup', $this->router->generate(
'registration_step',
['step' => 4],
UrlGeneratorInterface::ABSOLUTE_URL
));
}
}