1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kevinrob\GuzzleCache\Strategy; |
4
|
|
|
|
5
|
|
|
use Kevinrob\GuzzleCache\CacheEntry; |
6
|
|
|
use Kevinrob\GuzzleCache\Storage\CacheStorageInterface; |
7
|
|
|
use Psr\Http\Message\RequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* This strategy represent a "greedy" HTTP client. |
12
|
|
|
* |
13
|
|
|
* It can be used to cache responses in spite of any cache related response headers, |
14
|
|
|
* but it SHOULDN'T be used unless absolutely necessary, e.g. when accessing |
15
|
|
|
* badly designed APIs without Cache control. |
16
|
|
|
* |
17
|
|
|
* Obviously, this follows no RFC :(. |
18
|
|
|
*/ |
19
|
|
|
class GreedyCacheStrategy extends PrivateCacheStrategy |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var int |
23
|
|
|
*/ |
24
|
|
|
protected $ttl; |
25
|
|
|
|
26
|
|
|
public function __construct(CacheStorageInterface $cache = null, $ttl) |
27
|
|
|
{ |
28
|
|
|
$this->ttl = $ttl; |
29
|
|
|
|
30
|
|
|
parent::__construct($cache); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
protected function getCacheKey(RequestInterface $request) |
34
|
|
|
{ |
35
|
|
|
return sha1( |
36
|
|
|
'greedy'.$request->getMethod().$request->getUri() |
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function cache(RequestInterface $request, ResponseInterface $response) |
41
|
|
|
{ |
42
|
|
|
$response = $response->withAddedHeader( |
43
|
|
|
'Warning', |
44
|
|
|
'This response is cached although the response headers indicate not to do it!' |
45
|
|
|
); |
46
|
|
|
|
47
|
|
|
if ($cacheObject = $this->getCacheObject($request, $response)) { |
48
|
|
|
return $this->storage->save( |
49
|
|
|
$this->getCacheKey($request), |
50
|
|
|
$cacheObject |
51
|
|
|
); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return false; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
protected function getCacheObject(RequestInterface $request, ResponseInterface $response) |
58
|
|
|
{ |
59
|
|
|
if (!array_key_exists($response->getStatusCode(), $this->statusAccepted)) { |
60
|
|
|
// Don't cache it |
61
|
|
|
return null; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return new CacheEntry($request, $response, new \DateTime(sprintf('+%d seconds', $this->ttl))); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function fetch(RequestInterface $request) |
68
|
|
|
{ |
69
|
|
|
return $this->storage->fetch($this->getCacheKey($request)); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|