You are here

public function SettingsForm::validateForm in CloudFlare 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/SettingsForm.php, line 302

Class

SettingsForm
Class SettingsForm.

Namespace

Drupal\cloudflare\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {

  // Get the email address and apikey.
  $email = trim($form_state
    ->getValue('email'));
  $apikey = trim($form_state
    ->getValue('apikey'));

  // Validate the email address.
  if (!$this->emailValidator
    ->isValid($email)) {
    $form_state
      ->setErrorByName('email', $this
      ->t('Please enter a valid e-mail address.'));
    return;
  }
  try {

    // Confirm that the credentials can authenticate with the CloudFlareApi.
    $this->zoneApi
      ->assertValidCredentials($apikey, $email, $this->cloudFlareComposerDependenciesCheck, $this->state);
  } catch (CloudFlareTimeoutException $e) {
    $message = $this
      ->t('Unable to connect to CloudFlare in order to validate credentials. Connection timed out. Please try again later.');
    $form_state
      ->setErrorByName('apikey', $message);
    $this->logger
      ->error($message);
    return;
  } catch (CloudFlareInvalidCredentialException $e) {
    $form_state
      ->setErrorByName('apiKey', $e
      ->getMessage());
    return;
  } catch (CloudFlareException $e) {
    $form_state
      ->setErrorByName('apikey', $this
      ->t("An unknown error has occurred when attempting to connect to CloudFlare's API") . $e
      ->getMessage());
    return;
  }

  // Validate the bypass host.
  $bypass_host = trim($form_state
    ->getValue('bypass_host'));
  if (!empty($bypass_host)) {

    // Validate the bypass host does not begin with http.
    if (strpos($bypass_host, 'http') > -1) {
      $form_state
        ->setErrorByName('$bypass_host', $this
        ->t('Please enter a host without http/https'));
      return;
    }

    // Validate the host domain.
    try {
      Url::fromUri("http://{$bypass_host}");
    } catch (\InvalidArgumentException $e) {
      $form_state
        ->setErrorByName('bypass_host', $this
        ->t('You have entered an invalid host.'));
      return;
    }
  }
}