Search code examples
phpsymfonysymfony4php-7.2

Redirect response from Event Subscriber in Symfony PHP


I'm trying to return a permanent (301) redirect response from a event subscriber hooked into the kernel events in Synfony PHP.

My subscriber is as follow:

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

use Symfony\Component\HttpFoundation\RedirectResponse;

class KernelSubscriber implements EventSubscriberInterface {

    public function __construct() {

        // some stuff here but not relevant for this example
    }

    public static function getSubscribedEvents(): array {

        return [ KernelEvents::REQUEST => 'onRequest' ];
    }

    public function onRequest(GetResponseEvent $event): void {

        // if conditions met
        //     301 redirect to some internal or external URL

        if(!$event->isMasterRequest()) return;
    }   
}

If this were a controller I would return $this->redirectToRoute('route') or something like that but returning from the onRequest method is in a much different context.

How can I return a response (a redirect, in particular) from this event subscriber?


Solution

  • Should be something like:

    $event->setResponse(new RedirectResponse($route));