<?php
namespace Boab\CmsBundle\View\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Boab\CmsBundle\View\ViewManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ExceptionListener
{
private $viewManager;
public function __construct(ViewManagerInterface $viewManager)
{
$this->viewManager = $viewManager;
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
$request = $event->getRequest();
$response = $this->handleException($exception, $request);
if($response instanceof Response){
$event->setResponse($response);
}
}
private function handleException($exception, $request)
{
if ($exception instanceof NotFoundHttpException) {
return $this->getHtmlResponse(404, $exception, 'Page Not Found');
}
return;
}
private function getHtmlResponse($code, $exception, $title)
{
$statusCode = ($exception instanceof HttpExceptionInterface) ? $exception->getStatusCode() : $exception->getCode();
$view = $this->viewManager->load(sprintf('@BoabCms/Exception/exception_%s.html.twig', $code));
$view->exception = $exception;
$view->pageTitle = $title;
$response = new Response($view->render());
$response->setStatusCode($code);
return $response;
}
}