You are here

public function Domain301RedirectConfigForm::validateForm in Domain 301 Redirect 8

Form validation 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 FormBase::validateForm

File

src/Form/Domain301RedirectConfigForm.php, line 180

Class

Domain301RedirectConfigForm
Provides a settings for domain_301_redirect module.

Namespace

Drupal\domain_301_redirect\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $config = $this
    ->config('domain_301_redirect.settings');
  $values = $form_state
    ->getValues();
  if (!empty($values['enabled'])) {

    // Clean & trim the domain.
    $domain = trim(trim($values['domain']), '/');
    if (!preg_match('|^https?://|', $domain)) {
      $domain = 'http://' . $domain;
    }
    if (!UrlHelper::isValid($domain, TRUE)) {
      $form_state
        ->setErrorByName('domain', $this
        ->t('Domain 301 redirection can not be enabled if a valid domain is not set.'));
    }
    else {
      $domain_parts = parse_url($domain);
      $domain = $domain_parts['scheme'] . '://' . $domain_parts['host'] . (!empty($domain_parts['port']) ? ':' . $domain_parts['port'] : '');
      $form_state
        ->set('domain', $domain);
      if (!$this->redirectManager
        ->checkDomain($domain)) {
        $form_state
          ->setErrorByName('enabled', $this
          ->t('Domain 301 redirection can not be enabled as the domain you set does not currently point to this site.'));
      }
      else {

        // Clean up if someone is manually disabling. We don't want the system
        // to re-enable if the disabling was via the admin form.
        $this
          ->config('domain_301_redirect.settings')
          ->set('disabled_by_check', FALSE)
          ->save();
      }
      $redirect_count = 0;
      if ($this->redirectManager
        ->checkRedirectLoop($domain, $redirect_count)) {
        $form_state
          ->setErrorByName('domain', $this
          ->t('Domain 301 redirection can not be enabled as the domain you set does not currently point to this site.', [
          '@num' => $config
            ->get('loop_max_redirects'),
        ]));
      }
      elseif ($redirect_count > 0) {
        $this
          ->messenger()
          ->addWarning($this
          ->t('The redirect domain follows @count redirects. You may want to specify the final domain.', [
          '@count' => $redirect_count,
        ]));
      }
    }
  }
  parent::validateForm($form, $form_state);
}