src/EventSubscriber/RedirectSubscriber.php line 58

Open in your IDE?
  1. <?php 
  2. namespace App\EventSubscriber;
  3. use App\Entity\Redirection;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\Routing\RouterInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. class RedirectSubscriber implements EventSubscriberInterface
  12. {
  13.  
  14.     private $router;
  15.     private $token;
  16.     private $em;
  17.     private $urlGenerator;
  18.     public function __construct(UrlGeneratorInterface $urlGenerator,RouterInterface $router,TokenStorageInterface $token,EntityManagerInterface $em)
  19.     {
  20.         $this->router $router;
  21.         $this->token $token;
  22.         $this->em $em;
  23.         $this->urlGenerator $urlGenerator;
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             RequestEvent::class => 'onKernelRequest',
  29.         ];
  30.     }
  31.     public function onKernelRequest(RequestEvent $event)
  32.     {
  33.         $request $event->getRequest();
  34.         // if($request->attributes->get('_route') == 'page'){
  35.         //     $slug = $request->attributes->get('_route_params')['slug'];
  36.         //     $redirection = $this->em->getRepository(Redirection::class)->findOneBy(['old'=>$slug,'active'=>true]);
  37.         //     if(isset($redirection)){
  38.         //         $url = $redirection->getNew();
  39.         //         $response = new RedirectResponse($url);
  40.         //         $event->setResponse($response);
  41.         //     }
  42.         // }
  43.         // $route_name = $request->attributes->get('_route');
  44.         // $slug = $request->attributes->get('_route_params')['slug'];
  45.         // $url = $this->urlGenerator->generate($route_name, ['slug'=> $slug]);
  46.   
  47.         $url $request->getRequestUri();
  48.         $redirection $this->em->getRepository(Redirection::class)->findOneBy(['old'=>$url,'active'=>true]);
  49.         if(isset($redirection)){
  50.             $url $redirection->getNew();
  51.             $response = new RedirectResponse($url,301);
  52.             $event->setResponse($response);
  53.         }
  54.         
  55.     }
  56. }