src/EventListener/RoutingSubscriber.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Routing;
  4. use Doctrine\ORM\EntityManager;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  9. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  10. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. class RoutingSubscriber implements EventSubscriberInterface
  13. {
  14.     /** @var EntityManager */
  15.     private $entityManager;
  16.     public function __construct(EntityManagerInterface $entityManager)
  17.     {
  18.         $this->entityManager $entityManager;
  19.     }
  20.     public static function getSubscribedEvents()
  21.     {
  22.         return array(
  23.             KernelEvents::REQUEST => array(array('onKernelRequest'17)),
  24.             KernelEvents::EXCEPTION => array(array('onKernelException'10)),
  25.         );
  26.     }
  27.     /**
  28.      * @param GetResponseEvent $event
  29.      */
  30.     public function onKernelRequest(GetResponseEvent $event)
  31.     {
  32.         $request $event->getRequest();
  33.         $routing $this->entityManager->getRepository(Routing::class)->findOneBy(
  34.             ['routing' => $request->getPathInfo()]
  35.         );
  36.         if ($routing) {
  37.             $event->setResponse(
  38.                 new RedirectResponse(
  39.                     $routing->getRedirect(),
  40.                     $routing->getCodeRedirect() ? $routing->getCodeRedirect() : ""
  41.                 )
  42.             );
  43.         }
  44.     }
  45.     /**
  46.      * @param GetResponseForExceptionEvent $event
  47.      */
  48.     public function onKernelException(GetResponseForExceptionEvent $event){
  49.         $exception $event->getException();
  50.         if ($exception instanceof HttpExceptionInterface) {
  51.             if (404 == $exception->getStatusCode()) {
  52.                 $request $event->getRequest();
  53.                 $pathinfo $request->getPathInfo();
  54.                 $baseurl $request->getSchemeAndHttpHost() . $request->getBaseUrl();
  55.                 if (FALSE !== strpos($pathinfo'/article')) {
  56.                     $event->setResponse(new RedirectResponse($baseurl '/magazine'));
  57.                 }elseif (FALSE !== strpos($pathinfo'/activites')) {
  58.                     $event->setResponse(new RedirectResponse($baseurl '/activites'));
  59.                 }
  60.             }
  61.         }
  62.     }
  63. }