<?php
namespace App\EventListener;
use App\Entity\PrivateUser;
use App\Entity\ProUser;
use App\Entity\User;
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\Core\Authorization\AuthorizationCheckerInterface;
class RouteRequestListener
{
public function __construct(private readonly TokenStorageInterface $tokenStorage, private readonly AuthorizationCheckerInterface $authorizationChecker, private readonly RouterInterface $router)
{
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$user = $this->getUser();
if (
$event->isMainRequest()
&& 'frontend_cgv_validation' !== $request->get('_route')
&& 'fos_user_profile_edit' !== $request->get('_route')
&& $user instanceof ProUser
&& !$this->isGranted('ROLE_ACCESS', $user)
&& null === $user->getCgvValidatedAt()
&& !$this->authorizationChecker->isGranted('ROLE_API_RMS')
) {
$response = new RedirectResponse($this->router->generate('frontend_cgv_validation'));
$event->setResponse($response);
return $response;
}
if (
$user instanceof User
&& $user->isGranted('ROLE_STRANGER_SALESPERSON')
&& 'backend_index' === $request->get('_route')
) {
$response = new RedirectResponse($this->router->generate('backend_sales_list'));
$event->setResponse($response);
}
if (!in_array($request->get('_route'), ['homepage', 'homepage_pro'])) {
return;
}
if (
$user instanceof ProUser
&& 'homepage' === $request->get('_route')
) {
$response = new RedirectResponse($this->router->generate('homepage_pro'));
$event->setResponse($response);
}
if (
$user instanceof PrivateUser
&& 'homepage_pro' === $request->get('_route')
) {
$response = new RedirectResponse($this->router->generate('homepage'));
$event->setResponse($response);
}
}
protected function isGranted($attributes, $object)
{
return $this->authorizationChecker->isGranted($attributes, $object);
}
protected function getUser()
{
if (null !== $this->tokenStorage->getToken()) {
return $this->tokenStorage->getToken()->getUser();
}
return null;
}
}