SimpleSAML\Locale\Language::getLanguage PHP Method

getLanguage() public method

This method will return the language selected by the user, or the default language. It looks first for a cached language code, then checks for a language cookie, then it tries to calculate the preferred language from HTTP headers.
public getLanguage ( ) : string
return string The language selected by the user according to the processing rules specified, or the default language in any other case.
    public function getLanguage()
    {
        // language is set in object
        if (isset($this->language)) {
            return $this->language;
        }
        // run custom getLanguage function if defined
        if (isset($this->customFunction) && is_callable($this->customFunction)) {
            $customLanguage = call_user_func($this->customFunction, $this);
            if ($customLanguage !== null && $customLanguage !== false) {
                return $customLanguage;
            }
        }
        // language is provided in a stored cookie
        $languageCookie = Language::getLanguageCookie();
        if ($languageCookie !== null) {
            $this->language = $languageCookie;
            return $languageCookie;
        }
        // check if we can find a good language from the Accept-Language HTTP header
        $httpLanguage = $this->getHTTPLanguage();
        if ($httpLanguage !== null) {
            return $httpLanguage;
        }
        // language is not set, and we get the default language from the configuration
        return $this->getDefaultLanguage();
    }

Usage Example

 /**
  * Retrieve the preferred translation of a given text.
  *
  * @param array $translations The translations, as an associative array with language => text mappings.
  *
  * @return string The preferred translation.
  *
  * @throws \Exception If there's no suitable translation.
  */
 public function getPreferredTranslation($translations)
 {
     assert('is_array($translations)');
     // look up translation of tag in the selected language
     $selected_language = $this->language->getLanguage();
     if (array_key_exists($selected_language, $translations)) {
         return $translations[$selected_language];
     }
     // look up translation of tag in the default language
     $default_language = $this->language->getDefaultLanguage();
     if (array_key_exists($default_language, $translations)) {
         return $translations[$default_language];
     }
     // check for english translation
     if (array_key_exists('en', $translations)) {
         return $translations['en'];
     }
     // pick the first translation available
     if (count($translations) > 0) {
         $languages = array_keys($translations);
         return $translations[$languages[0]];
     }
     // we don't have anything to return
     throw new \Exception('Nothing to return from translation.');
 }
All Usage Examples Of SimpleSAML\Locale\Language::getLanguage