You are here

public function FacebookFetcher::getOembedData in Media entity facebook 8.2

Same name and namespace in other branches
  1. 8 src/FacebookFetcher.php \Drupal\media_entity_facebook\FacebookFetcher::getOembedData()
  2. 3.x src/FacebookFetcher.php \Drupal\media_entity_facebook\FacebookFetcher::getOembedData()

Fetch and return response from Facebook's oEmbed API endpoint.

Parameters

string $resource_url: The URL to pass to Facebook's oembed API.

File

src/FacebookFetcher.php, line 65

Class

FacebookFetcher
Class FacebookFetcher.

Namespace

Drupal\media_entity_facebook

Code

public function getOembedData($resource_url) {

  // Keep an in-memory cache of the response data for each URL, since this
  // data may be requested multiple times on the same request.
  static $memory_cache;
  if (!isset($memory_cache)) {
    $memory_cache = [];
  }
  if (!isset($memory_cache[$resource_url])) {

    // If there was an error interacting with the Facebook API, like a network
    // timeout due to Facebook being down, we don't want to clog up the Drupal
    // site's resources by making lots of API requests that may all timeout.
    // To do this, we mark when a request exception occurred and back out of
    // subsequent requests if so.
    if ($this->apiErrorEncountered) {
      $this->loggerChannel
        ->error('Aborting Facebook API request due to previously encountered error.');
      return FALSE;
    }
    $endpoint = $this
      ->getApiEndpointUrl($resource_url) . '?url=' . $resource_url;
    try {
      $options = [
        'timeout' => 5,
        'headers' => [
          'Accept-Language' => $this->languageManager
            ->getCurrentLanguage()
            ->getId(),
        ],
      ];
      $response = $this->httpClient
        ->request('GET', $endpoint, $options);
      $decoded = json_decode((string) $response
        ->getBody(), TRUE);
      $memory_cache[$resource_url] = $decoded;
    } catch (TransferException $e) {
      $this->loggerChannel
        ->error('Error retrieving oEmbed data for a Facebook media entity: @error', [
        '@error' => $e
          ->getMessage(),
      ]);
      $this->apiErrorEncountered = TRUE;
      return FALSE;
    }
  }
  return $memory_cache[$resource_url];
}