You are here

protected function LinkToFileConstraint::getEffectiveUrl in File Link 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Validation/Constraint/LinkToFileConstraint.php \Drupal\file_link\Plugin\Validation\Constraint\LinkToFileConstraint::getEffectiveUrl()

Get effective URL by following redirects, if any.

Parameters

string $url: Original URL.

Return value

string Effective URL.

1 call to LinkToFileConstraint::getEffectiveUrl()
LinkToFileConstraint::validate in src/Plugin/Validation/Constraint/LinkToFileConstraint.php
Checks if the passed value is valid.

File

src/Plugin/Validation/Constraint/LinkToFileConstraint.php, line 177

Class

LinkToFileConstraint
Validation constraint for file_link, checking that URI points to a file.

Namespace

Drupal\file_link\Plugin\Validation\Constraint

Code

protected function getEffectiveUrl($url) {

  // Skip performing HTTP requests, useful when running bulk imports.
  if (Settings::get('file_link.disable_http_requests', FALSE) || !Settings::get('file_link.follow_redirect_on_validate', TRUE)) {
    return $url;
  }

  // Setup HTTP client to follow redirect and perform an HEAD request.
  $options = [
    'exceptions' => TRUE,
    'connect_timeout' => TRUE,
    'allow_redirects' => [
      'strict' => TRUE,
      'on_redirect' => function (Request $request, Response $response, Uri $uri) use (&$url) {
        $url = (string) $uri;
      },
    ],
  ];
  try {

    // Perform HEAD request to get actual URL, as in: after the redirect.
    \Drupal::httpClient()
      ->head($url, $options);
  } catch (RequestException $e) {

    // Don't fail validation if connection has timed out or URL was not found.
  }
  return $url;
}