Skip to content

Commit

Permalink
Refactoring client
Browse files Browse the repository at this point in the history
  • Loading branch information
wtfzdotnet committed Apr 10, 2014
1 parent 08971f6 commit a279902
Show file tree
Hide file tree
Showing 3 changed files with 171 additions and 97 deletions.
136 changes: 39 additions & 97 deletions lib/Tmdb/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,10 @@
*/
namespace Tmdb;

use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Http\Client as GuzzleClient;
use Guzzle\Http\ClientInterface;
use Guzzle\Log\MessageFormatter;
use Guzzle\Log\PsrLogAdapter;
use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Plugin\Cache\CachePlugin;
use Guzzle\Plugin\Cache\DefaultCacheStorage;
use Guzzle\Plugin\Log\LogPlugin;
use Tmdb\HttpClient\HttpClient;
use Tmdb\HttpClient\HttpClientInterface;
use Tmdb\ApiToken as Token;
use Tmdb\HttpClient\Plugin\AcceptJsonHeaderPlugin;
use Tmdb\HttpClient\Plugin\ApiTokenPlugin;
use Tmdb\HttpClient\Plugin\SessionTokenPlugin;

/**
* Client wrapper for TMDB
Expand Down Expand Up @@ -106,7 +93,7 @@ class Client
private $cachePath;

/**
* Stores whether the cache is enabled or not
* Stores wether the cache is enabled or not
*
* @var boolean
*/
Expand All @@ -118,95 +105,44 @@ class Client
* @param ClientInterface|null $httpClient
* @param ApiToken $token
* @param boolean $secure
* @param array $options
*/
public function __construct(ApiToken $token, ClientInterface $httpClient = null, $secure = false)
public function __construct(
ApiToken $token,
ClientInterface $httpClient = null,
$secure = false,
$options = array()
)
{
$this->setToken($token);
$this->setSecure($secure);
$this->constructHttpClient($httpClient);
$this->constructHttpClient(
$httpClient,
array_merge(
array(
'token' => $this->getToken(),
'secure' => $this->getSecure()
),
$options
)
);
}

