-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCacheMiddleware.php
404 lines (338 loc) · 11 KB
/
CacheMiddleware.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
<?php
namespace Charcoal\Cache\Middleware;
// From PSR-6
use Psr\Cache\CacheItemPoolInterface;
// From PSR-7
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
// From 'charcoal-cache'
use Charcoal\Cache\CacheConfig;
/**
* Charcoal HTTP Cache Middleware
*
* Saves or loads the HTTP response from a {@link https://www.php-fig.org/psr/psr-6/ PSR-6 cache pool}.
* It uses {@see https://packagist.org/packages/tedivm/stash Stash} as the caching library, so you
* have plenty of driver choices.
*
* The middleware saves the response body and headers in a cache pool and returns.
*
* The middleware will attempt to load a cached HTTP response based on the HTTP request's route.
* The route must matched the middleware's conditons for allowed methods, paths, and query parameters,
* as well as the response's status code.
*
* If the cache is a hit, the response is immediately returned; meaning that any subsequent middleware
* in the stack will be ignored.
*
* Ideally, this middleware should be the first the execute on the stack, in most cases
* (with Slim, this means adding it last).
*/
class CacheMiddleware
{
/**
* PSR-6 cache item pool.
*
* @var CacheItemPoolInterface
*/
private $cachePool;
/**
* Cache response if the request matches one of the HTTP methods.
*
* @var string[]
*/
private $methods;
/**
* Cache response if the request matches one of the HTTP status codes.
*
* @var integer[]
*/
private $statusCodes;
/**
* Time-to-live in seconds.
*
* @var integer
*/
private $cacheTtl;
/**
* Cache response if the request matches one of the URI path patterns.
*
* One or more regex patterns (excluding the outer delimiters).
*
* @var null|string|array
*/
private $includedPath;
/**
* Cache response if the request does not match any of the URI path patterns.
*
* One or more regex patterns (excluding the outer delimiters).
*
* @var null|string|array
*/
private $excludedPath;
/**
* Cache response if the request matches one of the query parameters.
*
* One or more query string fields.
*
* @var array|string|null
*/
private $includedQuery;
/**
* Cache response if the request does not match any of the query parameters.
*
* One or more query string fields.
*
* @var array|string|null
*/
private $excludedQuery;
/**
* Ignore query parameters from the request.
*
* @var array|string|null
*/
private $ignoredQuery;
/**
* @param array $data Constructor dependencies and options.
*/
public function __construct(array $data)
{
$data = array_replace($this->defaults(), $data);
$this->cachePool = $data['cache'];
$this->cacheTtl = $data['ttl'];
$this->methods = (array)$data['methods'];
$this->statusCodes = (array)$data['status_codes'];
$this->includedPath = $data['included_path'];
$this->excludedPath = $data['excluded_path'];
$this->includedQuery = $data['included_query'];
$this->excludedQuery = $data['excluded_query'];
$this->ignoredQuery = $data['ignored_query'];
}
/**
* Default middleware options.
*
* @return array
*/
public function defaults()
{
return [
'ttl' => CacheConfig::DAY_IN_SECONDS,
'included_path' => '*',
'excluded_path' => [ '^/admin\b' ],
'methods' => [ 'GET' ],
'status_codes' => [ 200 ],
'included_query' => null,
'excluded_query' => null,
'ignored_query' => null
];
}
/**
* Load a route content from path's cache.
*
* This method is as dumb / simple as possible.
* It does not rely on any sort of settings / configuration.
* Simply: if the cache for the route exists, it will be used to display the page.
* The `$next` callback will not be called, therefore stopping the middleware stack.
*
* To generate the cache used in this middleware,
* @see \Charcoal\App\Middleware\CacheGeneratorMiddleware.
*
* @param RequestInterface $request The PSR-7 HTTP request.
* @param ResponseInterface $response The PSR-7 HTTP response.
* @param callable $next The next middleware callable in the stack.
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
// Bail early
if (!$this->isRequestMethodValid($request)) {
return $next($request, $response);
}
$cacheKey = $this->cacheKeyFromRequest($request);
$cacheItem = $this->cachePool->getItem($cacheKey);
if ($cacheItem->isHit()) {
$cached = $cacheItem->get();
$response->getBody()->write($cached['body']);
foreach ($cached['headers'] as $name => $header) {
$response = $response->withHeader($name, $header);
}
return $response;
}
$uri = $request->getUri();
$path = $uri->getPath();
$query = [];
parse_str($uri->getQuery(), $query);
$response = $next($request, $response);
if (!$this->isResponseStatusValid($response)) {
return $response;
}
if (!$this->isPathIncluded($path)) {
return $response;
}
if ($this->isPathExcluded($path)) {
return $response;
}
if (!$this->isQueryIncluded($query)) {
$queryArr = $this->parseIgnoredParams($query);
if (!empty($queryArr)) {
return $response;
}
}
if ($this->isQueryExcluded($query)) {
return $response;
}
// Nothing has excluded the cache so far: add it to the pool.
$cacheItem->expiresAfter($this->cacheTtl);
$cacheItem->set([
'body' => (string)$response->getBody(),
'headers' => (array)$response->getHeaders(),
]);
$this->cachePool->save($cacheItem);
return $response;
}
/**
* Generate the cache key from the HTTP request.
*
* @param RequestInterface $request The PSR-7 HTTP request.
* @return string
*/
private function cacheKeyFromRequest(RequestInterface $request)
{
$uri = $request->getUri();
$queryStr = $uri->getQuery();
if (!empty($queryStr)) {
$queryArr = [];
parse_str($queryStr, $queryArr);
$queryArr = $this->parseIgnoredParams($queryArr);
$queryStr = http_build_query($queryArr);
$uri = $uri->withQuery($queryStr);
}
$cacheKey = 'request/' . $request->getMethod() . '/' . md5((string)$uri);
return $cacheKey;
}
/**
* Determine if the HTTP request method matches the accepted choices.
*
* @param RequestInterface $request The PSR-7 HTTP request.
* @return boolean
*/
private function isRequestMethodValid(RequestInterface $request)
{
return in_array($request->getMethod(), $this->methods);
}
/**
* Determine if the HTTP response status matches the accepted choices.
*
* @param ResponseInterface $response The PSR-7 HTTP response.
* @return boolean
*/
private function isResponseStatusValid(ResponseInterface $response)
{
return in_array($response->getStatusCode(), $this->statusCodes);
}
/**
* Determine if the request should be cached based on the URI path.
*
* @param string $path The request path (route) to verify.
* @return boolean
*/
private function isPathIncluded($path)
{
if ($this->includedPath === '*') {
return true;
}
if (empty($this->includedPath) && !is_numeric($this->includedPath)) {
return false;
}
foreach ((array)$this->includedPath as $included) {
if (preg_match('@' . $included . '@', $path)) {
return true;
}
}
return false;
}
/**
* Determine if the request should NOT be cached based on the URI path.
*
* @param string $path The request path (route) to verify.
* @return boolean
*/
private function isPathExcluded($path)
{
if ($this->excludedPath === '*') {
return true;
}
if (empty($this->excludedPath) && !is_numeric($this->excludedPath)) {
return false;
}
foreach ((array)$this->excludedPath as $excluded) {
if (preg_match('@' . $excluded . '@', $path)) {
return true;
}
}
return false;
}
/**
* Determine if the request should be cached based on the URI query.
*
* @param array $queryParams The query parameters to verify.
* @return boolean
*/
private function isQueryIncluded(array $queryParams)
{
if (empty($queryParams)) {
return true;
}
if ($this->includedQuery === '*') {
return true;
}
if (empty($this->includedQuery) && !is_numeric($this->includedQuery)) {
return false;
}
$includedParams = array_intersect_key($queryParams, array_flip((array)$this->includedQuery));
return (count($includedParams) > 0);
}
/**
* Determine if the request should NOT be cached based on the URI query.
*
* @param array $queryParams The query parameters to verify.
* @return boolean
*/
private function isQueryExcluded(array $queryParams)
{
if (empty($queryParams)) {
return false;
}
if ($this->excludedQuery === '*') {
return true;
}
if (empty($this->excludedQuery) && !is_numeric($this->excludedQuery)) {
return false;
}
$excludedParams = array_intersect_key($queryParams, array_flip((array)$this->excludedQuery));
return (count($excludedParams) > 0);
}
/**
* Returns the query parameters that are NOT ignored.
*
* @param array $queryParams The query parameters to filter.
* @return array
*/
private function parseIgnoredParams(array $queryParams)
{
if (empty($queryParams)) {
return $queryParams;
}
if ($this->ignoredQuery === '*') {
if ($this->includedQuery === '*') {
return $queryParams;
}
if (empty($this->includedQuery) && !is_numeric($this->includedQuery)) {
return [];
}
return array_intersect_key($queryParams, array_flip((array)$this->includedQuery));
}
if (empty($this->ignoredQuery) && !is_numeric($this->ignoredQuery)) {
return $queryParams;
}
return array_diff_key($queryParams, array_flip((array)$this->ignoredQuery));
}
}