1 | <?php |
||
15 | class CachePlugin implements Plugin |
||
16 | { |
||
17 | /** |
||
18 | * @var CacheItemPoolInterface |
||
19 | */ |
||
20 | private $pool; |
||
21 | |||
22 | /** |
||
23 | * Default time to store object in cache. This value is used if CachePlugin::respectCacheHeaders is false or |
||
24 | * if cache headers are missing. |
||
25 | * |
||
26 | * @var int |
||
27 | */ |
||
28 | private $defaultTtl; |
||
29 | |||
30 | /** |
||
31 | * Look at the cache headers to know whether this response may be cached and to |
||
32 | * decide how it can be cached. |
||
33 | * |
||
34 | * @var bool Defaults to true |
||
35 | */ |
||
36 | private $respectCacheHeaders; |
||
37 | |||
38 | /** |
||
39 | * Available options are |
||
40 | * - respect_cache_headers: Whether to look at the cache directives or ignore them. |
||
41 | * |
||
42 | * @param CacheItemPoolInterface $pool |
||
43 | * @param array $options |
||
44 | */ |
||
45 | 6 | public function __construct(CacheItemPoolInterface $pool, array $options = []) |
|
51 | |||
52 | /** |
||
53 | * {@inheritdoc} |
||
54 | */ |
||
55 | 4 | public function handleRequest(RequestInterface $request, callable $next, callable $first) |
|
83 | |||
84 | /** |
||
85 | * Verify that we can cache this response. |
||
86 | * |
||
87 | * @param ResponseInterface $response |
||
88 | * |
||
89 | * @return bool |
||
90 | */ |
||
91 | 3 | protected function isCacheable(ResponseInterface $response) |
|
92 | { |
||
93 | 3 | if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) { |
|
94 | 1 | return false; |
|
95 | } |
||
96 | 2 | if (!$this->respectCacheHeaders) { |
|
97 | return true; |
||
98 | } |
||
99 | 2 | if ($this->getCacheControlDirective($response, 'no-store') || $this->getCacheControlDirective($response, 'private')) { |
|
100 | return false; |
||
101 | } |
||
102 | |||
103 | 2 | return true; |
|
104 | } |
||
105 | |||
106 | /** |
||
107 | * Get the value of a parameter in the cache control header. |
||
108 | * |
||
109 | * @param ResponseInterface $response |
||
110 | * @param string $name The field of Cache-Control to fetch |
||
111 | * |
||
112 | * @return bool|string The value of the directive, true if directive without value, false if directive not present. |
||
113 | */ |
||
114 | 2 | private function getCacheControlDirective(ResponseInterface $response, $name) |
|
131 | |||
132 | /** |
||
133 | * @param RequestInterface $request |
||
134 | * |
||
135 | * @return string |
||
136 | */ |
||
137 | 3 | private function createCacheKey(RequestInterface $request) |
|
141 | |||
142 | /** |
||
143 | * Get a ttl in seconds. It could return null if we do not respect cache headers and got no defaultTtl. |
||
144 | * |
||
145 | * @param ResponseInterface $response |
||
146 | * |
||
147 | * @return int|null |
||
148 | */ |
||
149 | 2 | private function getMaxAge(ResponseInterface $response) |
|
174 | } |
||
175 |