You are here

public function RateSettingsForm::validateForm in Rate 8

Same name and namespace in other branches
  1. 8.2 src/Form/RateSettingsForm.php \Drupal\rate\Form\RateSettingsForm::validateForm()

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/RateSettingsForm.php, line 209

Class

RateSettingsForm
Configure rate settings for the site.

Namespace

Drupal\rate\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $messenger = $this
    ->messenger();
  if ($form_state
    ->getValue([
    'botscout_key',
  ])) {
    $uri = "http://botscout.com/test/?ip=84.16.230.111&key=" . $form_state
      ->getValue([
      'botscout_key',
    ]);
    try {
      $response = $this->httpClient
        ->get($uri, [
        'headers' => [
          'Accept' => 'text/plain',
        ],
      ]);
      $data = (string) $response
        ->getBody();
      $status_code = $response
        ->getStatusCode();
      if (empty($data)) {
        $messenger
          ->addWarning($this
          ->t('An empty response was returned from botscout.'));
      }
      elseif ($status_code == 200) {
        if (in_array(substr($data, 0, 1), [
          'Y',
          'N',
        ], TRUE)) {
          $messenger
            ->addStatus($this
            ->t('Rate has succesfully contacted the BotScout server.'));
        }
        else {
          $form_state
            ->setErrorByName('botscout_key', $this
            ->t('Invalid API-key.'));
        }
      }
      else {
        $messenger
          ->addWarning($this
          ->t('Rate was unable to contact the BotScout server.'));
      }
    } catch (RequestException $e) {
      $messenger
        ->addWarning($this
        ->t('An error occurred contacting BotScout.'));
      watchdog_exception('rate', $e);
    }
  }
}