function public static function Bootstrap::request

8.x-3.x Bootstrap.php public static Bootstrap::request($url, array $options = [], &$exception = NULL)

Retrieves a response from a URL, using cached response if available.

Parameters

string $url: The URL to retrieve.

array $options: The options to pass to the HTTP client.

\Exception|null $exception: The exception thrown if there was an error, passed by reference.

Return value

\Drupal\bootstrap\SerializedResponse A Response object.

Class

Bootstrap
The primary class for the Drupal Bootstrap base theme.

Namespace

Drupal\bootstrap

Source src/Bootstrap.php (line 392)

public static function request($url, array $options = [], &$exception = NULL) {
  $options += [
    'method' => 'GET',
    'headers' => [
      'User-Agent' => 'Drupal Bootstrap ' . static::PROJECT_BRANCH . ' (' . static::PROJECT_PAGE . ')',
    ],
  ];

  // Determine if a custom TTL value was set.
  $ttl = isset($options['ttl']) ? $options['ttl'] : NULL;
  unset($options['ttl']);

  $cache = \Drupal::keyValueExpirable('theme:' . static::getTheme()->getName() . ':http');

  // The URL cannot be part of the prefix as the "name" field of
  // "key_value_expire" has a max length of 128.
  $hash = Crypt::generateBase64HashIdentifier(['url' => $url] + $options, 'request');
  $response = $cache->get($hash);

  if (!isset($response)) {
    /** @var \GuzzleHttp\Client $client */
    $client = \Drupal::service('http_client_factory')->fromOptions($options);
    $request = new Request($options['method'], $url, $options['headers']);

    try {
      $response = SerializedResponse::createFromGuzzleResponse($client->send($request, $options), $request);
    }
    catch (GuzzleException $e) {
      $exception = $e;
      $response = SerializedResponse::createFromException($e, $request);
    }
    catch (\Exception $e) {
      $exception = $e;
      $response = SerializedResponse::createFromException($e, $request);
    }

    // Only cache if a maximum age has been detected.
    $maxAge = (int) isset($ttl) ? $ttl : $response->getMaxAge();
    if ($response->getStatusCode() == 200 && $maxAge > 0) {
      // Due to key_value_expire setting the "expire" field to "INT(11)", it
      // is technically limited to a 32bit max value (Y2K38 bug).
      // @todo Remove this once this is no longer an issue.
      // @see https://www.drupal.org/project/drupal/issues/65474
      // @see https://www.drupal.org/project/drupal/issues/1003692
      $requestTime = \Drupal::time()->getRequestTime();
      if (($requestTime + $maxAge) > 2147483647) {
        $maxAge = 2147483647 - $requestTime;
      }
      try {
        $cache->setWithExpire($hash, $response, $maxAge);
      }
      catch (\Exception $e) {
        // Intentionally do nothing, tried to cache response... it failed.
      }
    }
  }

  return $response;
}