<?php
namespace App\EventSubscriber;
use App\Component\Configuration\Util\Config;
use App\Entity\Redirect;
use App\Repository\RedirectRepository;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class RedirectSubscriber implements EventSubscriberInterface
{
private Config $config;
private RedirectRepository $redirectRepository;
public function __construct(Config $config, EntityManagerInterface $entityManager)
{
$this->config = $config;
$this->redirectRepository = $entityManager->getRepository(Redirect::class);
}
public function onKernelRequest(RequestEvent $event)
{
if (!$this->config->get('site_redirects_active') || !$pathInfo = $event->getRequest()->getPathInfo()) {
return;
}
if (str_starts_with($pathInfo, '/admin') || !$redirect = $this->redirectRepository
->findOneBy(['source' => $pathInfo], ['id' => Criteria::DESC])) {
return;
}
$event->setResponse(new RedirectResponse(
$redirect->getDestination(),
$redirect->isPermanent() ? Response::HTTP_MOVED_PERMANENTLY : Response::HTTP_FOUND
));
}
public static function getSubscribedEvents(): array
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}