<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\EventListener\Twig;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;

/**
 * Ajuste le contexte du routeur Symfony pour les Live Components.
 *
 * Si la requête concerne une route sous `/dashboard`, le listener ajoute
 * un paramètre de contexte `_dashboard` afin d'assurer la cohérence du
 * firewall et du contexte de sécurité lors des requêtes AJAX Live Components.
 */
#[AsEventListener(event: KernelEvents::REQUEST, priority: 100)]
readonly class LiveComponentRouterContextListener
{
    public function __construct(
        private RouterInterface $router,
    ) {
    }

    public function __invoke(RequestEvent $event): void
    {
        $request = $event->getRequest();
        if (str_starts_with($request->getPathInfo(), '/dashboard')) {
            $this->router->getContext()->setParameter('_dashboard', 'dashboard/');
        } else {
            $this->router->getContext()->setParameter('_dashboard', null);
        }
    }
}
