src/EventSubscriber/RedirectSubscriber.php line 38

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. private $router;
  14. private $token;
  15. private $em;
  16. private $urlGenerator;
  17. public function __construct(UrlGeneratorInterface $urlGenerator,RouterInterface $router,TokenStorageInterface $token,EntityManagerInterface $em)
  18. {
  19. $this->router = $router;
  20. $this->token = $token;
  21. $this->em = $em;
  22. $this->urlGenerator = $urlGenerator;
  23. }
  24. public static function getSubscribedEvents(): array
  25. {
  26. return [
  27. RequestEvent::class => 'onKernelRequest',
  28. ];
  29. }
  30. public function onKernelRequest(RequestEvent $event)
  31. {
  32. $request = $event->getRequest();
  33. $url = $request->getRequestUri();
  34. if (strpos($url, '/control-panel-58e9ebc86109') === 0) {
  35. return;
  36. }
  37. $redirection = $this->em->getRepository(Redirection::class)->findOneBy(['old'=>$url,'active'=>true]);
  38. if(isset($redirection)){
  39. $url = $redirection->getNew();
  40. $response = new RedirectResponse($url,301);
  41. $event->setResponse($response);
  42. }
  43. }
  44. }