Further modules included.
[yaffs-website] / web / modules / contrib / libraries / src / ExternalLibrary / Definition / GuzzleDefinitionDiscovery.php
1 <?php
2
3 namespace Drupal\libraries\ExternalLibrary\Definition;
4
5 use Drupal\Component\Serialization\SerializationInterface;
6 use Drupal\libraries\ExternalLibrary\Exception\LibraryDefinitionNotFoundException;
7 use GuzzleHttp\ClientInterface;
8 use GuzzleHttp\Exception\GuzzleException;
9
10 /**
11  * Provides a definition discovery that fetches remote definitions using Guzzle.
12  *
13  * By default JSON files are assumed to be in JSON format.
14  *
15  * @todo Cache responses statically by ID to avoid multiple HTTP requests when
16  *   calling hasDefinition() and getDefinition() sequentially.
17  */
18 class GuzzleDefinitionDiscovery extends FileDefinitionDiscoveryBase implements DefinitionDiscoveryInterface {
19
20   /**
21    * The HTTP client.
22    *
23    * @var \GuzzleHttp\ClientInterface
24    */
25   protected $httpClient;
26
27   /**
28    * Constructs a Guzzle-based definition discvoery.
29    *
30    * @param \GuzzleHttp\ClientInterface $http_client
31    *   The 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.
36    */
37   public function __construct(ClientInterface $http_client, SerializationInterface $serializer, $base_url) {
38     parent::__construct($serializer, $base_url);
39     $this->httpClient = $http_client;
40   }
41
42   /**
43    * {@inheritdoc}
44    */
45   public function hasDefinition($id) {
46     try {
47       $response = $this->httpClient->request('GET', $this->getFileUri($id));
48       return $response->getStatusCode() === 200;
49     }
50     catch (GuzzleException $exception) {
51       return FALSE;
52     }
53   }
54
55   /**
56    * {@inheritdoc}
57    */
58   protected function getSerializedDefinition($id) {
59     try {
60       $response = $this->httpClient->request('GET', $this->getFileUri($id));
61       return (string) $response->getBody();
62     }
63     catch (GuzzleException $exception) {
64       throw new LibraryDefinitionNotFoundException($id, '', 0, $exception);
65     }
66     catch (\RuntimeException $exception) {
67       throw new LibraryDefinitionNotFoundException($id, '', 0, $exception);
68     }
69   }
70
71 }