Choose Locale

Try to match preferred and supported locales/languages

@param   string  $preferred  Preferred locales or languages, e.g. Accept-Language header
@return  bool
@access  public
@author  a.schmidt@internet-of-voice.de
977911
public function chooseLocale($preferred) {
        $available_locales   = array_flip($this->locales);
        $available_languages = array();
        foreach($available_locales as $key => $value) {
            $available_languages[substr($key, 0, 2)] = $key;
        }

        preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', $preferred, $matches, PREG_SET_ORDER);

        $matched_locales = array();
        foreach($matches as $match) {
            $temp  = explode('-', $match[1]);
            $lang  = array_shift($temp);
            $value = isset($match[2]) ? (float)$match[2] : 1.0;

            // Full match (language_territory)?
            if(isset($available_locales[$match[1]]) && !isset($matched_locales[$match[1]])) {
                $matched_locales[$match[1]] = $value;
            }

            // Language match (without territory)?
            if(isset($available_languages[$lang]) && !isset($matched_locales[$available_languages[$lang]])) {
                $matched_locales[$available_languages[$lang]] = $value - 0.05;
            }
        }

        if(count($matched_locales)) {
            arsort($matched_locales);
            $this->setLocale(key($matched_locales));
            return true;
        } else {
            $this->setLocale($this->locale_default);
            return false;
        }
    }
396011
private function askDefaultLocale(): string
    {
        $io = new SymfonyStyle(new ArgvInput(), new ConsoleOutput());

        return $io->ask(
            'Please input the default locale for existing layouts',
            '',
            static function (string $locale): string {
                if (!Locales::exists($locale)) {
                    throw new RuntimeException('Specified locale is not valid');
                }

                return $locale;
            }
        );
    }
1038272
private function checkLocaleSet() {
		
		if (!$this->defaultLocale) {
			
			$locale = Locale::getDefault();
			$this->defaultLocale = $locale;
			
			// server variable
			setlocale(LC_ALL, $locale->getRepresentation());
			
		}
		
		if (!$this->currentLocale) {
			
			// temporary sets default locale as current
			$this->currentLocale = $this->defaultLocale;
			
			// gets favorite language from browser settings
			if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
			
				preg_match_all('/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?' .
						'(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i',
						$_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches, PREG_SET_ORDER);
			
				// if browser’s lang matches and it’s different by current, will set as current
				if (!isset($matches[0][1]) or $this->currentLocale->getLanguage()->code == $matches[0][1]) {
					return;
				}
				
				$locale = Locale::getDefaultByLanguage($matches[0][1]);
				if (!$locale) {
					return;
				}
				
				$this->setLocale($locale);
					
			}

		}
		
	}
57540
public function supportedLocale($sValue)
    {
        /** @var Locale $oLocale */
        $oLocale           = Factory::service('Locale');
        $aSupportedLocales = $oLocale->getSupportedLocales();
        if (!in_array($sValue, $aSupportedLocales)) {
            $this->set_message('supportedLocale', 'This is not a supported locale');
            return false;
        }

        return true;
    }
1065581
public function getPreferredLanguage(array $locales = null)
    {
        $preferredLanguages = $this->getLanguages();

        if (empty($locales)) {
            return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
        }

        if (!$preferredLanguages) {
            return $locales[0];
        }

        $extendedPreferredLanguages = [];
        foreach ($preferredLanguages as $language) {
            $extendedPreferredLanguages[] = $language;
            if (false !== $position = strpos($language, '_')) {
                $superLanguage = substr($language, 0, $position);
                if (!\in_array($superLanguage, $preferredLanguages)) {
                    $extendedPreferredLanguages[] = $superLanguage;
                }
            }
        }

        $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));

        return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
    }
1348213
public function getClientPreferredLocale()
    {
        if (null !== $this->locale) {
            $locale = $this->locale;

        } else {
            // Get detector
            $detector = $this->getDetector();

            // Detect user's preferred locale
            $detector->detect();

            // get the locale from detector
            $locale = $detector->getLocale();
        }

        // return the active locale
        return $locale;
    }
290735
public static function setLocale(string $locale)
    {
        self::$runtimeLocale = self::getCompatibleLocale($locale);
        Response::setCookieHttpOnly(Language::LANGUAGE_COOKIE_NAME, self::$runtimeLocale);
    }
26778
def user_preferred_languages
      return [] if header.to_s.strip.empty?
      @user_preferred_languages ||= begin
        header.to_s.gsub(/\s+/, '').split(',').map do |language|
          locale, quality = language.split(';q=')
          raise ArgumentError, 'Not correctly formatted' unless locale =~ /^[a-z\-0-9]+|\*$/i

          locale  = locale.downcase.gsub(/-[a-z0-9]+$/i, &:upcase) # Uppercase territory
          locale  = nil if locale == '*' # Ignore wildcards

          quality = quality ? quality.to_f : 1.0

          [locale, quality]
        end.sort do |(_, left), (_, right)|
          right <=> left
        end.map(&:first).compact
      rescue ArgumentError # Just rescue anything if the browser messed up badly.
        []
      end
    end
