Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
yevg Avatar asked Nov 11 '18 00:11

yevg


1 Answers

Should be something like:

$event->setResponse(new RedirectResponse($route));
like image 94
Alex.Barylski Avatar answered Oct 23 '22 01:10

Alex.Barylski