src/Submarine/RedirectsBundle/EventSubscriber/RequestSubscriber.php line 43

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Submarine\RedirectsBundle\EventSubscriber;
  3. use Doctrine\ORM\ORMException;
  4. use Submarine\RedirectsBundle\Repository\RedirectRepository;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class RequestSubscriber implements EventSubscriberInterface
  10. {
  11.     /**
  12.      * @var RedirectRepository
  13.      */
  14.     private $repository;
  15.     /**
  16.      * @param RedirectRepository $repository
  17.      */
  18.     public function __construct(RedirectRepository $repository)
  19.     {
  20.         $this->repository $repository;
  21.     }
  22.     /**
  23.      * @return array
  24.      */
  25.     public static function getSubscribedEvents()
  26.     {
  27.         return [
  28.             KernelEvents::REQUEST => [
  29.                 ['processRequest'1024],
  30.             ]
  31.         ];
  32.     }
  33.     /**
  34.      * @param RequestEvent $event
  35.      * @throws ORMException
  36.      */
  37.     public function processRequest(RequestEvent $event)
  38.     {
  39.         if (!$event->isMainRequest()) {
  40.             return;
  41.         }
  42.         $url $event->getRequest()->getRequestUri();
  43.         $redirect $this->repository->findActiveRedirect($url);
  44.         if ($redirect) {
  45.             $response = new RedirectResponse($redirect->getRedirectUrl(), $redirect->getCode());
  46.             $event->setResponse($response);
  47.         }
  48.     }
  49. }