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