Client.php in Instagram API 8
File
src/Service/Client.php
View source
<?php
namespace Drupal\instagram_api\Service;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use GuzzleHttp\Client as GuzzleClient;
use Drupal\Core\Url;
use GuzzleHttp\Exception\GuzzleException;
class Client {
use StringTranslationTrait;
protected $config;
protected $loggerFactory;
protected $cacheBackend;
public function __construct(ConfigFactory $config, CacheBackendInterface $cacheBackend, TranslationInterface $stringTranslation, LoggerChannelFactoryInterface $loggerFactory) {
$this->config = $config
->get('instagram_api.settings');
$this->cacheBackend = $cacheBackend;
$this->stringTranslation = $stringTranslation;
$this->api_base_uri = $this->config
->get('api_base_uri');
$this->api_cache_maximum_age = $this->config
->get('api_cache_maximum_age');
$this->access_token = $this->config
->get('access_token');
$this->guzzleClient = new GuzzleClient([
'base_uri' => $this->api_base_uri,
]);
$this->loggerFactory = $loggerFactory;
}
public function request($method, array $args, $cacheable = TRUE) {
$args = $this
->buildArgs($args, $method);
$argHash = $this
->buildArgHash($args);
$cid = 'instagram_api:' . md5($argHash);
if ($cache = $this->cacheBackend
->get($cid)) {
$response = $cache->data;
return $response;
}
else {
$response = $this
->doRequest($method, $args);
if ($response) {
if ($this->api_cache_maximum_age != 0 && $cacheable == TRUE) {
$this->cacheBackend
->set($cid, $response, time() + $this->api_cache_maximum_age);
}
return $response;
}
}
return FALSE;
}
private function buildArgs(array $args, $method, $format = 'json') {
$args['access_token'] = $this->access_token;
ksort($args);
return $args;
}
private function buildArgHash(array $args) {
$argHash = '';
foreach ($args as $k => $v) {
$argHash .= $k . $v;
}
return $argHash;
}
private function doRequest($url, array $parameters = [], $requestMethod = 'GET') {
if ($this->access_token == "") {
$msg = $this
->t('Instagram API Access Token is not set. It can be set on the <a href=":config_page">configuration page</a>.', [
':config_page' => Url::fromRoute('instagram_api.settings'),
]);
drupal_set_message($msg, 'error');
return FALSE;
}
try {
$response = $this->guzzleClient
->request($requestMethod, $url, [
'query' => $parameters,
]);
if ($response
->getStatusCode() == 200) {
$contents = $response
->getBody()
->getContents();
$json = Json::decode($contents);
return $json['data'];
}
} catch (GuzzleException $e) {
$this->loggerFactory
->get('instagram_api')
->error("@message", [
'@message' => $e
->getMessage(),
]);
return FALSE;
}
}
}