You are here

public function InstagramEmbedFetcher::fetchInstagramEmbed in Media entity Instagram 8.2

Same name and namespace in other branches
  1. 8 src/InstagramEmbedFetcher.php \Drupal\media_entity_instagram\InstagramEmbedFetcher::fetchInstagramEmbed()

Retrieves a instagram post by its shortcode.

Parameters

int $shortcode: The instagram post shortcode.

bool $hidecaption: Indicates if the caption should be hidden in the html.

bool $maxWidth: Max width of the instagram widget.

Return value

array The instagram oEmbed information.

Overrides InstagramEmbedFetcherInterface::fetchInstagramEmbed

File

src/InstagramEmbedFetcher.php, line 65

Class

InstagramEmbedFetcher
Fetches instagram post via oembed.

Namespace

Drupal\media_entity_instagram

Code

public function fetchInstagramEmbed($shortcode, $hidecaption = FALSE, $maxWidth = NULL) {
  $options = [
    'url' => self::INSTAGRAM_URL . $shortcode . '/',
    'hidecaption' => (int) $hidecaption,
    'omitscript' => 1,
  ];
  if ($maxWidth) {
    $options['maxwidth'] = $maxWidth;
  }

  // Tweets don't change much, so pull it out of the cache (if we have one)
  // if this one has already been fetched.
  $cacheKey = md5(serialize($options));
  if ($this->cache && ($cached_instagram_post = $this->cache
    ->get($cacheKey))) {
    return $cached_instagram_post->data;
  }
  $queryParameter = UrlHelper::buildQuery($options);
  try {
    $response = $this->httpClient
      ->request('GET', self::INSTAGRAM_API . '?' . $queryParameter, [
      'timeout' => 5,
    ]);
    if ($response
      ->getStatusCode() === 200) {
      $data = Json::decode($response
        ->getBody()
        ->getContents());
    }
  } catch (RequestException $e) {
    $this->loggerFactory
      ->get('media_entity_instagram')
      ->error("Could not retrieve Instagram post {$shortcode}.", Error::decodeException($e));
  }

  // If we got data from Instagram oEmbed request, return data.
  if (isset($data)) {

    // If we have a cache, store the response for future use.
    if ($this->cache) {

      // Instagram posts don't change often, so the response should expire
      // from the cache on its own in 90 days.
      $this->cache
        ->set($cacheKey, $data, time() + 86400 * 90);
    }
    return $data;
  }
  return FALSE;
}