You are here

class Client in Flickr API Integration 8

Class Client.

@package Drupal\flickr_api\Service

Hierarchy

Expanded class hierarchy of Client

1 string reference to 'Client'
flickr_api.services.yml in ./flickr_api.services.yml
flickr_api.services.yml
1 service uses Client
flickr_api.client in ./flickr_api.services.yml
Drupal\flickr_api\Service\Client

File

src/Service/Client.php, line 18

Namespace

Drupal\flickr_api\Service
View source
class Client {
  use StringTranslationTrait;

  /**
   * Config.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * Cache backend.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  private $cacheBackend;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Api uri.
   *
   * @var string
   */
  private $apiUri;

  /**
   * Host uri.
   *
   * @var string
   */
  private $hostUri;

  /**
   * API Key.
   *
   * @var string
   */
  private $apiKey;

  /**
   * API Secret.
   *
   * @var string
   */
  private $apiSecret;

  /**
   * Max Age.
   *
   * @var string
   */
  private $apiCacheMaximumAge;

  /**
   * Guzzle Client.
   *
   * @var \GuzzleHttp\Client
   */
  private $guzzleClient;

  /**
   * Client constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactory $config
   *   Config.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cacheBackend
   *   Cache backend.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $stringTranslation
   *   String translation.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(ConfigFactory $config, CacheBackendInterface $cacheBackend, TranslationInterface $stringTranslation, MessengerInterface $messenger) {
    $this->config = $config
      ->get('flickr_api.settings');
    $this->cacheBackend = $cacheBackend;
    $this->stringTranslation = $stringTranslation;
    $this->messenger = $messenger;
    $this->apiUri = $this->config
      ->get('api_uri');
    $this->hostUri = $this->config
      ->get('host_uri');
    $this->apiKey = $this->config
      ->get('api_key');
    $this->apiSecret = $this->config
      ->get('api_secret');
    $this->apiCacheMaximumAge = $this->config
      ->get('api_cache_maximum_age');
    $this->guzzleClient = new GuzzleClient([
      'base_uri' => $this->apiUri,
    ]);
  }

  /**
   * Flickr request.
   *
   * @param string $method
   *   Method to call.
   * @param array $args
   *   Args to request.
   * @param bool $cacheable
   *   Is it cachable.
   *
   * @return bool|array
   *   Either an array or false.
   */
  public function request($method, array $args, $cacheable = TRUE) {

    // Build the arg_hash.
    $args = $this
      ->buildArgs($args, $method);
    $argHash = $this
      ->buildArgHash($args);

    // $response = &drupal_static(__FUNCTION__);
    // // Can be replaced with the `__METHOD__`.
    $cid = 'flickr_api:' . md5($argHash);

    // Check cache.
    if ($cache = $this->cacheBackend
      ->get($cid)) {
      $response = $cache->data;

      // Return result from cache if found.
      return $response;
    }
    else {

      // If we've got a secret, sign the arguments.
      if ($secret = $this->apiSecret) {
        $args['api_sig'] = md5($secret . $argHash);
      }

      // TODO Implement try catch.
      $response = $this
        ->doRequest('', $args);
      if ($response) {

        // Cache the response if we got one.
        if ($this->apiCacheMaximumAge != 0 && $cacheable == TRUE) {
          $this->cacheBackend
            ->set($cid, $response, time() + $this->apiCacheMaximumAge);
        }

        // Return result from source if found.
        return $response;
      }
    }

    // Tough luck, no results mate.
    return FALSE;
  }

  /**
   * Build default args.
   *
   * @param array $args
   *   Args to request.
   * @param string $method
   *   Method to call.
   * @param string $format
   *   Format to request.
   *
   * @return array
   *   Return the args array.
   */
  private function buildArgs(array $args, $method, $format = 'json') {

    // Add in additional parameters then sort them for signing.
    $args['api_key'] = $this->apiKey;
    $args['method'] = $method;
    $args['format'] = $format;
    $args['nojsoncallback'] = 1;
    ksort($args);
    return $args;
  }

  /**
   * Build Hash from Args array.
   *
   * @param array $args
   *   Args to request.
   *
   * @return string
   *   Return string.
   */
  private function buildArgHash(array $args) {

    // Build an argument hash API signing (we'll also use it for the cache id).
    $argHash = '';
    foreach ($args as $k => $v) {
      $argHash .= $k . $v;
    }
    return $argHash;
  }

  /**
   * Guzzle request for Flickr.
   *
   * @param string $url
   *   Url.
   * @param array $parameters
   *   Parameters.
   * @param string $requestMethod
   *   Request method.
   *
   * @return bool|array
   *   False or array.
   */
  private function doRequest($url, array $parameters = [], $requestMethod = 'GET') {
    if (!$this->apiKey || !$this->apiSecret) {
      $msg = $this
        ->t('Flickr API credentials are not set. It can be set on the <a href=":config_page">configuration page</a>.', [
        ':config_page' => Url::fromRoute('flickr_api.settings'),
      ]);
      $this->messenger
        ->addError($msg);
      return FALSE;
    }
    $response = $this->guzzleClient
      ->request($requestMethod, $url, [
      'query' => $parameters,
    ]);

    // TODO Error checking can be improved.
    if ($response
      ->getStatusCode() == !200) {
      return FALSE;
    }

    // TODO Add some checking.
    $body = $response
      ->getBody();

    // TODO Add some checking.
    return json_decode((string) $body, TRUE);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Client::$apiCacheMaximumAge private property Max Age.
Client::$apiKey private property API Key.
Client::$apiSecret private property API Secret.
Client::$apiUri private property Api uri.
Client::$cacheBackend private property Cache backend.
Client::$config protected property Config.
Client::$guzzleClient private property Guzzle Client.
Client::$hostUri private property Host uri.
Client::$messenger protected property The messenger.
Client::buildArgHash private function Build Hash from Args array.
Client::buildArgs private function Build default args.
Client::doRequest private function Guzzle request for Flickr.
Client::request public function Flickr request.
Client::__construct public function Client constructor.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.