<?php declare(strict_types=1);
namespace Submarine\RedirectsBundle\EventSubscriber;
use Doctrine\ORM\ORMException;
use Submarine\RedirectsBundle\Repository\RedirectRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestSubscriber implements EventSubscriberInterface
{
/**
* @var RedirectRepository
*/
private $repository;
/**
* @param RedirectRepository $repository
*/
public function __construct(RedirectRepository $repository)
{
$this->repository = $repository;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [
['processRequest', 1024],
]
];
}
/**
* @param RequestEvent $event
* @throws ORMException
*/
public function processRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$url = $event->getRequest()->getRequestUri();
$redirect = $this->repository->findActiveRedirect($url);
if ($redirect) {
$response = new RedirectResponse($redirect->getRedirectUrl(), $redirect->getCode());
$event->setResponse($response);
}
}
}