src/Event/EventSubscriber/CanonicalRedirectSubscriber.php line 40

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Event\EventSubscriber;
  4. use App\Exception\CanonicalRedirectException;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\Routing\RouterInterface;
  9. final class CanonicalRedirectSubscriber implements EventSubscriberInterface
  10. {
  11.     private RouterInterface $router;
  12.     /**
  13.      * @param RouterInterface $router
  14.      */
  15.     public function __construct(RouterInterface $router)
  16.     {
  17.         $this->router = $router;
  18.     }
  19.     /**
  20.      * @inheritDoc
  21.      */
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             ExceptionEvent::class => 'onKernelException',
  26.         ];
  27.     }
  28.     /**
  29.      * @param ExceptionEvent $event
  30.      *
  31.      * @return void
  32.      */
  33.     public function onKernelException(ExceptionEvent $event): void
  34.     {
  35.         $exception = $event->getThrowable();
  36.         if (!$exception instanceof CanonicalRedirectException) {
  37.             return;
  38.         }
  39.         $route = $exception->getHeaders()['X-Canonical-Route'];
  40.         $params = json_decode($exception->getHeaders()['X-Canonical-Params'], true);
  41.         $url = $this->router->generate($route, $params);
  42.         $event->setResponse(new RedirectResponse($url, 302));
  43.     }
  44. }