Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4 : ignore kernel events coming from debug toolbar

I'm quite new to Symfony so forgive me if it seems obvious for you :)

For my project, i need to perform some actions depending on the url. I use kernel events, more specifically the kernel request to do so.

In services.yaml :

App\Service\UrlManager:
    tags:
        - { name: kernel.event_listener, event: kernel.request}  

In UrlManager.php :

public function onKernelRequest(GetResponseEvent $event)
{
    $request = Request::createFromGlobals();
    $hostname = parse_url($request->server->get('HTTP_HOST'),PHP_URL_HOST);

    /*
     * here my treatment that works fine :)
     */ 

But as i'm in DEV mode, the same event is fired again by the debug toolbar... The only workaround i found was by adding this before my treatment :

if (substr($request->server->get('REQUEST_URI'),0,6) != '/_wdt/') {

Also works fine, but i think it's not the best thing to do, because something very specific will stay in the project, and only for DEV mode. Is there a way to "tell" the toolbar not to fire this event ? Maybe something to add in services.yaml ? Or some other config parameter ?

like image 847
sylvain Avatar asked Jan 28 '23 22:01

sylvain


1 Answers

So I did a bit more research. It's not that the kernel event is being fired twice but rather that once your original page is sent to the browser a bit of javascript initiates a second _wdt request for additional information. So you actually have two independent requests. You can see this by pressing F12 in your browser and then selecting the network tab and refreshing.

It is easy enough to filter the debug request since the name of the route will always be _wdt. And you can also get the host directly from the request. Still want to check for the master request because eventually your code might trigger sub requests.

public function onRequest(GetResponseEvent $event)
{
    // Only master
    if (!$event->isMasterRequest()) {
        return;
    }
    $request = $event->getRequest();

    // Ignore toolbar
    if ($request->attributes->get('_route') === '_wdt') {
        return;
    }

    // Avoid parsing urls and other stuff, the request object should have
    // all the info you need
    $host = $request->getHost();

}
like image 195
Cerad Avatar answered Jan 31 '23 20:01

Cerad