InstagramEmbedFetcher.php in Media entity Instagram 8.2
File
src/InstagramEmbedFetcher.php
View source
<?php
namespace Drupal\media_entity_instagram;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Utility\Error;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class InstagramEmbedFetcher implements InstagramEmbedFetcherInterface {
const INSTAGRAM_URL = 'http://instagr.am/p/';
const INSTAGRAM_API = 'http://api.instagram.com/oembed';
protected $cache;
protected $httpClient;
protected $loggerFactory;
public function __construct(Client $client, LoggerChannelFactoryInterface $loggerFactory, CacheBackendInterface $cache = NULL) {
$this->httpClient = $client;
$this->loggerFactory = $loggerFactory;
$this->cache = $cache;
}
public function fetchInstagramEmbed($shortcode, $hidecaption = FALSE, $maxWidth = NULL) {
$options = [
'url' => self::INSTAGRAM_URL . $shortcode . '/',
'hidecaption' => (int) $hidecaption,
'omitscript' => 1,
];
if ($maxWidth) {
$options['maxwidth'] = $maxWidth;
}
$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 (isset($data)) {
if ($this->cache) {
$this->cache
->set($cacheKey, $data, time() + 86400 * 90);
}
return $data;
}
return FALSE;
}
}