You are here

public function MatomoReportsSettings::validateForm in Matomo 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/MatomoReportsSettings.php, line 126

Class

MatomoReportsSettings
Class MatomoReportsSettings.

Namespace

Drupal\matomo_reports\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  $url = $form_state
    ->getValue('matomo_server_url');
  if (!empty($url)) {
    if (substr($url, -strlen('/')) !== '/') {
      $url .= '/';
      $form_state
        ->setValueForElement($form['matomo_reports_server']['matomo_server_url'], $url);
    }
    $url = $url . 'piwik.php';
    try {
      $result = $this->httpClient
        ->get($url);
      if ($result
        ->getStatusCode() != 200) {
        $form_state
          ->setErrorByName('matomo_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('matomo_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(),
      ]));
    }
  }
}