You are here

public function LinkCheckerService::check in Link checker 8

Check the link.

Parameters

\Drupal\linkchecker\LinkCheckerLinkInterface $link: The link to check.

Return value

\GuzzleHttp\Promise\PromiseInterface Promise of link checking request.

File

src/LinkCheckerService.php, line 141

Class

LinkCheckerService
Class LinkCheckerService.

Namespace

Drupal\linkchecker

Code

public function check(LinkCheckerLinkInterface $link) {
  $userAgent = $this->linkcheckerSetting
    ->get('check.useragent');
  $headers = [];
  $headers['User-Agent'] = $userAgent;
  $uri = @parse_url($link
    ->getUrl());

  // URL contains a fragment.
  if (in_array($link
    ->getRequestMethod(), [
    'HEAD',
    'GET',
  ]) && !empty($uri['fragment'])) {

    // We need the full content and not only the HEAD.
    $link
      ->setRequestMethod('GET');

    // Request text content only (like Firefox/Chrome).
    $headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
  }
  elseif ($link
    ->getRequestMethod() == 'GET') {

    // Range: Only request the first 1024 bytes from remote server. This is
    // required to prevent timeouts on URLs that are large downloads.
    $headers['Range'] = 'bytes=0-1024';
  }

  // Add in the headers.
  $options = [
    'headers' => $headers,
    'max_redirects' => 0,
    'http_errors' => FALSE,
    'allow_redirects' => FALSE,
    'synchronous' => FALSE,
  ];
  return $this->httpClient
    ->requestAsync($link
    ->getRequestMethod(), $link
    ->getUrl(), $options)
    ->then(function (ResponseInterface $response) use ($link, $uri) {
    if (!empty($uri['fragment'])) {
      $response = $response
        ->withHeader('Fragment', $uri['fragment']);
    }
    $this
      ->statusHandling($response, $link);
  }, function (RequestException $e) use ($link) {
    $this
      ->exceptionHandling($e, $link);
  });
}