/**
* Construct the http client
*
* @param ClientInterface $httpClient
* @throws RuntimeException
* @param ClientInterface $httpClient
* @param array $options
* @return void
*/
private function constructHttpClient(ClientInterface $httpClient = null)
{
$httpClient = $httpClient ?: new GuzzleClient($this->getBaseUrl());

if ($httpClient instanceof HasDispatcherInterface) {
$acceptJsonHeaderPlugin = new AcceptJsonHeaderPlugin();
$httpClient->addSubscriber($acceptJsonHeaderPlugin);

$backoffPlugin = BackoffPlugin::getExponentialBackoff(5);
$httpClient->addSubscriber($backoffPlugin);

if ($this->getToken() instanceof ApiToken) {
$apiTokenPlugin = new ApiTokenPlugin($this->getToken());
$httpClient->addSubscriber($apiTokenPlugin);
}

if ($this->cacheEnabled && !empty($this->cachePath)) {
if (!class_exists('Doctrine\Common\Cache\FilesystemCache')) {
//@codeCoverageIgnoreStart
throw new RuntimeException(
'Could not find the doctrine cache library,
have you added doctrine-cache to your composer.json?'
);
//@codeCoverageIgnoreEnd
}

$cachePlugin = new CachePlugin(array(
'storage' => new DefaultCacheStorage(
new DoctrineCacheAdapter(
new \Doctrine\Common\Cache\FilesystemCache($this->cachePath)
)
)
)
);

$httpClient->addSubscriber($cachePlugin);
}

if ($this->logEnabled && !empty($this->logPath)) {
if (empty($this->logger) && !class_exists('\Monolog\Logger')) {
//@codeCoverageIgnoreStart
throw new RuntimeException(
'Could not find any logger set and the monolog logger library was not found
to provide a default, you have to set a custom logger on the client or
have you forgot adding monolog to your composer.json?'
);
//@codeCoverageIgnoreEnd
} else {
$this->setLogger(new \Monolog\Logger('php-tmdb-api'));
$this->getLogger()->pushHandler(
new \Monolog\Handler\StreamHandler(
$this->logPath,
\Monolog\Logger::DEBUG
)
);
}

if ($this->logger instanceof \Psr\Log\LoggerInterface) {
$logPlugin = new LogPlugin(
new PsrLogAdapter($this->logger),
MessageFormatter::SHORT_FORMAT
);

$httpClient->addSubscriber($logPlugin);
}
}

if ($this->getSessionToken() instanceof SessionToken) {
$sessionTokenPlugin = new SessionTokenPlugin($this->getSessionToken());
$httpClient->addSubscriber($sessionTokenPlugin);
}
}

$this->httpClient = new HttpClient($this->getBaseUrl(), array(), $httpClient);
private function constructHttpClient(ClientInterface $httpClient = null, array $options)
{
$httpClient = $httpClient ?: new \Guzzle\Http\Client($this->getBaseUrl());
$this->httpClient = new HttpClient(
$this->getBaseUrl(),
$options,
$httpClient
);
}

/**
Expand Down Expand Up @@ -485,7 +421,9 @@ public function setSessionToken($sessionToken)
{
$this->sessionToken = $sessionToken;

$this->constructHttpClient();
if ($this->httpClient instanceof HttpClientInterface) {
$this->getHttpClient()->setSessionToken($sessionToken);
}

return $this;
}
Expand Down Expand Up @@ -523,8 +461,10 @@ public function setCaching($enabled = true, $path = null)
$path
;

// @todo doesn't cover a custom client, would require un-registering all known plugins
$this->constructHttpClient();
$this->getHttpClient()->setCaching(array(
'enabled' => $enabled,
'cache_path' => $path
));

return $this;
}
Expand Down Expand Up @@ -581,8 +521,10 @@ public function setLogging($enabled = true, $path = null)
$path
;

// @todo doesn't cover a custom client, would require un-registering all known plugins
$this->constructHttpClient();
$this->getHttpClient()->setLogging(array(
'enabled' => $enabled,
'log_path' => $path
));

return $this;
}
Expand Down
129 changes: 129 additions & 0 deletions lib/Tmdb/HttpClient/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Log\MessageFormatter;
use Guzzle\Log\PsrLogAdapter;
use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Plugin\Cache\CachePlugin;
use Guzzle\Plugin\Cache\DefaultCacheStorage;
use Guzzle\Plugin\Log\LogPlugin;
use Tmdb\ApiToken;
use Tmdb\HttpClient\Plugin\AcceptJsonHeaderPlugin;
use Tmdb\HttpClient\Plugin\ApiTokenPlugin;
use Tmdb\HttpClient\Plugin\SessionTokenPlugin;
use Tmdb\SessionToken;

/**
* Class HttpClient
Expand Down Expand Up @@ -54,6 +67,8 @@ public function __construct($baseUrl, array $options, ClientInterface $client)
$this->base_url = $baseUrl;
$this->options = $options;
$this->client = $client;

$this->registerGuzzleSubscribers($options);
}

/**
Expand Down Expand Up @@ -238,13 +253,127 @@ public function getLastResponse()
return $this->lastResponse;
}

/**
* Get the current base url
*
* @return null|string
*/
public function getBaseUrl()
{
return $this->getClient()->getBaseUrl();
}

/**
* Set the base url secure / insecure
*
* @param $url
* @return ClientInterface
*/
public function setBaseUrl($url)
{
return $this->getClient()->setBaseUrl($url);
}

/**
* Register the default subscribers for Guzzle
*
* @param array $options
*/
public function registerGuzzleSubscribers(array $options)
{
$acceptJsonHeaderPlugin = new AcceptJsonHeaderPlugin();
$this->addSubscriber($acceptJsonHeaderPlugin);

$backoffPlugin = BackoffPlugin::getExponentialBackoff(5);
$this->addSubscriber($backoffPlugin);

if (array_key_exists('token', $options) && $options['token'] instanceof ApiToken) {
$apiTokenPlugin = new ApiTokenPlugin($options['token']);
$this->addSubscriber($apiTokenPlugin);
}
}

/**
* Add an subscriber to enable caching.
*
* @param array $parameters
* @throws \Guzzle\Common\Exception\RuntimeException
*/
public function setCaching(array $parameters = array())
{
if (!class_exists('Doctrine\Common\Cache\FilesystemCache')) {
//@codeCoverageIgnoreStart
throw new RuntimeException(
'Could not find the doctrine cache library,
have you added doctrine-cache to your composer.json?'
);
//@codeCoverageIgnoreEnd
}

$cachePlugin = new CachePlugin(array(
'storage' => new DefaultCacheStorage(
new DoctrineCacheAdapter(
new \Doctrine\Common\Cache\FilesystemCache($parameters['cache_path'])
)
)
)
);

$this->addSubscriber($cachePlugin);
}

/**
* Add an subscriber to enable logging.
*
* @param array $parameters
* @throws \Guzzle\Common\Exception\RuntimeException
*/
public function setLogging(array $parameters = array())
{
if (!array_key_exists('logger', $parameters) && !class_exists('\Monolog\Logger')) {
//@codeCoverageIgnoreStart
throw new RuntimeException(
'Could not find any logger set and the monolog logger library was not found
to provide a default, you have to set a custom logger on the client or
have you forgot adding monolog to your composer.json?'
);
//@codeCoverageIgnoreEnd
} else {
$logger = new \Monolog\Logger('php-tmdb-api');
$logger->pushHandler(
new \Monolog\Handler\StreamHandler(
$parameters['log_path'],
\Monolog\Logger::DEBUG
)
);
}

if (array_key_exists('logger', $parameters)) {
$logger = $parameters['logger'];
}

$logPlugin = null;

if ($logger instanceof \Psr\Log\LoggerInterface) {
$logPlugin = new LogPlugin(
new PsrLogAdapter($logger),
MessageFormatter::SHORT_FORMAT
);
}

if (null !== $logPlugin) {
$this->addSubscriber($logPlugin);
}
}

/**
* Add an subscriber to append the session_token to the query parameters.
*
* @param SessionToken $sessionToken
*/
public function setSessionToken(SessionToken $sessionToken)
{
$sessionTokenPlugin = new SessionTokenPlugin($sessionToken);
$this->addSubscriber($sessionTokenPlugin);
}
}
3 changes: 3 additions & 0 deletions lib/Tmdb/HttpClient/HttpClientInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Tmdb\SessionToken;

/**
* Interface HttpClientInterface
Expand Down Expand Up @@ -102,4 +103,6 @@ public function request(RequestInterface $request);

public function getBaseUrl();
public function setBaseUrl($url);

public function setSessionToken(SessionToken $sessionToken);
}

0 comments on commit a279902

Please sign in to comment.