src/EventSubscriber/LocaleRedirectSubscriber.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. class LocaleRedirectSubscriber implements EventSubscriberInterface
  8. {
  9.     private $defaultLocale;
  10.     public function __construct(string $defaultLocale)
  11.     {
  12.         $this->defaultLocale $defaultLocale;
  13.     }
  14.     public function onKernelRequest(RequestEvent $event)
  15.     {
  16.         $request $event->getRequest();
  17.         // Verificar si la ruta no contiene el prefijo del idioma
  18.         $locale $request->getLocale();
  19.         if (!$request->attributes->get('_route') || strpos($request->getPathInfo(), "/$locale/") !== 0) {
  20.             // Obtener el idioma por defecto
  21.             $defaultLocale $this->defaultLocale;
  22.             // Verificar si ya estamos en la URL deseada para evitar redirecciones infinitas
  23.             if ($locale !== $defaultLocale) {
  24.                 // Redirigir al usuario a la misma ruta con el prefijo del idioma por defecto
  25.                 $url $request->getSchemeAndHttpHost() . '/' $defaultLocale $request->getPathInfo();
  26.                 $event->setResponse(new RedirectResponse($url));
  27.             }
  28.         }
  29.     }
  30.     public static function getSubscribedEvents()
  31.     {
  32.         return [
  33.             KernelEvents::REQUEST => 'onKernelRequest',
  34.         ];
  35.     }
  36. }