lib/boab/cms-bundle/src/View/EventListener/ExceptionListener.php line 55

Open in your IDE?
  1. <?php
  2. namespace Boab\CmsBundle\View\EventListener;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  6. use Boab\CmsBundle\View\ViewManagerInterface;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  10. class ExceptionListener
  11. {
  12.     private $viewManager;
  13.     public function __construct(ViewManagerInterface $viewManager)
  14.     {
  15.         $this->viewManager $viewManager;
  16.     }
  17.     public function onKernelException(ExceptionEvent $event
  18.     {
  19.         $exception $event->getThrowable();
  20.         $request $event->getRequest();
  21.         $response $this->handleException($exception$request);
  22.         if($response instanceof Response){
  23.             
  24.             $event->setResponse($response);
  25.         }
  26.         if($request->isXmlHttpRequest()) {
  27.             $response = new JsonResponse([
  28.              'status' => 'error',
  29.              'message' => $exception->getMessage()
  30.             ]);
  31.             if($exception->getCode() != '0'){
  32.                 $response->setStatusCode($exception->getCode());
  33.             }
  34.             $event->setResponse($response);
  35.             //return $response;
  36.          }      
  37.     }
  38.     
  39.     private function handleException($exception$request)
  40.     {
  41.         if ($exception instanceof NotFoundHttpException) {
  42.             return $this->getHtmlResponse(404$exception'Page Not Found');
  43.         }
  44.         return;
  45.     }
  46.     private function getHtmlResponse($code$exception$title)
  47.     {
  48.         $statusCode = ($exception instanceof HttpExceptionInterface) ? $exception->getStatusCode() : $exception->getCode();
  49.         $view $this->viewManager->load(sprintf('@BoabCms/Exception/exception_%s.html.twig'$code));
  50.         $view->exception $exception;
  51.         $view->pageTitle $title;
  52.         $response = new Response($view->render());
  53.         $response->setStatusCode($code);
  54.         return $response;
  55.     }