src/EventSubscriber/ProductGoneSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/ProductGoneSubscriber.php
  3. namespace App\EventSubscriber;
  4. use App\Exception\ProductGoneWithSuggestionsException;
  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 ProductGoneSubscriber implements EventSubscriberInterface
  11. {
  12.     private $twig;
  13.     public function __constructTwig $twig) {
  14.         $this->twig $twig;
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [KernelEvents::EXCEPTION => 'onKernelException'];
  19.     }
  20.     public function onKernelException(ExceptionEvent $event): void
  21.     {
  22.         $e $event->getThrowable();
  23.         if (!$e instanceof ProductGoneWithSuggestionsException) {
  24.             return;
  25.         }
  26.         $html $this->twig->render('bundles/TwigBundle/Exception/error410.html.twig', [
  27.             'status_code'  => 410,
  28.             'status_text'  => Response::$statusTexts[410] ?? 'Gone',
  29.             'suggestions'  => $e->getSuggestions(),
  30.         ]);
  31.         $event->setResponse(new Response($html410));
  32.     }
  33. }