1 | <?php |
||
17 | class CachePlugin implements Plugin |
||
18 | { |
||
19 | /** |
||
20 | * @var CacheItemPoolInterface |
||
21 | */ |
||
22 | private $pool; |
||
23 | |||
24 | /** |
||
25 | * @var StreamFactory |
||
26 | */ |
||
27 | private $streamFactory; |
||
28 | |||
29 | private $config = [ |
||
30 | 'default_ttl' => null, |
||
31 | 'respect_cache_headers' => true, |
||
32 | ]; |
||
33 | |||
34 | /** |
||
35 | * @param CacheItemPoolInterface $pool |
||
36 | * @param StreamFactory $streamFactory |
||
37 | * @param array $config |
||
38 | */ |
||
39 | public function __construct(CacheItemPoolInterface $pool, StreamFactory $streamFactory, array $config = []) |
||
46 | 6 | ||
47 | /** |
||
48 | * {@inheritdoc} |
||
49 | */ |
||
50 | public function handleRequest(RequestInterface $request, callable $next, callable $first) |
||
82 | |||
83 | /** |
||
84 | * Verify that we can cache this response. |
||
85 | * |
||
86 | * @param ResponseInterface $response |
||
87 | 3 | * |
|
88 | * @return bool |
||
89 | 3 | */ |
|
90 | 3 | protected function isCacheable(ResponseInterface $response) |
|
91 | { |
||
92 | $cachableCodes = [200, 203, 300, 301, 302, 404, 410]; |
||
93 | 3 | $privateHeaders = $this->getCacheControlDirective($response, 'no-store') || $this->getCacheControlDirective($response, 'private'); |
|
94 | |||
95 | // If http status code is cachable and if we respect the headers, make sure there is no private cache headers. |
||
96 | return in_array($response->getStatusCode(), $cachableCodes) && !($this->config['respect_cache_headers'] && $privateHeaders); |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * Returns the value of a parameter in the cache control header. If not found we return false. If found with no |
||
101 | * value return true. |
||
102 | * |
||
103 | * @param ResponseInterface $response |
||
104 | * @param string $name |
||
105 | 3 | * |
|
106 | * @return bool|string |
||
107 | 3 | */ |
|
108 | 3 | private function getCacheControlDirective(ResponseInterface $response, $name) |
|
125 | |||
126 | /** |
||
127 | * @param RequestInterface $request |
||
128 | 3 | * |
|
129 | * @return string |
||
130 | 3 | */ |
|
131 | private function createCacheKey(RequestInterface $request) |
||
135 | |||
136 | /** |
||
137 | * Get a ttl in seconds. It could return null if we do not respect cache headers and got no defaultTtl. |
||
138 | * |
||
139 | * @param ResponseInterface $response |
||
140 | 2 | * |
|
141 | * @return int|null |
||
142 | 2 | */ |
|
143 | private function getMaxAge(ResponseInterface $response) |
||
168 | |||
169 | /** |
||
170 | * @param array $config |
||
171 | * |
||
172 | * @return array |
||
173 | */ |
||
174 | protected function configure(array $config = []) |
||
184 | } |
||
185 |