<?php
namespace App\EventSubscriber;
use App\Entity\Redirection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class RedirectSubscriber implements EventSubscriberInterface
{
private $router;
private $token;
private $em;
private $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator,RouterInterface $router,TokenStorageInterface $token,EntityManagerInterface $em)
{
$this->router = $router;
$this->token = $token;
$this->em = $em;
$this->urlGenerator = $urlGenerator;
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$url = $request->getRequestUri();
if (strpos($url, '/control-panel-58e9ebc86109') === 0) {
return;
}
$redirection = $this->em->getRepository(Redirection::class)->findOneBy(['old'=>$url,'active'=>true]);
if(isset($redirection)){
$url = $redirection->getNew();
$response = new RedirectResponse($url,301);
$event->setResponse($response);
}
}
}