509671
protected function preferredLocale($notifiable, $notification)
    {
        return $notification->locale ?? $this->locale ?? value(function () use ($notifiable) {
            if ($notifiable instanceof HasLocalePreference) {
                return $notifiable->preferredLocale();
            }
        });
    }
1047924
public function getBeginEndPreferredLabelPair( $preferredLabel )
	{
		if ( ! $preferredLabel ) return false;

		return array_filter( $this->getBeginEndPreferredLabelPairs(), function( $pair ) use( $preferredLabel )
		{
			return in_array( $preferredLabel, $pair );
		} );
	}
789010
public function findDefaultByContentLocale( $contentId,
                                                $locale,
                                                $preferredSubdomainId = null )
    {
        $locale = (string) $locale;
        $priLng = Locale::getPrimaryLanguage( $locale );

        if ( $priLng != $locale )
        {
            $locale = array( $locale, $priLng );
        }

        $platform = $this->getDbAdapter()
                         ->getPlatform();

        return $this->findOne( array(
            'contentId'     => $contentId,
            'locale'        => $locale,
        ), array(
            new Expression(
                'CASE ' . $platform->quoteIdentifier( 'subdomainId' ) .
                    ' WHEN ? THEN 1 ELSE 0 END DESC',
                array( (int) $preferredSubdomainId ),
                array( Expression::TYPE_VALUE )
            ),
            'locale'    => 'DESC',
            'default'   => 'DESC',
            'id'        => 'ASC',
        ) );
    }
919751
public static function setLanguage($language)
    {
        if (! ($language instanceof Language)) {
            $language = Language::findByCode($language);
        }

        if (! $language) {
            return false;
        }

        App::setLocale($language->code);
        request()->setDefaultLocale($language->code);
        self::$language = $language;

        return $language;
    }
567268
def select_locale_by_request(self, request, locales=()):
        """"""
        default_locale = locales and locales[0] or self.cfg.default_locale

        if len(locales) == 1 or 'ACCEPT-LANGUAGE' not in request.headers:
            return default_locale

        ulocales = [
            (q, locale_delim_re.split(v)[0])
            for v, q in parse_accept_header(request.headers['ACCEPT-LANGUAGE'])
        ]
        ulocales.sort()
        ulocales.reverse()

        for locale in locales:
            for _, ulocale in ulocales:
                ulocale = locale_delim_re.split(ulocale)[0]
                if ulocale.lower() == locale.lower():
                    return ulocale

        return ulocales[0][1]
1032831
public static Locale getLocaleToBeUsed(final UiProperties.Localization localizationProperties,
            final Locale desiredLocale) {
        final List<String> availableLocals = localizationProperties.getAvailableLocals();
        // ckeck if language code of UI locale matches an available local.
        // Country, region and variant are ignored. "availableLocals" must only
        // contain language codes without country or other extensions.
        if (availableLocals.contains(desiredLocale.getLanguage())) {
            return desiredLocale;
        }
        return new Locale(localizationProperties.getDefaultLocal());
    }
1172224
function (countries, preferred, preferredDelim) {
        var preferredShortCodes = preferred.split(',').reverse();
        var preferredMap = {};
        var foundPreferred = false;

        var updatedCountries = countries.filter(function (c) {
            if (preferredShortCodes.indexOf(c[1]) !== -1) {
                preferredMap[c[1]] = c;
                foundPreferred = true;
                return false;
            }
            return true;
        });

        if (foundPreferred && preferredDelim) {
            updatedCountries.unshift([preferredDelim, "", "", {}, true]);
        }

        // now prepend the preferred countries
        for (var i=0; i<preferredShortCodes.length; i++) {
            var code = preferredShortCodes[i];
            updatedCountries.unshift(preferredMap[code]);
        }

        return updatedCountries;
    }
60018
public function setLocale($locale = null)
    {
        if (empty($locale) || ! is_string($locale)) {
            // If the locale has not been passed through the function
            // it tries to get it from the first segment of the url
            $locale = $this->request()->segment(1);
        }

        if ($this->isSupportedLocale($locale)) {
            $this->setCurrentLocale($locale);
        }
        else {
            // if the first segment/locale passed is not valid the system would ask which locale have to take
            // it could be taken by the browser depending on your configuration
            $locale = null;

            $this->getCurrentOrDefaultLocale();
        }

        $this->app->setLocale($this->getCurrentLocale());
        $this->updateRegional();

        return $locale;
    }
895926
public function setSupportedLocales(array $supportedLocales)
    {
        if ( ! is_array($supportedLocales) || empty($supportedLocales))
            throw new UndefinedSupportedLocalesException;

        $this->supportedLocales = $this->filterLocales($supportedLocales);

        return $this;
    }