You are here

public function ResourceFetcher::fetchResource in Drupal 8

Same name and namespace in other branches
  1. 9 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

https://oembed.com/#section2

File

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

Class

ResourceFetcher
Fetches and caches oEmbed resources.

Namespace

Drupal\media\OEmbed

Code

public function fetchResource($url) {
  $cache_id = "media:oembed_resource:{$url}";
  $cached = $this
    ->cacheGet($cache_id);
  if ($cached) {
    return $this
      ->createResource($cached->data, $url);
  }
  try {
    $response = $this->httpClient
      ->get($url);
  } catch (RequestException $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);
  }
  elseif (strstr($format, 'text/javascript') || strstr($format, 'application/json')) {
    $data = Json::decode($content);
  }
  else {
    throw new ResourceException('The fetched resource did not have a valid Content-Type header.', $url);
  }
  $this
    ->cacheSet($cache_id, $data);
  return $this
    ->createResource($data, $url);
}