src/EventSubscriber/RedirectSubscriber.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Component\Configuration\Util\Config;
  4. use App\Entity\Redirect;
  5. use App\Repository\RedirectRepository;
  6. use Doctrine\Common\Collections\Criteria;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\HttpKernel\Event\RequestEvent;
  12. class RedirectSubscriber implements EventSubscriberInterface
  13. {
  14.     private Config $config;
  15.     private RedirectRepository $redirectRepository;
  16.     public function __construct(Config $configEntityManagerInterface $entityManager)
  17.     {
  18.         $this->config $config;
  19.         $this->redirectRepository $entityManager->getRepository(Redirect::class);
  20.     }
  21.     public function onKernelRequest(RequestEvent $event)
  22.     {
  23.         if (!$this->config->get('site_redirects_active') || !$pathInfo $event->getRequest()->getPathInfo()) {
  24.             return;
  25.         }
  26.         if (str_starts_with($pathInfo'/admin') || !$redirect $this->redirectRepository
  27.                 ->findOneBy(['source' => $pathInfo], ['id' => Criteria::DESC])) {
  28.             return;
  29.         }
  30.         $event->setResponse(new RedirectResponse(
  31.             $redirect->getDestination(),
  32.             $redirect->isPermanent() ? Response::HTTP_MOVED_PERMANENTLY Response::HTTP_FOUND
  33.         ));
  34.     }
  35.     public static function getSubscribedEvents(): array
  36.     {
  37.         return [
  38.             'kernel.request' => 'onKernelRequest',
  39.         ];
  40.     }
  41. }