You are here

public static function LinkAutocompleteFormTrait::validateLinkAutocompleteElement in Helper 8

Validation callback for URL elements.

File

src/LinkAutocompleteFormTrait.php, line 55

Class

LinkAutocompleteFormTrait
Provides helpers for adding a content autocomplete link element to a form.

Namespace

Drupal\helper

Code

public static function validateLinkAutocompleteElement(&$element, FormStateInterface $form_state) {
  if (!empty($element['#value'])) {
    $uri = static::getUserEnteredStringAsUri($element['#target_type'], $element['#value']);
    $form_state
      ->setValueForElement($element, $uri);

    // @see \Drupal\link\Plugin\Field\FieldWidget\LinkWidget::validateUriElement()
    // If getUserEnteredStringAsUri() mapped the entered value to a
    // 'internal:' URI , ensure the raw value begins with '/', '?' or '#'.
    // @todo '<front>' is valid input for BC reasons, may be removed by https://www.drupal.org/node/2421941
    $valid_starting_internal_chars = [
      '/',
      '?',
      '#',
    ];
    if (parse_url($uri, PHP_URL_SCHEME) === 'internal' && !in_array($element['#value'][0], $valid_starting_internal_chars, TRUE) && substr($element['#value'], 0, 7) !== '<front>') {
      $form_state
        ->setError($element, t('Manually entered paths should start with one of the following characters: / ? #'));
      return;
    }

    // Validate non-external URLs.
    if (!UrlHelper::isExternal($uri)) {
      $url = Url::fromUri($uri);
      if (!\Drupal::service('path.validator')
        ->getUrlIfValid($url
        ->toString())) {
        $form_state
          ->setError($element, t('The URL @url is invalid.', [
          '@url' => $element['#value'],
        ]));
      }
    }
  }
}