3 namespace Drupal\media\OEmbed;
5 use Drupal\Component\Datetime\TimeInterface;
6 use Drupal\Component\Serialization\Json;
7 use Drupal\Core\Cache\CacheBackendInterface;
8 use Drupal\Core\Cache\UseCacheBackendTrait;
9 use Drupal\Core\Config\ConfigFactoryInterface;
10 use GuzzleHttp\ClientInterface;
11 use GuzzleHttp\Exception\RequestException;
14 * Retrieves and caches information about oEmbed providers.
16 class ProviderRepository implements ProviderRepositoryInterface {
18 use UseCacheBackendTrait;
21 * How long the provider data should be cached, in seconds.
30 * @var \GuzzleHttp\Client
32 protected $httpClient;
35 * URL of a JSON document which contains a database of oEmbed providers.
39 protected $providersUrl;
44 * @var \Drupal\Component\Datetime\TimeInterface
49 * Constructs a ProviderRepository instance.
51 * @param \GuzzleHttp\ClientInterface $http_client
53 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
54 * The config factory service.
55 * @param \Drupal\Component\Datetime\TimeInterface $time
57 * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
58 * (optional) The cache backend.
60 * (optional) How long the cache data should be kept. Defaults to a week.
62 public function __construct(ClientInterface $http_client, ConfigFactoryInterface $config_factory, TimeInterface $time, CacheBackendInterface $cache_backend = NULL, $max_age = 604800) {
63 $this->httpClient = $http_client;
64 $this->providersUrl = $config_factory->get('media.settings')->get('oembed_providers_url');
66 $this->cacheBackend = $cache_backend;
67 $this->maxAge = (int) $max_age;
73 public function getAll() {
74 $cache_id = 'media:oembed_providers';
76 $cached = $this->cacheGet($cache_id);
82 $response = $this->httpClient->request('GET', $this->providersUrl);
84 catch (RequestException $e) {
85 throw new ProviderException("Could not retrieve the oEmbed provider database from $this->providersUrl", NULL, $e);
88 $providers = Json::decode((string) $response->getBody());
90 if (!is_array($providers) || empty($providers)) {
91 throw new ProviderException('Remote oEmbed providers database returned invalid or empty list.');
94 $keyed_providers = [];
95 foreach ($providers as $provider) {
97 $name = (string) $provider['provider_name'];
98 $keyed_providers[$name] = new Provider($provider['provider_name'], $provider['provider_url'], $provider['endpoints']);
100 catch (ProviderException $e) {
101 // Just skip all the invalid providers.
102 // @todo Log the exception message to help with debugging.
106 $this->cacheSet($cache_id, $keyed_providers, $this->time->getCurrentTime() + $this->maxAge);
107 return $keyed_providers;
113 public function get($provider_name) {
114 $providers = $this->getAll();
116 if (!isset($providers[$provider_name])) {
117 throw new \InvalidArgumentException("Unknown provider '$provider_name'");
119 return $providers[$provider_name];