1 | <?php |
||
18 | class Cache extends AbstractMiddleware |
||
19 | { |
||
20 | use CacheTrait; |
||
21 | use LoggerTrait; |
||
22 | |||
23 | const DEFAULT_TTL = 60; |
||
24 | const PREFIX = 'cache#'; |
||
25 | |||
26 | /** |
||
27 | * {@inheritdoc} |
||
28 | */ |
||
29 | 3 | public function processRequest(Request $request, Route $route) |
|
30 | { |
||
31 | 3 | if (!$route->hasOption('cache') || !$request->isMethod('GET')) { |
|
32 | // return null; |
||
33 | } |
||
34 | |||
35 | 3 | $cacheKey = $this->generateCacheKey($request); |
|
36 | |||
37 | 3 | $ttl = $route->getOption('cache'); |
|
38 | 3 | $cache = $this->getCache(); |
|
39 | 3 | if ($cache->hasItem($cacheKey)) { |
|
40 | 1 | return $this->handleCached($cache, $cacheKey, $ttl); |
|
41 | } |
||
42 | |||
43 | // enable cache for current request. Store response later in given key |
||
44 | 2 | $request->attributes->set('_cacheKey', $cacheKey); |
|
45 | 2 | $request->attributes->set('_cacheTTL', $ttl); |
|
46 | |||
47 | 2 | return null; |
|
48 | } |
||
49 | |||
50 | /** |
||
51 | * {@inheritdoc} |
||
52 | */ |
||
53 | 2 | public function processResponse(Request $request, Response $response) |
|
54 | { |
||
55 | 2 | if (!$response->isOk()) { |
|
56 | 1 | return; |
|
57 | } |
||
58 | |||
59 | 2 | $cacheKey = $request->attributes->get('_cacheKey'); |
|
60 | 2 | $ttl = $request->attributes->get('_cacheTTL'); |
|
61 | 2 | if (empty($cacheKey)) { |
|
62 | return; |
||
63 | } |
||
64 | |||
65 | 2 | $cache = $this->getCache(); |
|
66 | |||
67 | 2 | $this->info(sprintf('miss: save into cache: %s', $cacheKey), [ |
|
68 | 2 | 'application' => 'cache', |
|
69 | 2 | 'type' => 'miss', |
|
70 | 2 | 'cacheKey' => $cacheKey, |
|
71 | 2 | 'ttl' => $ttl, |
|
72 | ]); |
||
73 | |||
74 | 2 | $item = $cache->getItem($cacheKey); |
|
75 | 2 | $item->set($response); |
|
76 | 1 | $item->expiresAfter($ttl); |
|
77 | 1 | $cache->save($item); |
|
78 | |||
79 | 1 | $response->headers->set('X-Cache', 'miss'); |
|
80 | 1 | $response->setMaxAge($ttl); |
|
81 | 1 | $response->setExpires(new DateTime(sprintf('+%d seconds', $ttl))); |
|
82 | 1 | } |
|
83 | |||
84 | /** |
||
85 | * @param AdapterInterface $cache |
||
86 | * @param string $cacheKey |
||
87 | * @param int $ttl |
||
88 | * @return Response |
||
89 | */ |
||
90 | 1 | private function handleCached(AdapterInterface $cache, string $cacheKey, int $ttl) : Response |
|
108 | |||
109 | /** |
||
110 | * @param Request $request |
||
111 | * @return string |
||
112 | */ |
||
113 | 3 | private function generateCacheKey(Request $request) : string |
|
117 | } |
||
118 |
This check looks
TODO
comments that have been left in the code.``TODO``s show that something is left unfinished and should be attended to.