Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ $repositories = $client->api('user')->repositories('ornicar');

From `$client` object, you can access to all GitHub.

## Cache usage

```php
<?php

// This file is generated by Composer
require_once 'vendor/autoload.php';

$client = new Github\Client(new CachedHttpClient(new FilesystemCache('/tmp/github-api-cache')));
```

Using cache, the client will get cached responses if resources haven't changed since last time,
**without** reaching the `X-Rate-Limit` [imposed by github](http://developer.github.com/v3/#rate-limiting).


## Documentation

See the `doc` directory for more detailed documentation.
Expand Down
10 changes: 3 additions & 7 deletions lib/Github/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,11 @@ class Client
/**
* Instantiate a new GitHub client
*
* @param null|ClientInterface $httpClient Buzz client
* @param null|HttpClientInterface $httpClient Github http client
*/
public function __construct(ClientInterface $httpClient = null)
public function __construct(HttpClientInterface $httpClient = null)
{
$httpClient = $httpClient ?: new Curl();
$httpClient->setTimeout($this->options['timeout']);
$httpClient->setVerifyPeer(false);

$this->httpClient = new HttpClient($this->options, $httpClient);
$this->httpClient = $httpClient ?: new HttpClient($this->options);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is better :)

}

/**
Expand Down
32 changes: 32 additions & 0 deletions lib/Github/HttpClient/Cache/CacheInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Github\HttpClient\Cache;

use Github\HttpClient\Message\Response;

/**
* Caches github api responses
*
* @author Florian Klein <florian.klein@free.fr>
*/
interface CacheInterface
{
/**
* @param string the id of the cached resource
* @return int the modified since timestamp
**/
public function getModifiedSince($id);

/**
* @param string the id of the cached resource
* @return Response The cached response object
**/
public function get($id);

/**
* @param string the id of the cached resource
* @param Response the response to cache
**/
public function set($id, Response $response);
}

48 changes: 48 additions & 0 deletions lib/Github/HttpClient/Cache/FilesystemCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace Github\HttpClient\Cache;

use Github\HttpClient\Message\Response;

class FilesystemCache implements CacheInterface
{
protected $path;

public function __construct($path = null)
{
$this->path = $path ?: sys_get_temp_dir().DIRECTORY_SEPARATOR.'php-github-api-cache';
}

public function get($id)
{
if (false !== $content = @file_get_contents($this->getPath($id))) {
return unserialize($content);
}

throw new \InvalidArgumentException(sprintf('File "%s" not found', $this->getPath($id)));
}

public function set($id, Response $response)
{
if (!is_dir($this->path)) {
mkdir($this->path, 0777, true);
}

if (false === $bytes = @file_put_contents($this->getPath($id), serialize($response))) {
throw new \InvalidArgumentException(sprintf('Cannot put content in file "%s"', $this->getPath($id)));
}
}

public function getModifiedSince($id)
{
if (file_exists($this->getPath($id))) {
return filemtime($this->getPath($id));
}
}

protected function getPath($id)
{
return sprintf('%s%s%s', rtrim($this->path, DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR, md5($id));
}
}

65 changes: 65 additions & 0 deletions lib/Github/HttpClient/CachedHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace Github\HttpClient;

use Buzz\Client\ClientInterface;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Listener\ListenerInterface;

use Github\Exception\ErrorException;
use Github\Exception\RuntimeException;
use Github\HttpClient\Listener\ErrorListener;
use Github\HttpClient\Message\Request;
use Github\HttpClient\Message\Response;
use Github\HttpClient\Cache\CacheInterface;
use Github\HttpClient\Cache\FilesystemCache;

/**
* Performs requests on GitHub API using If-Modified-Since headers.
* Returns a cached version if not modified
* Avoids increasing the X-Rate-Limit, which is cool
*
* @author Florian Klein <florian.klein@free.fr>
*/
class CachedHttpClient extends HttpClient
{
protected $cache;

public function __construct(array $options = array(), ClientInterface $client = null, CacheInterface $cache = null)
{
parent::__construct($options, $client);

$this->cache = $cache ?: new FilesystemCache;
}

public function request($path, array $parameters = array(), $httpMethod = 'GET', array $headers = array(), Response $response = null)
{
$response = parent::request($path, $parameters, $httpMethod, $headers, $response);

$key = trim($this->options['base_url'].$path, '/');
if ($response->isNotModified()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Such method not exist in Response class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just added it :) oops

return $this->cache->get($key);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will fail if cache was not found and response was not modified (i.e. some GC cleaned temp folder)

}

$this->cache->set($key, $response);

return $response;
}

/**
* Create requests with If-Modified-Since headers
* @param string $httpMethod
* @param string $url
*
* @return Request
*/
protected function createRequest($httpMethod, $url)
{
$request = parent::createRequest($httpMethod, $url);
$modifiedSince = date('r', $this->cache->getModifiedSince($url));
$request->addHeader(sprintf('If-Modified-Since: %s', $modifiedSince));

return $request;
}
}
15 changes: 11 additions & 4 deletions lib/Github/HttpClient/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Github\HttpClient\Listener\ErrorListener;
use Github\HttpClient\Message\Request;
use Github\HttpClient\Message\Response;
use Buzz\Client\Curl;

