You are here

public function OembedProviderForm::validateForm in oEmbed Providers 1.1.x

Same name and namespace in other branches
  1. 2.x src/OembedProviderForm.php \Drupal\oembed_providers\OembedProviderForm::validateForm()
  2. 1.0.x src/OembedProviderForm.php \Drupal\oembed_providers\OembedProviderForm::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/OembedProviderForm.php, line 312

Class

OembedProviderForm
Form controller for the oEmbed provider edit/add forms.

Namespace

Drupal\oembed_providers

Code

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

  // If validation is triggered by an AJAX action, then skip validation.
  $trigger = $form_state
    ->getTriggeringElement();
  if (in_array('remove_endpoint', $trigger['#parents']) || in_array('add_endpoint', $trigger['#parents'])) {
    $form_state
      ->clearErrors();
    return;
  }
  parent::validateForm($form, $form_state);
  $values = $form_state
    ->getValues();
  unset($values['endpoints']['actions']);

  // Loop through endpoints.
  foreach ($values['endpoints'] as $endpoint_id => $endpoint_value) {

    // Convert schemes from string delimited by returns to indexed array.
    $schemes = preg_split('/\\R/', $endpoint_value['schemes']);
    foreach ($schemes as $key => $scheme) {

      // Verify schemes are valid URLs.
      if (!$this
        ->urlIsValid($scheme)) {
        $form_state
          ->setError($form['endpoints'][$endpoint_id]['schemes'], $this
          ->t('A valid URL is required on line @line.', [
          '@line' => $key + 1,
        ]));
      }

      // Validate scheme URL.
      // Mimic Drupal\media\OEmbed\Endpoint::__construct() in how the
      // `{format}` string is handled.
      $endpoint_url = str_replace('{format}', 'format', $endpoint_value['url']);
      if (!UrlHelper::isValid($endpoint_url)) {
        $form_state
          ->setError($form['endpoints'][$endpoint_id]['url'], $this
          ->t('The URL @url is not valid.', [
          '@url' => $endpoint_url,
        ]));
      }
    }

    // Either discovery or formats is required.
    if (empty($endpoint_value['discovery']) && empty($endpoint_value['formats']['json']) && empty($endpoint_value['formats']['xml'])) {
      $form_state
        ->setError($form['endpoints'][$endpoint_id]['formats'], $this
        ->t('If discovery is disabled, then one or more formats must be explicitly defined for an endpoint.'));
    }
  }
}