You are here

public function IpLanguageNegotiationLanguageNegotiationIp::getLangcode in IP Language Negotiation 8

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

src/Plugin/LanguageNegotiation/IpLanguageNegotiationLanguageNegotiationIp.php, line 29

Class

IpLanguageNegotiationLanguageNegotiationIp
Class for identifying language from the IP address.

Namespace

Drupal\ip_language_negotiation\Plugin\LanguageNegotiation

Code

public function getLangcode(Request $request = NULL) {
  $langcode = NULL;
  if ($request && $this->languageManager) {

    // Disable caching for this page. This only happens when negotiating
    // based on IP. Once the redirect took place to the correct domain
    // or language prefix, this function is not reached anymore and
    // caching works as expected.
    \Drupal::service('page_cache_kill_switch')
      ->trigger();
    $countries = $this->config
      ->get('ip_language_negotiation.settings')
      ->get('ip_language_negotiation_countries') ?: [];
    $current_ip = $request
      ->getClientIp();

    // Check for debug settings. If enabled, use it.
    if (\Drupal::config('ip2country.settings')
      ->get('debug')) {

      // Debug Country entered.
      if (\Drupal::config('ip2country.settings')
        ->get('test_type') == 0) {
        $country_code = \Drupal::config('ip2country.settings')
          ->get('test_country') ?: 'US';
      }
      else {
        $ip = \Drupal::config('ip2country.settings')
          ->get('test_ip_address') ?: $current_ip;
        $country_code = ip2country_get_country($ip);
      }
    }
    else {
      $country_code = ip2country_get_country($current_ip);
    }
    if (!empty($country_code)) {

      // Check if a language is set for the determined country.
      if (!empty($countries[$country_code])) {
        $langcode = $countries[$country_code];
      }
    }
  }
  return $langcode;
}