Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When multiple locales are used, it only works with the default one #11

Open
vvasiloi opened this issue Nov 4, 2019 · 0 comments
Open

Comments

@vvasiloi
Copy link

vvasiloi commented Nov 4, 2019

The Sylius\Bundle\LocaleBundle\Context\RequestBasedLocaleContext gets the locale from the _locale request attribute, which is set after the route is matched, since it's a path parameter, therefore it's no available during the route matching.
Because this context does not return a locale, the next context Sylius\Component\Locale\Cont ext\ProviderBasedLocaleContext will return the default one.

Temporary solution:

namespace App\Context;

use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Locale\Context\LocaleNotFoundException;
use Sylius\Component\Locale\Provider\LocaleProviderInterface;
use Symfony\Component\HttpFoundation\RequestStack;

final class UrlBasedLocaleContext implements LocaleContextInterface
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * @var LocaleProviderInterface
     */
    private $localeProvider;

    /**
     * @param RequestStack $requestStack
     * @param LocaleProviderInterface $localeProvider
     */
    public function __construct(RequestStack $requestStack, LocaleProviderInterface $localeProvider)
    {
        $this->requestStack = $requestStack;
        $this->localeProvider = $localeProvider;
    }

    /**
     * @throws LocaleNotFoundException
     */
    public function getLocaleCode(): string
    {
        $request = $this->requestStack->getMasterRequest();

        if (null === $request) {
            throw new LocaleNotFoundException('No master request available.');
        }

        $pathInfo = $request->getPathInfo();
        $availableLocalesCodes = $this->localeProvider->getAvailableLocalesCodes();

        foreach ($availableLocalesCodes as $localeCode) {
            if (false !== strpos($pathInfo, sprintf('/%s/', $localeCode))) {
                return $localeCode;
            }
        }

        throw new LocaleNotFoundException('No available locale found in the url.');
    }
}
services:
    App\Context\UrlBasedLocaleContext:
        tags:
            - { name: sylius.context.locale, priority: -64 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant