You are here

public function Ip2CountrySettingsForm::submitForm in IP-based Determination of a Visitor's Country 8

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides ConfigFormBase::submitForm

File

src/Form/Ip2CountrySettingsForm.php, line 312

Class

Ip2CountrySettingsForm
Configure ip2country settings for this site.

Namespace

Drupal\ip2country\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state
    ->getValues();
  $ip2country_config = $this
    ->config('ip2country.settings');
  $ip2country_config
    ->setData([
    'watchdog' => (bool) $values['ip2country_watchdog'],
    'rir' => (string) $values['ip2country_rir'],
    'md5_checksum' => (bool) $values['ip2country_md5_checksum'],
    'update_interval' => (int) $values['ip2country_update_interval'],
    'batch_size' => (int) $values['ip2country_update_batch_size'],
    'debug' => (bool) $values['ip2country_debug'],
    'test_type' => (int) $values['ip2country_test_type'],
    'test_country' => (string) $values['ip2country_test_country'],
    'test_ip_address' => (string) $values['ip2country_test_ip_address'],
  ])
    ->save();

  // Check to see if debug set.
  if ($values['ip2country_debug']) {

    // Debug on.
    if ($values['ip2country_test_type']) {

      // Dummy IP Address.
      $ip = $values['ip2country_test_ip_address'];
      $country_code = $this->ip2countryLookup
        ->getCountry($ip);
    }
    else {

      // Dummy Country.
      $country_code = $values['ip2country_test_country'];
    }
    $country_list = $this->countryManager
      ->getList();
    $country_name = $country_list[$country_code];
    $this
      ->messenger()
      ->addMessage($this
      ->t('Using DEBUG value for Country - @country (@code)', [
      '@country' => $country_name,
      '@code' => $country_code,
    ]));
  }
  else {

    // Debug off - make sure we set/reset IP/Country to their real values.
    $ip = $this->currentRequest
      ->getClientIp();
    $country_code = $this->ip2countryLookup
      ->getCountry($ip);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Using ACTUAL value for Country - @country', [
      '@country' => $country_code,
    ]));
  }

  // Finally, save country, if it has been determined.
  if ($country_code) {

    // Store the ISO country code in the $user object.
    $account_id = $this->currentUser
      ->id();
    $account = User::load($account_id);
    $account->country_iso_code_2 = $country_code;
    $this->userData
      ->set('ip2country', $account_id, 'country_iso_code_2', $country_code);
  }
  parent::submitForm($form, $form_state);
}