You are here

trait HttpClientTrait in Remote Stream Wrapper 8

Trait to help reuse HTTP client logic.

Hierarchy

2 files declare their use of HttpClientTrait
HttpMimeTypeGuesser.php in src/File/MimeType/HttpMimeTypeGuesser.php
HttpStreamWrapper.php in src/StreamWrapper/HttpStreamWrapper.php

File

src/HttpClientTrait.php, line 12

Namespace

Drupal\remote_stream_wrapper
View source
trait HttpClientTrait {

  /**
   * The HTTP client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * Sets the HTTP client.
   *
   * @param \GuzzleHttp\ClientInterface $httpClient
   *   An HTTP client.
   */
  public function setHttpClient(ClientInterface $httpClient) {
    $this->httpClient = $httpClient;
  }

  /**
   * Returns the HTTP client.
   *
   * @return \GuzzleHttp\ClientInterface
   */
  public function getHttpClient() {
    if (!isset($this->httpClient)) {
      $this->httpClient = \Drupal::httpClient();
    }
    return $this->httpClient;
  }

  /**
   * Perform a HEAD/GET request looking for a specific header.
   *
   * If the header was found in the HEAD request, then the HEAD response is
   * returned. Otherwise the GET request response is returned (without checking
   * if the header was found).
   *
   * @param string $uri
   * @param string $header
   *   Case-insensitive header field name.
   * @param array $options
   *
   * @return \Psr\Http\Message\ResponseInterface
   *   The HTTP response object.
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function requestTryHeadLookingForHeader($uri, $header, array $options = []) {
    try {
      $response = $this
        ->getHttpClient()
        ->request('HEAD', $uri, $options);
      if ($response
        ->hasHeader($header)) {
        return $response;
      }
    } catch (ClientException $exception) {

      // Do nothing, try a GET request instead.
    } catch (ServerException $exception) {

      // Do nothing, try a GET request instead.
    }
    return $this
      ->getHttpClient()
      ->request('GET', $uri, $options);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
HttpClientTrait::$httpClient protected property The HTTP client.
HttpClientTrait::getHttpClient public function Returns the HTTP client.
HttpClientTrait::requestTryHeadLookingForHeader public function Perform a HEAD/GET request looking for a specific header.
HttpClientTrait::setHttpClient public function Sets the HTTP client.