vendor/kematjaya/menu-bundle/src/Listener/ExceptionListener.php line 42

Open in your IDE?
  1. <?php
  2. /**
  3.  * This file is part of the menu-bundle.
  4.  */
  5. namespace Kematjaya\MenuBundle\Listener;
  6. use Twig\Environment;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  10. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  11. use Symfony\Component\HttpKernel\Exception\HttpException;
  12. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  13. /**
  14.  * @package Kematjaya\MenuBundle\DependencyInjection
  15.  * @license https://opensource.org/licenses/MIT MIT
  16.  * @author  Nur Hidayatullah <[email protected]>
  17.  */
  18. class ExceptionListener 
  19. {
  20.     /**
  21.      * 
  22.      * @var Environment
  23.      */
  24.     private $twig;
  25.     
  26.     /**
  27.      * 
  28.      * @var UrlGeneratorInterface
  29.      */
  30.     private $urlGenerator;
  31.     
  32.     public function __construct(Environment $twigUrlGeneratorInterface $urlGenerator
  33.     {
  34.         $this->twig $twig;
  35.         $this->urlGenerator $urlGenerator;
  36.     }
  37.     
  38.     public function onKernelException(ExceptionEvent $event)
  39.     {
  40.         $exception $event->getThrowable();
  41.         if ($exception instanceof AccessDeniedHttpException) {
  42.             $response = new Response(
  43.                 $this->twig->render('@Menu/access-denied.html.twig', [
  44.                     'message' => 'access_denied_message',
  45.                     'title' => 'access_denied'
  46.                 ])
  47.             );
  48.             $response->setStatusCode($exception->getStatusCode());
  49.             $event->setResponse($response);
  50.             $event->stopPropagation();
  51.             return;
  52.         }
  53.         
  54.         if ($exception instanceof HttpException) {
  55.             $codes = [
  56.                 Response::HTTP_UNAUTHORIZED
  57.             ];
  58.             if (!in_array($exception->getStatusCode(), $codes)) {
  59.                 
  60.                 return;
  61.             }
  62.             
  63.             $response = new RedirectResponse(
  64.                 $this->urlGenerator->generate('kmj_user_login')
  65.             );
  66.             
  67.             $response->setStatusCode($exception->getStatusCode());
  68.             $response->headers->replace($exception->getHeaders());
  69.             $event->setResponse($response);
  70.             $event->stopPropagation();
  71.         }
  72.     }
  73. }