public function ResourceFetcher::fetchResource in Drupal 9
Same name and namespace in other branches
- 8 core/modules/media/src/OEmbed/ResourceFetcher.php \Drupal\media\OEmbed\ResourceFetcher::fetchResource()
Fetches an oEmbed resource.
Parameters
string $url: Endpoint-specific URL of the oEmbed resource.
Return value
\Drupal\media\OEmbed\Resource A resource object built from the oEmbed resource data.
Throws
\Drupal\media\OEmbed\ResourceException If the oEmbed endpoint is not reachable or the response returns an unexpected Content-Type header.
Overrides ResourceFetcherInterface::fetchResource
See also
File
- core/
modules/ media/ src/ OEmbed/ ResourceFetcher.php, line 60
Class
- ResourceFetcher
- Fetches and caches oEmbed resources.
Namespace
Drupal\media\OEmbedCode
public function fetchResource($url) {
$cache_id = "media:oembed_resource:{$url}";
$cached = $this->cacheBackend
->get($cache_id);
if ($cached) {
return $this
->createResource($cached->data, $url);
}
try {
$response = $this->httpClient
->request('GET', $url, [
RequestOptions::TIMEOUT => 5,
]);
} catch (TransferException $e) {
throw new ResourceException('Could not retrieve the oEmbed resource.', $url, [], $e);
}
list($format) = $response
->getHeader('Content-Type');
$content = (string) $response
->getBody();
if (strstr($format, 'text/xml') || strstr($format, 'application/xml')) {
$data = $this
->parseResourceXml($content, $url);
}
else {
$data = Json::decode($content);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ResourceException('Error decoding oEmbed resource: ' . json_last_error_msg(), $url);
}
}
if (empty($data) || !is_array($data)) {
throw new ResourceException('The oEmbed resource could not be decoded.', $url);
}
$this->cacheBackend
->set($cache_id, $data);
return $this
->createResource($data, $url);
}