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

[11.x] Add derived fallback locale support #54465

Closed
wants to merge 2 commits into from

Conversation

olivermbs
Copy link

@olivermbs olivermbs commented Feb 4, 2025

This PR adds support for derived fallback locales when setting the application locale. For example, when using 'de_CH', you can optionally have it automatically determine 'de' as a fallback locale.

Added a new $useDerivedFallback parameter to setLocale():

public function setLocale($locale, $useDerivedFallback = false)
{
    $this['config']->set('app.locale', $locale);

    $this['translator']->setLocale($locale);

    $this['events']->dispatch(new LocaleUpdated($locale));

    if ($useDerivedFallback) {
        $primaryLanguage = substr($locale, 0, 2);

        if ($primaryLanguage !== $locale) {
            $this->setFallbackLocale($primaryLanguage);
        }
    }
}

@olivermbs olivermbs changed the title [11.x] Add derived locale support [11.x] Add derived fallback locale support Feb 4, 2025
@shaedrich
Copy link
Contributor

shaedrich commented Feb 4, 2025

Keep in mind, that locales can not only be de and de_CH, they can also have more segments.

It also raises the question if the passed in locale should be validated

public function setLocale($locale)
{
    if (!ctype_lower(substr($locale, 0, 2)) || (strlen($locale) > 2 && substr($locale, 2, 1) !== '_') || (strlen($locale) > 3 && !ctype_upper(substr($locale, 3, 2)))) {
        throw new InvalidArgumentException('Not a valid locale');
    }

which then would open the opportunity to

  • replace - with _
  • change case of the segments to allow for case insensitive processing later on

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

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

Successfully merging this pull request may close these issues.

3 participants