You are here

public function LanguageNegotiationUrl::getLangcode in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::getLangcode()
  2. 9 core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::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\LanguageNegotiation

Code

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;
}