Identify language via URL prefix or domain.
$languages: An array of valid language objects.
$request: The HttpRequest object representing the current request.
A valid language code on success, FALSE otherwise.
function language_from_url($languages, $request) {
$language_url = FALSE;
if (!language_negotiation_method_enabled(LANGUAGE_NEGOTIATION_URL)) {
return $language_url;
}
switch (config('language.negotiation')
->get('url.source')) {
case LANGUAGE_NEGOTIATION_URL_PREFIX:
$current_path = $request->attributes
->get('system_path');
if (!isset($current_path)) {
$current_path = trim($request
->getPathInfo(), '/');
}
list($language, $path) = language_url_split_prefix($current_path, $languages);
// Store the correct system path, i.e. minus the path prefix, in the
// request.
$request->attributes
->set('system_path', $path);
if ($language !== FALSE) {
$language_url = $language->langcode;
}
break;
case LANGUAGE_NEGOTIATION_URL_DOMAIN:
// Get only the host, not the port.
$http_host = $_SERVER['HTTP_HOST'];
if (strpos($http_host, ':') !== FALSE) {
$http_host_tmp = explode(':', $http_host);
$http_host = current($http_host_tmp);
}
$domains = language_negotiation_url_domains();
foreach ($languages as $language) {
// Skip the check if the language doesn't have a domain.
if (!empty($domains[$language->langcode])) {
// Ensure that there is exactly one protocol in the URL when checking
// the hostname.
$host = 'http://' . str_replace(array(
'http://',
'https://',
), '', $domains[$language->langcode]);
$host = parse_url($host, PHP_URL_HOST);
if ($http_host == $host) {
$language_url = $language->langcode;
break;
}
}
}
break;
}
return $language_url;
}