<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Twig\Environment;
class NotFoundHttpExceptionEventSubscriber implements EventSubscriberInterface
{
private Environment $twig;
public function __construct(Environment $twig)
{
$this->twig = $twig;
}
public static function getSubscribedEvents(): array
{
return [
ExceptionEvent::class => 'onKernelException'
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!($exception instanceof NotFoundHttpException)) {
return;
}
$content = $this->twig->render('page/error/404.html.twig', [
'exception' => $exception
]);
$event->setResponse(new Response($content, Response::HTTP_NOT_FOUND));
}
}