You are here

public function FacebookFetcher::getOembedData in Media entity facebook 3.x

Same name and namespace in other branches
  1. 8.2 src/FacebookFetcher.php \Drupal\media_entity_facebook\FacebookFetcher::getOembedData()
  2. 8 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 88

Class

FacebookFetcher
Class FacebookFetcher.

Namespace

Drupal\media_entity_facebook

Code

public function getOembedData($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. This of course only matters if there are many
  // embeds on a single page request.
  if ($this->apiErrorEncountered) {
    $this->loggerChannel
      ->error('Aborting Facebook oembed API request due to a previously encountered error on the same request.');
    return FALSE;
  }
  $appId = $this->config
    ->get('facebook_app_id') ?: '';
  $appSecret = $this->config
    ->get('facebook_app_secret') ?: '';
  if (empty($appId) || empty($appSecret)) {
    $this->loggerChannel
      ->error('Cannot retrieve Facebook embed as the Facebook app ID and/or app secret are missing from configuration. Visit /admin/config/media/facebook-settings to provide these values.');
    return FALSE;
  }
  $endpoint = $this
    ->getApiEndpointUrl($resource_url) . '?url=' . $resource_url . '&access_token=' . $appId . '|' . $appSecret;
  $cid = 'media_entity_facebook:' . Crypt::hashBase64(serialize($endpoint));
  $cacheItem = $this->cache
    ->get($cid);
  if ($cacheItem) {
    $oembedResponse = $cacheItem->data;
  }
  else {
    $options = [
      'timeout' => 5,
      'headers' => [
        'Accept-Language' => $this->languageManager
          ->getCurrentLanguage()
          ->getId(),
      ],
    ];
    try {
      $response = $this->httpClient
        ->request('GET', $endpoint, $options);
    } catch (GuzzleException $e) {
      $this->loggerChannel
        ->error('Error retrieving oEmbed data for a Facebook media entity: @error', [
        '@error' => $e
          ->getMessage(),
      ]);
      $this->apiErrorEncountered = TRUE;
      return FALSE;
    }
    $oembedResponse = json_decode((string) $response
      ->getBody(), TRUE);

    // Cache the result for 10 minutes.
    $cacheTime = \Drupal::time()
      ->getRequestTime() + 600;
    $this->cache
      ->set($cid, $oembedResponse, $cacheTime);
  }
  return $oembedResponse;
}