<?php
// src/EventSubscriber/ProductNotFoundSubscriber.php
namespace App\EventSubscriber;
use App\Exception\ProductNotFoundWithSuggestionsException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment as Twig;
class ProductNotFoundSubscriber implements EventSubscriberInterface
{
private $twig;
public function __construct( Twig $twig) {
$this->twig = $twig;
}
public static function getSubscribedEvents(): array
{
return [KernelEvents::EXCEPTION => 'onKernelException'];
}
public function onKernelException(ExceptionEvent $event): void
{
$e = $event->getThrowable();
if (!$e instanceof ProductNotFoundWithSuggestionsException) {
return;
}
$html = $this->twig->render('bundles/TwigBundle/Exception/error404.html.twig', [
'status_code' => 404,
'status_text' => Response::$statusTexts[404] ?? 'Not Found',
'suggestions' => $e->getSuggestions(), // <— tes données ici
]);
$event->setResponse(new Response($html, 404));
}
}