You are here

public function PiwikReportsSettings::validateForm in Piwik Reports 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/PiwikReportsSettings.php, line 98

Class

PiwikReportsSettings
Class PiwikReportsSettings.

Namespace

Drupal\piwik_reports\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  $url = $form_state
    ->getValue('piwik_server_url');
  if (!empty($url)) {
    if (substr($url, -1) !== '/') {
      $url .= '/';
      $form_state
        ->setValueForElement($form['piwik_reports_server']['piwik_server_url'], $url);
    }
    $url = $url . 'piwik.php';
    try {
      $result = \Drupal::httpClient()
        ->get($url);
      if ($result
        ->getStatusCode() != 200) {
        $form_state
          ->setErrorByName('piwik_server_url', $this
          ->t('The validation of "@url" failed with error "@error" (HTTP code @code).', [
          '@url' => UrlHelper::filterBadProtocol($url),
          '@error' => $result
            ->getReasonPhrase(),
          '@code' => $result
            ->getStatusCode(),
        ]));
      }
    } catch (RequestException $exception) {
      $form_state
        ->setErrorByName('piwik_server_url', $this
        ->t('The validation of "@url" failed with an exception "@error" (HTTP code @code).', [
        '@url' => UrlHelper::filterBadProtocol($url),
        '@error' => $exception
          ->getMessage(),
        '@code' => $exception
          ->getCode(),
      ]));
    }
  }
}