src/EventSubscriber/RedirectLocale.php line 16

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\Routing\RouterInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. class RedirectLocale implements EventSubscriberInterface
  8. {
  9.     public function __construct(
  10.         private RouterInterface $router
  11.     ) {
  12.     }
  13.     public function onKernelController(RequestEvent $event): void
  14.     {
  15.         $routeName $event->getRequest()->attributes->get('_route');
  16.         $newRoute $routeName '_no_locale';
  17.         if ($event->getRequest()->getLocale() == $event->getRequest()->getDefaultLocale() && $this->router->getRouteCollection()->get($newRoute) && strstr($event->getRequest()->getUri(), "/".$event->getRequest()->getDefaultLocale())) {
  18.             $newurl str_replace("/".$event->getRequest()->getLocale(), ""$event->getRequest()->getUri());
  19.             $event->setResponse(new RedirectResponse($newurl301));
  20.         }
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             'kernel.request' => 'onKernelController',
  26.         ];
  27.     }
  28. }