<?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\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
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);
}
if($request->isXmlHttpRequest()) {
$response = new JsonResponse([
'status' => 'error',
'message' => $exception->getMessage()
]);
if($exception->getCode() != '0'){
$response->setStatusCode($exception->getCode());
}
$event->setResponse($response);
//return $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;
}
}