Search code examples
symfony-2.8

How to redirect and prevent running all onKernelResponse in Listeners?


I have implemented a Listener with the highest priority, that depending on a header value redirects the user off from my server.

Since this affects a lot of users I would like to execute the redirect before all other Listeners are run ad especially also the onKernelResponse of those Listeners.

Is there a way to stop and redirect the user really in the moment my redirect is called? Maybe I can redirect not using the RedirectResponse? But then how?

public function onKernelRequest(GetResponseEvent $event)
{
    if (!$event->isMasterRequest()) {
        return;
    }

    $request = $this->requestStack->getCurrentRequest();
    $requestedWith = $request->headers->get('x-header-myfeature');
    if (!empty($requestedWith)) {
        $event->setResponse(new RedirectResponse($this->newUrltoRedirect));
    }
}

Mind the redirect works, I just want to avoid running all other Listeners and triggering e.g. log messages there.

I would not mind applying even more brutal methods to redirect at this point without caring to run any more code.

Any ideas?

P.S. : I tried adding a

public function onKernelResponse(FilterResponseEvent $event)
{
    $response =  $event->getResponse();
    if ($response instanceof RedirectResponse) {
        $this->logger->notice(' We want to redirect');
        $event->stopPropagation();
    }
}

But it doesn't work since I get a plain Response object and not a RedirectResponse object.


Solution

  • What worked although I am still not sure if this is the best solution was, to check on the same header again in the onKernelResponse event.

    public function onKernelResponse(FilterResponseEvent $event)
    {
        $requestedWith = $this->requestStack->getCurrentRequest()->headers->get('x-header-myfeature');
        if (!empty($requestedWith)) {
            $event->stopPropagation();
        }
    }
    

    The call of stopPropagation() stops running the code of all other onKernelResponse methods, although if you look in the log, still all listener classes are called.

    So any other approach or solution is still welcome.