You are here

public static function WebformAttachmentUrl::validateAttachmentUrl in Webform 6.x

Same name and namespace in other branches
  1. 8.5 modules/webform_attachment/src/Plugin/WebformElement/WebformAttachmentUrl.php \Drupal\webform_attachment\Plugin\WebformElement\WebformAttachmentUrl::validateAttachmentUrl()

Form API callback. Validate url/path.

See also

\Drupal\Core\Render\Element\Url::validateUrl

File

modules/webform_attachment/src/Plugin/WebformElement/WebformAttachmentUrl.php, line 64

Class

WebformAttachmentUrl
Provides a 'webform_attachment_url' element.

Namespace

Drupal\webform_attachment\Plugin\WebformElement

Code

public static function validateAttachmentUrl(&$element, FormStateInterface &$form_state) {
  $value = trim($element['#value']);
  $form_state
    ->setValueForElement($element, $value);

  // Prepend scheme and host to root relative path.
  if (strpos($value, '/') === 0) {
    $value = \Drupal::request()
      ->getSchemeAndHttpHost() . $value;
  }

  // Skip validating [webform_submission] tokens which can't be replaced.
  if (strpos($value, '[webform_submission:') !== FALSE) {
    return;
  }

  // Validate URL formatting.
  if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
    $form_state
      ->setError($element, t('The URL %url is not valid.', [
      '%url' => $value,
    ]));
  }

  // Validate URL access.
  try {
    \Drupal::httpClient()
      ->head($value);
  } catch (ClientException $e) {
    $form_state
      ->setError($element, t('The URL <a href=":url">@url</a> is not available.', [
      ':url' => $value,
      '@url' => $value,
    ]));
  }
}