<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
use Twig\Environment;
/**
* Class ExceptionListener
*/
class ExceptionListener
{
protected Environment $templating;
/**
* ExceptionListener constructor.
*/
public function __construct(Environment $templating)
{
$this->templating = $templating;
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (
$exception instanceof InsufficientAuthenticationException
|| $exception instanceof AccessDeniedException
) {
$response = new Response();
$response->setContent($this->templating->render('errors/404.html.twig'));
$response->setStatusCode(Response::HTTP_NOT_FOUND);
$event->setResponse($response);
}
}
}