function ResourceFetcher::fetchResource

Same name in other branches
  1. 8.9.x core/modules/media/src/OEmbed/ResourceFetcher.php \Drupal\media\OEmbed\ResourceFetcher::fetchResource()
  2. 10 core/modules/media/src/OEmbed/ResourceFetcher.php \Drupal\media\OEmbed\ResourceFetcher::fetchResource()
  3. 11.x core/modules/media/src/OEmbed/ResourceFetcher.php \Drupal\media\OEmbed\ResourceFetcher::fetchResource()

Overrides ResourceFetcherInterface::fetchResource

File

core/modules/media/src/OEmbed/ResourceFetcher.php, line 60

Class

ResourceFetcher
Fetches and caches oEmbed resources.

Namespace

Drupal\media\OEmbed

Code

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);
    }
    [
        $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);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.