Completed
Pull Request — master (#20)
by Tobias
05:53
created

CachePlugin::calculateCacheItemExpiresAfter()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

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