|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Github\HttpClient; |
| 4 | + |
| 5 | +use Buzz\Client\ClientInterface; |
| 6 | +use Buzz\Message\MessageInterface; |
| 7 | +use Buzz\Message\RequestInterface; |
| 8 | +use Buzz\Listener\ListenerInterface; |
| 9 | + |
| 10 | +use Github\Exception\ErrorException; |
| 11 | +use Github\Exception\RuntimeException; |
| 12 | +use Github\HttpClient\Listener\ErrorListener; |
| 13 | +use Github\HttpClient\Message\Request; |
| 14 | +use Github\HttpClient\Message\Response; |
| 15 | +use Github\HttpClient\Cache\CacheInterface; |
| 16 | +use Github\HttpClient\Cache\FilesystemCache; |
| 17 | + |
| 18 | +/** |
| 19 | + * Performs requests on GitHub API using If-Modified-Since headers. |
| 20 | + * Returns a cached version if not modified |
| 21 | + * Avoids increasing the X-Rate-Limit, which is cool |
| 22 | + * |
| 23 | + * @author Florian Klein <florian.klein@free.fr> |
| 24 | + */ |
| 25 | +class CachedHttpClient extends HttpClient |
| 26 | +{ |
| 27 | + protected $cache; |
| 28 | + |
| 29 | + public function __construct(array $options = array(), ClientInterface $client = null, CacheInterface $cache = null) |
| 30 | + { |
| 31 | + parent::__construct($options, $client); |
| 32 | + |
| 33 | + $this->cache = $cache ?: new FilesystemCache; |
| 34 | + } |
| 35 | + |
| 36 | + public function request($path, array $parameters = array(), $httpMethod = 'GET', array $headers = array(), Response $response = null) |
| 37 | + { |
| 38 | + $response = parent::request($path, $parameters, $httpMethod, $headers, $response); |
| 39 | + |
| 40 | + $key = trim($this->options['base_url'].$path, '/'); |
| 41 | + if ($response->isNotModified()) { |
| 42 | + return $this->cache->get($key); |
| 43 | + } |
| 44 | + |
| 45 | + $this->cache->set($key, $response); |
| 46 | + |
| 47 | + return $response; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Create requests with If-Modified-Since headers |
| 52 | + * @param string $httpMethod |
| 53 | + * @param string $url |
| 54 | + * |
| 55 | + * @return Request |
| 56 | + */ |
| 57 | + protected function createRequest($httpMethod, $url) |
| 58 | + { |
| 59 | + $request = parent::createRequest($httpMethod, $url); |
| 60 | + $modifiedSince = date('r', $this->cache->getModifiedSince($url)); |
| 61 | + $request->addHeader(sprintf('If-Modified-Since: %s', $modifiedSince)); |
| 62 | + |
| 63 | + return $request; |
| 64 | + } |
| 65 | +} |
0 commit comments