<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use JetBrains\PhpStorm\ArrayShape;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
class BadRequestResponseEventSubscriber implements EventSubscriberInterface
{
private Environment $twig;
private LoggerInterface $logger;
public function __construct(Environment $twig, LoggerInterface $logger)
{
$this->twig = $twig;
$this->logger = $logger;
}
public static function getSubscribedEvents(): array
{
return [
ExceptionEvent::class => 'onException'
];
}
public function onException(ExceptionEvent $event): void
{
if (($exception = $event->getThrowable()) instanceof BadRequestHttpException) {
$this->logger->warning(sprintf('Message: %s', $exception->getMessage()));
$event->setResponse($this->getResponse($exception));
}
}
private function getResponse(BadRequestHttpException $exception): Response
{
return new Response(
$this->twig->render(
'page/error/400.html.twig',
['message' => $exception->getMessage()]
),
Response::HTTP_BAD_REQUEST
);
}
}