/**
* Performs requests on GitHub API. API documentation should be self-explanatory.
Expand Down Expand Up @@ -48,8 +49,12 @@ class HttpClient implements HttpClientInterface
* @param array $options
* @param ClientInterface $client
*/
public function __construct(array $options, ClientInterface $client)
public function __construct(array $options = array(), ClientInterface $client = null)
{
$client = $client ?: new Curl();
$client->setTimeout($this->options['timeout']);
$client->setVerifyPeer(false);

$this->options = array_merge($this->options, $options);
$this->client = $client;

Expand Down Expand Up @@ -139,7 +144,7 @@ public function put($path, array $parameters = array(), array $headers = array()
/**
* {@inheritDoc}
*/
public function request($path, array $parameters = array(), $httpMethod = 'GET', array $headers = array())
public function request($path, array $parameters = array(), $httpMethod = 'GET', array $headers = array(), Response $response = null)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason of this change ? I look at code and can't find in what case this Response is overwritten. It seems like it's always null in acutal code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It permits more flexibility. We had no way access to the response in precedent code. It's used in tests currently :-s
Another possibility would be to use a ResponseFactory. (The Buzz one for example).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that similar method to createRequest() would be enough, and more clear than this additional param =)

{
$path = trim($this->options['base_url'].$path, '/');

Expand All @@ -154,7 +159,9 @@ public function request($path, array $parameters = array(), $httpMethod = 'GET',
}
}

$response = new Response();
if (null === $response) {
$response = new Response;
}

try {
$this->client->send($request, $response);
Expand Down Expand Up @@ -198,7 +205,7 @@ public function getLastResponse()
*
* @return Request
*/
private function createRequest($httpMethod, $url)
protected function createRequest($httpMethod, $url)
{
$request = new Request($httpMethod);
$request->setHeaders($this->headers);
Expand Down
3 changes: 2 additions & 1 deletion lib/Github/HttpClient/HttpClientInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Github\HttpClient;

use Github\Exception\InvalidArgumentException;
use Github\HttpClient\Message\Response;

/**
* Performs requests on GitHub API. API documentation should be self-explanatory.
Expand Down Expand Up @@ -77,7 +78,7 @@ public function delete($path, array $parameters = array(), array $headers = arra
*
* @return array Data
*/
public function request($path, array $parameters = array(), $httpMethod = 'GET', array $headers = array());
public function request($path, array $parameters = array(), $httpMethod = 'GET', array $headers = array(), Response $response = null);

/**
* Change an option value.
Expand Down
10 changes: 10 additions & 0 deletions lib/Github/HttpClient/Message/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,14 @@ public function getApiLimit()
throw new ApiLimitExceedException($this->options['api_limit']);
}
}

/**
* Is not modified
*
* @return Boolean
*/
public function isNotModified()
{
return 304 === $this->getStatusCode();
}
}
2 changes: 1 addition & 1 deletion test/Github/Tests/Api/AbstractApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ protected function getAbstractApiObject($client)
*/
protected function getClientMock()
{
return new \Github\Client($this->getHttpClientMock());
return new \Github\Client($this->getHttpMock());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion test/Github/Tests/Api/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ protected function getApiMock()

$mock = $this->getMock('Github\HttpClient\HttpClient', array(), array(array(), $httpClient));

$client = new \Github\Client($httpClient);
$client = new \Github\Client($mock);
$client->setHttpClient($mock);

return $this->getMockBuilder($this->getApiClass())
Expand Down
44 changes: 44 additions & 0 deletions test/Github/Tests/HttpClient/Cache/FilesystemCacheTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Github\Tests\HttpClient\Cache;

use Github\HttpClient\Message\Response;
use Github\HttpClient\Cache\FilesystemCache;

class FilesystemCacheTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function shouldStoreAResponseForAGivenKey()
{
$cache = new FilesystemCache('/tmp/github-api-test');

$cache->set('test', new Response);

$this->assertNotNull($cache->get('test'));
}

/**
* @test
*/
public function shouldGetATimestampForExistingFile()
{
$cache = new FilesystemCache('/tmp/github-api-test');

$cache->set('test', new Response);

$this->assertInternalType('int', $cache->getModifiedSince('test'));
}

/**
* @test
*/
public function shouldNotGetATimestampForInexistingFile()
{
$cache = new FilesystemCache('/tmp/github-api-test');

$this->assertNull($cache->getModifiedSince('test2'));
}
}

Loading