<?php
namespace App\Controller\Page;
use App\Entity\Page as PageEntity;
use App\Renderer\Page as PageRenderer;
use Doctrine\ORM\EntityManagerInterface;
use Gedmo\Translatable\TranslatableListener;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
class ExceptionController extends AbstractController
{
/**
* ExceptionController constructor.
*/
public function __construct(
private readonly Environment $twig,
private readonly EntityManagerInterface $manager,
private readonly ParameterBagInterface $parameterBag,
private readonly PageRenderer $pageRenderer,
private readonly HtmlErrorRenderer $errorRenderer,
private readonly ?TranslatableListener $translatableListener = null
) {
}
/**
* Converts an Exception to a Response.
*
* A "showException" request parameter can be used to force display of an error page (when set to false) or
* the exception page (when true). If it is not present, the "debug" value passed into the constructor will
* be used.
*
* @throws LoaderError
* @throws SyntaxError
* @throws RuntimeError
*/
public function show(Request $request, \Throwable $exception): Response
{
$this->translatableListener?->setTranslatableLocale($this->parameterBag->get('site_translation_default_locale'));
$flattenException = $this->errorRenderer->render($exception);
if ('prod' !== $_ENV['APP_ENV']
|| !$notFoundPage = $this->manager
->getRepository(PageEntity::class)
->findOneBy([
'alias' => $flattenException->getStatusCode().'_page',
])
) {
return new Response(
$flattenException->getAsString(),
$flattenException->getStatusCode(),
$flattenException->getHeaders()
);
}
$content = $this->twig->render(
'@default/pages/pages_index.html.twig',
[
'header' => $this->pageRenderer->getHeader(),
'footer' => $this->pageRenderer->getFooter(),
'page' => $notFoundPage,
]
);
return new Response($content, $flattenException->getStatusCode(), [
'Content-Type' => $request->getMimeType($request->getRequestFormat()) ?: 'text/html',
]);
}
}