0

I am working on a Symfony(4.4) project. I am trying to make eventSubscriber that will redirect user with locale based on saved cookie. The idea is when I visit homepage for first time(or if I have not saved cookie) I have to redirect myself to homepage with the default locale(which is 'en' in my case). When I change the locale I save the new locale in cookie (for example my cookie is "LOCALE" => 'de'). When I enter in homepage next time I have to redirect myself with the 'de' locale(because it's saved on the cookie). When I set the priority to 32+ I get redirect to the default locale instead the cookie locale(I receive the cookie content, so the problem is not from the cookie), else if I set the priority before 32 I get the error "Route not found for '/' " https://i.stack.imgur.com/NXfem.jpg. For now I made this:

I added new method in RequestSubscriber:

public function redirectToCookieLocale(RequestEvent $event)
{
    if ($event->isMasterRequest() === false) {
        return;
    }

    $request = $event->getRequest();
    $path = $event->getRequest()->getPathInfo();

    $cookieLocale = $request->cookies->get('LOCALE');
    if ($cookieLocale != null && $this->isValidLocale($cookieLocale)) {
        $locale = $request->cookies->get('LOCALE');
    } else {
        $locale = $request->getDefaultLocale();
    }

    if ($path == '/') {
        $event->setResponse(new RedirectResponse(
            $this->generator->generate(
                'frontend_index',
                ['_locale' => $locale]
            ),
            301
        ));
    }
}

public static function getSubscribedEvents(): array
{
    return [
        KernelEvents::REQUEST => [
            ['redirectToCookieLocale', 30]
        ]
    ];
}

Also I created ResponseSubscriber where I create the cookie:

public function onKernelResponse(ResponseEvent $event)
    {
        $request = $event->getRequest();
        $response = $event->getResponse();

        if ($response->isRedirection()) {
            return;
        }

        $urlLocale = $request->get('_locale');
        $cookieLocale = $request->cookies->get('LOCALE');

        if ($urlLocale != null && $urlLocale != $cookieLocale) {
            $cookie = new Cookie('LOCALE', $request->getLocale(), (time() + 3600 * 24 * 7), '/', '', '', false);
            $response->headers->setCookie($cookie);
        }
    }


public static function getSubscribedEvents(): array
{
    return [
        KernelEvents::RESPONSE => [
            ['onKernelResponse', 0],
        ],
    ];
}
Dan
  • 52
  • 7
  • From the Symfony docs you can do it [like this](https://symfony.com/doc/current/translation/locale.html#the-locale-and-the-url) instead of a subscriber.. The locale is set in the users request, you can still use a cookie and check if it is set if the user wants to set their language to something other than their own operating system. – Bossman Sep 20 '22 at 10:03

0 Answers0