public function LanguageNegotiationUrl::getLangcode in Drupal 9
Same name and namespace in other branches
- 8 core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::getLangcode()
Performs language negotiation.
Parameters
\Symfony\Component\HttpFoundation\Request $request: (optional) The current request. Defaults to NULL if it has not been initialized yet.
Return value
string A valid language code or FALSE if the negotiation was unsuccessful.
Overrides LanguageNegotiationMethodInterface::getLangcode
File
- core/
modules/ language/ src/ Plugin/ LanguageNegotiation/ LanguageNegotiationUrl.php, line 48
Class
- LanguageNegotiationUrl
- Class for identifying language via URL prefix or domain.
Namespace
Drupal\language\Plugin\LanguageNegotiationCode
public function getLangcode(Request $request = NULL) {
$langcode = NULL;
if ($request && $this->languageManager) {
$languages = $this->languageManager
->getLanguages();
$config = $this->config
->get('language.negotiation')
->get('url');
switch ($config['source']) {
case LanguageNegotiationUrl::CONFIG_PATH_PREFIX:
$request_path = urldecode(trim($request
->getPathInfo(), '/'));
$path_args = explode('/', $request_path);
$prefix = array_shift($path_args);
// Search prefix within added languages.
$negotiated_language = FALSE;
foreach ($languages as $language) {
if (isset($config['prefixes'][$language
->getId()]) && $config['prefixes'][$language
->getId()] == $prefix) {
$negotiated_language = $language;
break;
}
}
if ($negotiated_language) {
$langcode = $negotiated_language
->getId();
}
break;
case LanguageNegotiationUrl::CONFIG_DOMAIN:
// Get only the host, not the port.
$http_host = $request
->getHost();
foreach ($languages as $language) {
// Skip the check if the language doesn't have a domain.
if (!empty($config['domains'][$language
->getId()])) {
// Ensure that there is exactly one protocol in the URL when
// checking the hostname.
$host = 'http://' . str_replace([
'http://',
'https://',
], '', $config['domains'][$language
->getId()]);
$host = parse_url($host, PHP_URL_HOST);
if ($http_host == $host) {
$langcode = $language
->getId();
break;
}
}
}
break;
}
}
return $langcode;
}