<?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();
// if($request->attributes->get('_route') == 'page'){
// $slug = $request->attributes->get('_route_params')['slug'];
// $redirection = $this->em->getRepository(Redirection::class)->findOneBy(['old'=>$slug,'active'=>true]);
// if(isset($redirection)){
// $url = $redirection->getNew();
// $response = new RedirectResponse($url);
// $event->setResponse($response);
// }
// }
// $route_name = $request->attributes->get('_route');
// $slug = $request->attributes->get('_route_params')['slug'];
// $url = $this->urlGenerator->generate($route_name, ['slug'=> $slug]);
$url = $request->getRequestUri();
$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);
}
}
}