<?php
// src/EventSubscriber/ProductGoneSubscriber.php
namespace App\EventSubscriber;
use App\Exception\ProductGoneWithSuggestionsException;
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 ProductGoneSubscriber 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 ProductGoneWithSuggestionsException) {
return;
}
$html = $this->twig->render('bundles/TwigBundle/Exception/error410.html.twig', [
'status_code' => 410,
'status_text' => Response::$statusTexts[410] ?? 'Gone',
'suggestions' => $e->getSuggestions(),
]);
$event->setResponse(new Response($html, 410));
}
}