<?php
namespace App\EventSubscriber;
use App\Repository\RedirectRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RedirectSubscriber implements EventSubscriberInterface
{
/**
* @var RedirectRepository
*/
private $redirectRepository;
public function __construct(RedirectRepository $redirectRepository)
{
$this->redirectRepository = $redirectRepository;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 110],
];
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$redirect = $this->redirectRepository->findOneBy([
'whereFrom' => $event->getRequest()->getRequestUri()
]);
if ($redirect) {
$event->setResponse(
new RedirectResponse($redirect->getWhereTo(), $redirect->getHttpCode())
);
}
}
}