src/EventSubscriber/RedirectSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Repository\RedirectRepository;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class RedirectSubscriber implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * @var RedirectRepository
  12.      */
  13.     private $redirectRepository;
  14.     public function __construct(RedirectRepository $redirectRepository)
  15.     {
  16.         $this->redirectRepository $redirectRepository;
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             KernelEvents::REQUEST => ['onKernelRequest'110],
  22.         ];
  23.     }
  24.     public function onKernelRequest(RequestEvent $event)
  25.     {
  26.         if (!$event->isMainRequest()) {
  27.             return;
  28.         }
  29.         $redirect $this->redirectRepository->findOneBy([
  30.             'whereFrom' => $event->getRequest()->getRequestUri()
  31.         ]);
  32.         if ($redirect) {
  33.             $event->setResponse(
  34.                 new RedirectResponse($redirect->getWhereTo(), $redirect->getHttpCode())
  35.             );
  36.         }
  37.     }
  38. }