vendor/kematjaya/user-bundle/src/EventListener/UnauthorizedEventListener.php line 42

Open in your IDE?
  1. <?php
  2. /*
  3.  * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
  4.  * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
  5.  */
  6. namespace Kematjaya\UserBundle\EventListener;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Cookie;
  12. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  13. /**
  14.  * Description of UnauthorizedEventListener
  15.  *
  16.  * @author guest
  17.  */
  18. class UnauthorizedEventListener 
  19. {
  20.     /**
  21.      * 
  22.      * @var UrlGeneratorInterface
  23.      */
  24.     private $urlGenerator;
  25.     
  26.     /**
  27.      * 
  28.      * @var ParameterBagInterface
  29.      */
  30.     private $parameterBag;
  31.     
  32.     public function __construct(UrlGeneratorInterface $urlGeneratorParameterBagInterface $parameterBag
  33.     {
  34.         $this->urlGenerator $urlGenerator;
  35.         $this->parameterBag $parameterBag;
  36.     }
  37.     
  38.     public function onKernelException(ExceptionEvent $event)
  39.     {
  40.         if ($event->getThrowable() instanceof InsufficientAuthenticationException) {
  41.             $this->createResponse($event);
  42.         }
  43.         
  44.         if ($event->getThrowable()->getPrevious() instanceof InsufficientAuthenticationException) {
  45.             $this->createResponse($event);
  46.         }
  47.     }
  48.     
  49.     protected function createResponse(ExceptionEvent $event)
  50.     {
  51.         $configs $this->parameterBag->get("user");
  52.         $event->getRequest()->getSession()->getFlashBag()->add("error"$event->getThrowable()->getMessage());
  53.         $redirectPath $configs['route']['unauthorize_redirect_path'];
  54.         $response = new RedirectResponse(
  55.             $this->urlGenerator->generate($redirectPath)
  56.         );
  57.         
  58.         $url $this->urlGenerator->generate(
  59.             $event->getRequest()->attributes->get("_route"),
  60.             $event->getRequest()->attributes->get("_route_params"),
  61.             UrlGeneratorInterface::ABSOLUTE_URL
  62.         );
  63.         
  64.         $response->headers->setCookie(
  65.             Cookie::create(
  66.                 "redirect_path"
  67.                 $url
  68.             )
  69.         );
  70.         $event->setResponse($response);
  71.     }
  72. }