How to get the user's browser locale?

I am using multisite.
One of the site is defined with the French language.
And I want my theme supported on this site to be able to handle the user’s browser language and not the site definition language.

How can I achieve that please ?

There is a method called getLocalesFromBrowser you can use

// Returns a sorted array in format of `[(string) locale => (float) priority]`
$supported = Site::getLocalesFromBrowser();
3 Likes

What type is Site please ?
I tried Site, SiteDefinition, SiteManager but all gives me an error on the method call.
And when I search the method name getLocalesFromBrowser in all the php code, i cant find this method name.

Hi @chris ,

\modules\system\classes\sitemanager\HasPreferredLanguage.php

/**
     * getLocalesFromBrowser based on an accepted string, e.g. en-GB,en-US;q=0.9,en;q=0.8
     * Returns a sorted array in format of `[(string) locale => (float) priority]`
     */
    public function getLocalesFromBrowser(string $acceptedStr): array
    {
        $result = $matches = [];
        $acceptedStr = strtolower($acceptedStr);

        // Find explicit matches
        preg_match_all('/([\w-]+)(?:[^,\d]+([\d.]+))?/', $acceptedStr, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
            $locale = $match[1] ?? '';
            $priority = (float) ($match[2] ?? 1.0);

            if ($locale) {
                $result[$locale] = $priority;
            }
        }

        // Estimate other locales by popping off the region (en-us -> en)
        foreach ($result as $locale => $priority) {
            $shortLocale = explode('-', $locale)[0];
            if ($shortLocale !== $locale && !array_key_exists($shortLocale, $result)) {
                $result[$shortLocale] = $priority - 0.1;
            }
        }

        arsort($result);
        return $result;
    }

thanks @apinard
so its not a static function indeed, so how can Site::getLocalesFromBrowser() work ?

Site is a facade that refers to an instance in the Laravel container, and that contains an instance of the SiteManager class. This is what allows it to be called statically.

1 Like