3 namespace Drupal\libraries\ExternalLibrary\Definition;
5 use Drupal\Component\Serialization\SerializationInterface;
6 use Drupal\libraries\ExternalLibrary\Exception\LibraryDefinitionNotFoundException;
7 use GuzzleHttp\ClientInterface;
8 use GuzzleHttp\Exception\GuzzleException;
11 * Provides a definition discovery that fetches remote definitions using Guzzle.
13 * By default JSON files are assumed to be in JSON format.
15 * @todo Cache responses statically by ID to avoid multiple HTTP requests when
16 * calling hasDefinition() and getDefinition() sequentially.
18 class GuzzleDefinitionDiscovery extends FileDefinitionDiscoveryBase implements DefinitionDiscoveryInterface {
23 * @var \GuzzleHttp\ClientInterface
25 protected $httpClient;
28 * Constructs a Guzzle-based definition discvoery.
30 * @param \GuzzleHttp\ClientInterface $http_client
32 * @param \Drupal\Component\Serialization\SerializationInterface $serializer
33 * The serializer for the library definition files.
34 * @param string $base_url
35 * The base URL for the library files.
37 public function __construct(ClientInterface $http_client, SerializationInterface $serializer, $base_url) {
38 parent::__construct($serializer, $base_url);
39 $this->httpClient = $http_client;
45 public function hasDefinition($id) {
47 $response = $this->httpClient->request('GET', $this->getFileUri($id));
48 return $response->getStatusCode() === 200;
50 catch (GuzzleException $exception) {
58 protected function getSerializedDefinition($id) {
60 $response = $this->httpClient->request('GET', $this->getFileUri($id));
61 return (string) $response->getBody();
63 catch (GuzzleException $exception) {
64 throw new LibraryDefinitionNotFoundException($id, '', 0, $exception);
66 catch (\RuntimeException $exception) {
67 throw new LibraryDefinitionNotFoundException($id, '', 0, $exception);