Completed
Pull Request — master (#24)
by
unknown
03:04
created

CachePlugin::handleRequest()   C

Complexity

Conditions 12
Paths 7

Size

Total Lines 75
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 12.0014

Importance

Changes 0
Metric Value
dl 0
loc 75
ccs 45
cts 46
cp 0.9783
rs 5.3413
c 0
b 0
f 0
cc 12
eloc 42
nc 7
nop 3
crap 12.0014

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 12
    public function __construct(CacheItemPoolInterface $pool, StreamFactory $streamFactory, array $config = [])
51
    {
52 12
        $this->pool = $pool;
53 12
        $this->streamFactory = $streamFactory;
54
55 12
        $optionsResolver = new OptionsResolver();
56 12
        $this->configureOptions($optionsResolver);
57 12
        $this->config = $optionsResolver->resolve($config);
58 11
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63 9
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
64
    {
65 9
        $method = strtoupper($request->getMethod());
66
        // if the request not is cachable, move to $next
67 9
        if (!in_array($method, $this->config['methods'])) {
68 1
            return $next($request);
69
        }
70
71
        // If we can cache the request
72 8
        $key = $this->createCacheKey($request);
73 8
        $cacheItem = $this->pool->getItem($key);
74
75 8
        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
        return $next($request)->then(function (ResponseInterface $response) use ($cacheItem) {
94 7
            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->calculateResponseExpiresAt($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 5
            if ($this->isCacheable($response)) {
114 4
                $bodyStream = $response->getBody();
115 4
                $body = $bodyStream->__toString();
116 4
                if ($bodyStream->isSeekable()) {
117 4
                    $bodyStream->rewind();
118 4
                } else {
119
                    $response = $response->withBody($this->streamFactory->createStream($body));
120
                }
121
122 4
                $maxAge = $this->getMaxAge($response);
123
                $cacheItem
124 4
                    ->expiresAfter($this->calculateCacheItemExpiresAfter($maxAge))
125 4
                    ->set([
126 4
                        'response' => $response,
127 4
                        'body' => $body,
128 4
                        'expiresAt' => $this->calculateResponseExpiresAt($maxAge),
129 4
                        'createdAt' => time(),
130 4
                        'etag' => $response->getHeader('ETag'),
131 4
                    ]);
132 4
                $this->pool->save($cacheItem);
133 4
            }
134
135 5
            return $response;
136 7
        });
137
    }
138
139
    /**
140
     * Calculate the timestamp when this cache item should be dropped from the cache. The lowest value that can be
141
     * returned is $maxAge.
142
     *
143
     * @param int|null $maxAge
144
     *
145
     * @return int|null Unix system time passed to the PSR-6 cache
146
     */
147 5
    private function calculateCacheItemExpiresAfter($maxAge)
148
    {
149 5
        if ($this->config['cache_lifetime'] === null && $maxAge === null) {
150
            return;
151
        }
152
153 5
        return $this->config['cache_lifetime'] + $maxAge;
154
    }
155
156
    /**
157
     * Calculate the timestamp when a response expires. After that timestamp, we need to send a
158
     * If-Modified-Since / If-None-Match request to validate the response.
159
     *
160
     * @param int|null $maxAge
161
     *
162
     * @return int|null Unix system time. A null value means that the response expires when the cache item expires
163
     */
164 5
    private function calculateResponseExpiresAt($maxAge)
165
    {
166 5
        if ($maxAge === null) {
167
            return;
168
        }
169
170 5
        return time() + $maxAge;
171
    }
172
173
    /**
174
     * Verify that we can cache this response.
175
     *
176
     * @param ResponseInterface $response
177
     *
178
     * @return bool
179
     */
180 5
    protected function isCacheable(ResponseInterface $response)
181
    {
182 5
        if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) {
183 1
            return false;
184
        }
185 4
        if (!$this->config['respect_cache_headers']) {
186
            return true;
187
        }
188 4
        if ($this->getCacheControlDirective($response, 'no-store') || $this->getCacheControlDirective($response, 'private')) {
189
            return false;
190
        }
191
192 4
        return true;
193
    }
194
195
    /**
196
     * Get the value of a parameter in the cache control header.
197
     *
198
     * @param ResponseInterface $response
199
     * @param string            $name     The field of Cache-Control to fetch
200
     *
201
     * @return bool|string The value of the directive, true if directive without value, false if directive not present
202
     */
203 5
    private function getCacheControlDirective(ResponseInterface $response, $name)
204
    {
205 5
        $headers = $response->getHeader('Cache-Control');
206 5
        foreach ($headers as $header) {
207 1
            if (preg_match(sprintf('|%s=?([0-9]+)?|i', $name), $header, $matches)) {
208
                // return the value for $name if it exists
209 1
                if (isset($matches[1])) {
210 1
                    return $matches[1];
211
                }
212
213
                return true;
214
            }
215 5
        }
216
217 5
        return false;
218
    }
219
220
    /**
221
     * @param RequestInterface $request
222
     *
223
     * @return string
224
     */
225 8
    private function createCacheKey(RequestInterface $request)
226
    {
227 8
        return hash($this->config['hash_algo'], $request->getMethod().' '.$request->getUri().$request->getBody());
228
    }
229
230
    /**
231
     * Get a ttl in seconds. It could return null if we do not respect cache headers and got no defaultTtl.
232
     *
233
     * @param ResponseInterface $response
234
     *
235
     * @return int|null
236
     */
237 5
    private function getMaxAge(ResponseInterface $response)
238
    {
239 5
        if (!$this->config['respect_cache_headers']) {
240
            return $this->config['default_ttl'];
241
        }
242
243
        // check for max age in the Cache-Control header
244 5
        $maxAge = $this->getCacheControlDirective($response, 'max-age');
245 5
        if (!is_bool($maxAge)) {
246 1
            $ageHeaders = $response->getHeader('Age');
247 1
            foreach ($ageHeaders as $age) {
248 1
                return $maxAge - ((int) $age);
249
            }
250
251
            return (int) $maxAge;
252
        }
253
254
        // check for ttl in the Expires header
255 4
        $headers = $response->getHeader('Expires');
256 4
        foreach ($headers as $header) {
257
            return (new \DateTime($header))->getTimestamp() - (new \DateTime())->getTimestamp();
258 4
        }
259
260 4
        return $this->config['default_ttl'];
261
    }
262
263
    /**
264
     * Configure an options resolver.
265
     *
266
     * @param OptionsResolver $resolver
267
     */
268 12
    private function configureOptions(OptionsResolver $resolver)
269
    {
270 12
        $resolver->setDefaults([
271 12
            'cache_lifetime' => 86400 * 30, // 30 days
272 12
            'default_ttl' => 0,
273 12
            'respect_cache_headers' => true,
274 12
            'hash_algo' => 'sha1',
275 12
            'methods' => ['GET', 'HEAD'],
276 12
        ]);
277
278 12
        $resolver->setAllowedTypes('cache_lifetime', ['int', 'null']);
279 12
        $resolver->setAllowedTypes('default_ttl', ['int', 'null']);
280 12
        $resolver->setAllowedTypes('respect_cache_headers', 'bool');
281 12
        $resolver->setAllowedTypes('methods', 'array');
282 12
        $resolver->setAllowedValues('hash_algo', hash_algos());
283 12
        $resolver->setAllowedValues('methods', function ($value) {
284
            /* Any VCHAR, except delimiters. RFC7230 sections 3.1.1 and 3.2.6 */
285 12
            $matches = preg_grep('/[^[:alnum:]!#$%&\'*\/+\-.^_`|~]/', $value);
286
287 12
            return empty($matches);
288 12
        });
289 12
    }
290
291
    /**
292
     * @param CacheItemInterface $cacheItem
293
     *
294
     * @return ResponseInterface
295
     */
296 2
    private function createResponseFromCacheItem(CacheItemInterface $cacheItem)
297
    {
298 2
        $data = $cacheItem->get();
299
300
        /** @var ResponseInterface $response */
301 2
        $response = $data['response'];
302 2
        $response = $response->withBody($this->streamFactory->createStream($data['body']));
303
304 2
        return $response;
305
    }
306
307
    /**
308
     * Get the value of the "If-Modified-Since" header.
309
     *
310
     * @param CacheItemInterface $cacheItem
311
     *
312
     * @return string|null
313
     */
314 2
    private function getModifiedSinceHeaderValue(CacheItemInterface $cacheItem)
315
    {
316 2
        $data = $cacheItem->get();
317
        // The isset() is to be removed in 2.0.
318 2
        if (!isset($data['createdAt'])) {
319
            return;
320
        }
321
322 2
        $modified = new \DateTime('@'.$data['createdAt']);
323 2
        $modified->setTimezone(new \DateTimeZone('GMT'));
324
325 2
        return sprintf('%s GMT', $modified->format('l, d-M-y H:i:s'));
326
    }
327
328
    /**
329
     * Get the ETag from the cached response.
330
     *
331
     * @param CacheItemInterface $cacheItem
332
     *
333
     * @return string|null
334
     */
335 2
    private function getETag(CacheItemInterface $cacheItem)
336
    {
337 2
        $data = $cacheItem->get();
338
        // The isset() is to be removed in 2.0.
339 2
        if (!isset($data['etag'])) {
340
            return;
341
        }
342
343 2
        if (!is_array($data['etag'])) {
344
            return $data['etag'];
345
        }
346
347 2
        foreach ($data['etag'] as $etag) {
348 2
            if (!empty($etag)) {
349 2
                return $etag;
350
            }
351
        }
352
    }
353
}
354