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. |
/** * 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.'); }
/** * Test SimpleSAML\Locale\Language::setLanguage(). */ public function testSetLanguage() { // test with valid configuration, no cookies set $c = \SimpleSAML_Configuration::loadFromArray(array('language.available' => array('en', 'nn', 'es'), 'language.parameter.name' => 'xyz', 'language.parameter.setcookie' => false), '', 'simplesaml'); $_GET['xyz'] = 'Es'; // test also that lang code is transformed to lower caps $l = new Language($c); $this->assertEquals('es', $l->getLanguage()); // test with valid configuration, no cookies, language set unavailable $_GET['xyz'] = 'unavailable'; $l = new Language($c); $this->assertEquals('en', $l->getLanguage()); }