1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Http\Client\Common\Plugin; |
4
|
|
|
|
5
|
|
|
use Http\Client\Common\Plugin; |
6
|
|
|
use Http\Message\StreamFactory; |
7
|
|
|
use Http\Promise\FulfilledPromise; |
8
|
|
|
use Psr\Cache\CacheItemInterface; |
9
|
|
|
use Psr\Cache\CacheItemPoolInterface; |
10
|
|
|
use Psr\Http\Message\RequestInterface; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Allow for caching a response. |
16
|
|
|
* |
17
|
|
|
* @author Tobias Nyholm <[email protected]> |
18
|
|
|
*/ |
19
|
|
|
final class CachePlugin implements Plugin |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var CacheItemPoolInterface |
23
|
|
|
*/ |
24
|
|
|
private $pool; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var StreamFactory |
28
|
|
|
*/ |
29
|
|
|
private $streamFactory; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var array |
33
|
|
|
*/ |
34
|
|
|
private $config; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param CacheItemPoolInterface $pool |
38
|
|
|
* @param StreamFactory $streamFactory |
39
|
|
|
* @param array $config { |
40
|
|
|
* |
41
|
|
|
* @var bool $respect_cache_headers Whether to look at the cache directives or ignore them |
42
|
|
|
* @var int $default_ttl (seconds) If we do not respect cache headers or can't calculate a good ttl, use this |
43
|
|
|
* value |
44
|
|
|
* @var string $hash_algo The hashing algorithm to use when generating cache keys |
45
|
|
|
* @var int $cache_lifetime (seconds) To support serving a previous stale response when the server answers 304 |
46
|
|
|
* we have to store the cache for a longer time that the server originally says it is valid for. |
47
|
|
|
* We store a cache item for $cache_lifetime + max age of the response. |
48
|
|
|
* } |
49
|
|
|
*/ |
50
|
10 |
|
public function __construct(CacheItemPoolInterface $pool, StreamFactory $streamFactory, array $config = []) |
51
|
|
|
{ |
52
|
10 |
|
$this->pool = $pool; |
53
|
10 |
|
$this->streamFactory = $streamFactory; |
54
|
|
|
|
55
|
10 |
|
$optionsResolver = new OptionsResolver(); |
56
|
10 |
|
$this->configureOptions($optionsResolver); |
57
|
10 |
|
$this->config = $optionsResolver->resolve($config); |
58
|
10 |
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* {@inheritdoc} |
62
|
|
|
*/ |
63
|
8 |
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
64
|
1 |
|
{ |
65
|
8 |
|
$method = strtoupper($request->getMethod()); |
66
|
|
|
// if the request not is cachable, move to $next |
67
|
8 |
|
if ($method !== 'GET' && $method !== 'HEAD') { |
68
|
1 |
|
return $next($request); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
// If we can cache the request |
72
|
7 |
|
$key = $this->createCacheKey($request); |
73
|
7 |
|
$cacheItem = $this->pool->getItem($key); |
74
|
|
|
|
75
|
7 |
|
if ($cacheItem->isHit()) { |
76
|
3 |
|
$data = $cacheItem->get(); |
77
|
|
|
// The isset() is to be removed in 2.0. |
78
|
3 |
|
if (isset($data['expiresAt']) && time() < $data['expiresAt']) { |
79
|
|
|
// This item is still valid according to previous cache headers |
80
|
1 |
|
return new FulfilledPromise($this->createResponseFromCacheItem($cacheItem)); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
// Add headers to ask the server if this cache is still valid |
84
|
2 |
|
if ($modifiedSinceValue = $this->getModifiedSinceHeaderValue($cacheItem)) { |
85
|
2 |
|
$request = $request->withHeader('If-Modified-Since', $modifiedSinceValue); |
86
|
2 |
|
} |
87
|
|
|
|
88
|
2 |
|
if ($etag = $this->getETag($cacheItem)) { |
89
|
2 |
|
$request = $request->withHeader('If-None-Match', $etag); |
90
|
2 |
|
} |
91
|
2 |
|
} |
92
|
|
|
|
93
|
6 |
|
return $next($request)->then(function (ResponseInterface $response) use ($cacheItem) { |
94
|
6 |
|
if (304 === $response->getStatusCode()) { |
95
|
2 |
|
if (!$cacheItem->isHit()) { |
96
|
|
|
/* |
97
|
|
|
* We do not have the item in cache. This plugin did not add If-Modified-Since |
98
|
|
|
* or If-None-Match headers. Return the response from server. |
99
|
|
|
*/ |
100
|
1 |
|
return $response; |
101
|
|
|
} |
102
|
|
|
|
103
|
|
|
// The cached response we have is still valid |
104
|
1 |
|
$data = $cacheItem->get(); |
105
|
1 |
|
$maxAge = $this->getMaxAge($response); |
106
|
1 |
|
$data['expiresAt'] = time() + $maxAge; |
107
|
1 |
|
$cacheItem->set($data)->expiresAfter($this->config['cache_lifetime'] + $maxAge); |
108
|
1 |
|
$this->pool->save($cacheItem); |
109
|
|
|
|
110
|
1 |
|
return $this->createResponseFromCacheItem($cacheItem); |
111
|
|
|
} |
112
|
|
|
|
113
|
4 |
|
if ($this->isCacheable($response)) { |
114
|
3 |
|
$bodyStream = $response->getBody(); |
115
|
3 |
|
$body = $bodyStream->__toString(); |
116
|
3 |
|
if ($bodyStream->isSeekable()) { |
117
|
3 |
|
$bodyStream->rewind(); |
118
|
3 |
|
} else { |
119
|
|
|
$response = $response->withBody($this->streamFactory->createStream($body)); |
120
|
|
|
} |
121
|
|
|
|
122
|
3 |
|
$maxAge = $this->getMaxAge($response); |
123
|
3 |
|
$currentTime = time(); |
124
|
|
|
$cacheItem |
125
|
3 |
|
->expiresAfter($this->config['cache_lifetime'] + $maxAge) |
126
|
3 |
|
->set([ |
127
|
3 |
|
'response' => $response, |
128
|
3 |
|
'body' => $body, |
129
|
3 |
|
'expiresAt' => $currentTime + $maxAge, |
130
|
3 |
|
'createdAt' => $currentTime, |
131
|
3 |
|
'etag' => $response->getHeader('ETag'), |
132
|
3 |
|
]); |
133
|
3 |
|
$this->pool->save($cacheItem); |
134
|
3 |
|
} |
135
|
|
|
|
136
|
4 |
|
return $response; |
137
|
6 |
|
}); |
138
|
|
|
} |
139
|
|
|
|
140
|
|
|
/** |
141
|
|
|
* Verify that we can cache this response. |
142
|
|
|
* |
143
|
|
|
* @param ResponseInterface $response |
144
|
|
|
* |
145
|
|
|
* @return bool |
146
|
|
|
*/ |
147
|
4 |
|
protected function isCacheable(ResponseInterface $response) |
148
|
|
|
{ |
149
|
4 |
|
if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) { |
150
|
1 |
|
return false; |
151
|
|
|
} |
152
|
3 |
|
if (!$this->config['respect_cache_headers']) { |
153
|
|
|
return true; |
154
|
|
|
} |
155
|
3 |
|
if ($this->getCacheControlDirective($response, 'no-store') || $this->getCacheControlDirective($response, 'private')) { |
156
|
|
|
return false; |
157
|
|
|
} |
158
|
|
|
|
159
|
3 |
|
return true; |
160
|
|
|
} |
161
|
|
|
|
162
|
|
|
/** |
163
|
|
|
* Get the value of a parameter in the cache control header. |
164
|
|
|
* |
165
|
|
|
* @param ResponseInterface $response |
166
|
|
|
* @param string $name The field of Cache-Control to fetch |
167
|
|
|
* |
168
|
|
|
* @return bool|string The value of the directive, true if directive without value, false if directive not present |
169
|
|
|
*/ |
170
|
4 |
|
private function getCacheControlDirective(ResponseInterface $response, $name) |
171
|
|
|
{ |
172
|
4 |
|
$headers = $response->getHeader('Cache-Control'); |
173
|
4 |
|
foreach ($headers as $header) { |
174
|
1 |
|
if (preg_match(sprintf('|%s=?([0-9]+)?|i', $name), $header, $matches)) { |
175
|
|
|
|
176
|
|
|
// return the value for $name if it exists |
177
|
1 |
|
if (isset($matches[1])) { |
178
|
1 |
|
return $matches[1]; |
179
|
|
|
} |
180
|
|
|
|
181
|
|
|
return true; |
182
|
|
|
} |
183
|
4 |
|
} |
184
|
|
|
|
185
|
4 |
|
return false; |
186
|
|
|
} |
187
|
|
|
|
188
|
|
|
/** |
189
|
|
|
* @param RequestInterface $request |
190
|
|
|
* |
191
|
|
|
* @return string |
192
|
|
|
*/ |
193
|
7 |
|
private function createCacheKey(RequestInterface $request) |
194
|
|
|
{ |
195
|
7 |
|
return hash($this->config['hash_algo'], $request->getMethod().' '.$request->getUri()); |
196
|
|
|
} |
197
|
|
|
|
198
|
|
|
/** |
199
|
|
|
* Get a ttl in seconds. It could return null if we do not respect cache headers and got no defaultTtl. |
200
|
|
|
* |
201
|
|
|
* @param ResponseInterface $response |
202
|
|
|
* |
203
|
|
|
* @return int|null |
204
|
|
|
*/ |
205
|
4 |
|
private function getMaxAge(ResponseInterface $response) |
206
|
|
|
{ |
207
|
4 |
|
if (!$this->config['respect_cache_headers']) { |
208
|
|
|
return $this->config['default_ttl']; |
209
|
|
|
} |
210
|
|
|
|
211
|
|
|
// check for max age in the Cache-Control header |
212
|
4 |
|
$maxAge = $this->getCacheControlDirective($response, 'max-age'); |
213
|
4 |
|
if (!is_bool($maxAge)) { |
214
|
1 |
|
$ageHeaders = $response->getHeader('Age'); |
215
|
1 |
|
foreach ($ageHeaders as $age) { |
216
|
1 |
|
return $maxAge - ((int) $age); |
217
|
|
|
} |
218
|
|
|
|
219
|
|
|
return (int) $maxAge; |
220
|
|
|
} |
221
|
|
|
|
222
|
|
|
// check for ttl in the Expires header |
223
|
3 |
|
$headers = $response->getHeader('Expires'); |
224
|
3 |
|
foreach ($headers as $header) { |
225
|
|
|
return (new \DateTime($header))->getTimestamp() - (new \DateTime())->getTimestamp(); |
226
|
3 |
|
} |
227
|
|
|
|
228
|
3 |
|
return $this->config['default_ttl']; |
229
|
|
|
} |
230
|
|
|
|
231
|
|
|
/** |
232
|
|
|
* Configure an options resolver. |
233
|
|
|
* |
234
|
|
|
* @param OptionsResolver $resolver |
235
|
|
|
*/ |
236
|
10 |
|
private function configureOptions(OptionsResolver $resolver) |
237
|
|
|
{ |
238
|
10 |
|
$resolver->setDefaults([ |
239
|
10 |
|
'cache_lifetime' => 86400 * 30, // 30 days |
240
|
10 |
|
'default_ttl' => null, |
241
|
10 |
|
'respect_cache_headers' => true, |
242
|
10 |
|
'hash_algo' => 'sha1', |
243
|
10 |
|
]); |
244
|
|
|
|
245
|
10 |
|
$resolver->setAllowedTypes('cache_lifetime', 'int'); |
246
|
10 |
|
$resolver->setAllowedTypes('default_ttl', ['int', 'null']); |
247
|
10 |
|
$resolver->setAllowedTypes('respect_cache_headers', 'bool'); |
248
|
10 |
|
$resolver->setAllowedValues('hash_algo', hash_algos()); |
249
|
10 |
|
} |
250
|
|
|
|
251
|
|
|
/** |
252
|
|
|
* @param CacheItemInterface $cacheItem |
253
|
|
|
* |
254
|
|
|
* @return ResponseInterface |
255
|
|
|
*/ |
256
|
2 |
|
private function createResponseFromCacheItem(CacheItemInterface $cacheItem) |
257
|
|
|
{ |
258
|
2 |
|
$data = $cacheItem->get(); |
259
|
|
|
|
260
|
|
|
/** @var ResponseInterface $response */ |
261
|
2 |
|
$response = $data['response']; |
262
|
2 |
|
$response = $response->withBody($this->streamFactory->createStream($data['body'])); |
263
|
|
|
|
264
|
2 |
|
return $response; |
265
|
|
|
} |
266
|
|
|
|
267
|
|
|
/** |
268
|
|
|
* Get the value of the "If-Modified-Since" header. |
269
|
|
|
* |
270
|
|
|
* @param CacheItemInterface $cacheItem |
271
|
|
|
* |
272
|
|
|
* @return string|null |
273
|
|
|
*/ |
274
|
2 |
|
private function getModifiedSinceHeaderValue(CacheItemInterface $cacheItem) |
275
|
|
|
{ |
276
|
2 |
|
$data = $cacheItem->get(); |
277
|
|
|
// The isset() is to be removed in 2.0. |
278
|
2 |
|
if (!isset($data['createdAt'])) { |
279
|
|
|
return; |
280
|
|
|
} |
281
|
|
|
|
282
|
2 |
|
$modified = new \DateTime('@'.$data['createdAt']); |
283
|
2 |
|
$modified->setTimezone(new \DateTimeZone('GMT')); |
284
|
|
|
|
285
|
2 |
|
return sprintf('%s GMT', $modified->format('l, d-M-y H:i:s')); |
286
|
|
|
} |
287
|
|
|
|
288
|
|
|
/** |
289
|
|
|
* Get the ETag from the cached response. |
290
|
|
|
* |
291
|
|
|
* @param CacheItemInterface $cacheItem |
292
|
|
|
* |
293
|
|
|
* @return string|null |
294
|
|
|
*/ |
295
|
2 |
|
private function getETag(CacheItemInterface $cacheItem) |
296
|
|
|
{ |
297
|
2 |
|
$data = $cacheItem->get(); |
298
|
|
|
// The isset() is to be removed in 2.0. |
299
|
2 |
|
if (!isset($data['etag'])) { |
300
|
|
|
return; |
301
|
|
|
} |
302
|
|
|
|
303
|
2 |
|
if (!is_array($data['etag'])) { |
304
|
|
|
return $data['etag']; |
305
|
|
|
} |
306
|
|
|
|
307
|
2 |
|
foreach ($data['etag'] as $etag) { |
308
|
2 |
|
if (!empty($etag)) { |
309
|
2 |
|
return $etag; |
310
|
|
|
} |
311
|
|
|
} |
312
|
|
|
} |
313
|
|
|
} |
314
|
|
|
|