src/EventSubscriber/ProductNotFoundSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/ProductNotFoundSubscriber.php
  3. namespace App\EventSubscriber;
  4. use App\Exception\ProductNotFoundWithSuggestionsException;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Twig\Environment as Twig;
  10. class ProductNotFoundSubscriber implements EventSubscriberInterface
  11. {
  12.     private $twig;
  13.     
  14.     public function __constructTwig $twig) {
  15.         $this->twig $twig;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [KernelEvents::EXCEPTION => 'onKernelException'];
  20.     }
  21.     public function onKernelException(ExceptionEvent $event): void
  22.     {
  23.         $e $event->getThrowable();
  24.         if (!$e instanceof ProductNotFoundWithSuggestionsException) {
  25.             return;
  26.         }
  27.         $html $this->twig->render('bundles/TwigBundle/Exception/error404.html.twig', [
  28.             'status_code'  => 404,
  29.             'status_text'  => Response::$statusTexts[404] ?? 'Not Found',
  30.             'suggestions'  => $e->getSuggestions(), // <— tes données ici
  31.         ]);
  32.         $event->setResponse(new Response($html404));
  33.     }
  34. }