<?php
declare(strict_types=1);
namespace App\Event\EventSubscriber;
use App\Exception\CanonicalRedirectException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
final class CanonicalRedirectSubscriber implements EventSubscriberInterface
{
private RouterInterface $router;
/**
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
ExceptionEvent::class => 'onKernelException',
];
}
/**
* @param ExceptionEvent $event
*
* @return void
*/
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!$exception instanceof CanonicalRedirectException) {
return;
}
$route = $exception->getHeaders()['X-Canonical-Route'];
$params = json_decode($exception->getHeaders()['X-Canonical-Params'], true);
$url = $this->router->generate($route, $params);
$event->setResponse(new RedirectResponse($url, 302));
}
}