Completed
Pull Request — master (#8)
by Tobias
14:07
created

CachePlugin::configureOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 12
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
crap 2
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 If we do not respect cache headers or can't calculate a good ttl, use this value.
43
     * }
44 6
     */
45
    public function __construct(CacheItemPoolInterface $pool, StreamFactory $streamFactory, array $config = [])
46 6
    {
47 6
        $this->pool = $pool;
48
        $this->streamFactory = $streamFactory;
49 6
50 6
        $optionsResolver = new OptionsResolver();
51 6
        $this->configureOptions($optionsResolver);
52 6
        $this->config = $optionsResolver->resolve($config);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57 4
     */
58
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
59 4
    {
60
        $method = strtoupper($request->getMethod());
61
        // if the request not is cachable, move to $next
62 4
        if ($method !== 'GET' && $method !== 'HEAD') {
63 1
            return $next($request);
64
        }
65
66
        // If we can cache the request
67 3
        $key = $this->createCacheKey($request);
68 3
        $cacheItem = $this->pool->getItem($key);
69
70 3
        if ($cacheItem->isHit()) {
71
            $data = $cacheItem->get();
72
            if (isset($data['expiresAt']) && time() > $data['expiresAt']) {
73
                // This item is still valid according to previous cache headers
74
                return new FulfilledPromise($this->createResponseFromCacheItem($cacheItem));
75
            }
76
77
            // Add headers to ask the server if this cache is still valid
78
            if ($modifiedAt = $this->getModifiedAt($cacheItem)) {
79 3
                $modifiedAt = new \DateTime('@'.$modifiedAt);
80 3
                $modifiedAt->setTimezone(new \DateTimeZone('GMT'));
81 2
                $request = $request->withHeader(
82 2
                    'If-Modified-Since',
83 2
                    sprintf('%s GMT', $modifiedAt->format('l, d-M-y H:i:s'))
84 2
                );
85 2
            }
86
87
            if ($etag = $this->getETag($cacheItem)) {
88
                $request = $request->withHeader(
89 2
                    'If-None-Match',
90 2
                    $etag
91 2
                );
92 2
            }
93
        }
94 3
95 3
96
        return $next($request)->then(function (ResponseInterface $response) use ($cacheItem) {
97
            if (304 === $response->getStatusCode()) {
98
                if (!$cacheItem->isHit()) {
99
                    // We do not have the item in cache. We can return the cached response.
100
                    return $response;
101
                }
102
103
                // The cached response we have is still valid
104
                $data = $cacheItem->get();
105 3
                $maxAge = $this->getMaxAge($response);
106
                $data['expiresAt'] = time() + $maxAge;
107 3
                $cacheItem->set($data)->expiresAfter($this->config['cache_lifetime'] + $maxAge);
108 1
                $this->pool->save($cacheItem);
109
110 2
                return $this->createResponseFromCacheItem($cacheItem);
111
            }
112
113 2
            if ($this->isCacheable($response)) {
114
                $bodyStream = $response->getBody();
115
                $body = $bodyStream->__toString();
116
                if ($bodyStream->isSeekable()) {
117 2
                    $bodyStream->rewind();
118
                } else {
119
                    $response = $response->withBody($this->streamFactory->createStream($body));
120
                }
121
122
                $maxAge = $this->getMaxAge($response);
123
                $cacheItem
124
                    ->expiresAfter($this->config['cache_lifetime'] + $maxAge)
125
                    ->set([
126
                    'response' => $response,
127
                    'body' => $body,
128 2
                    'expiresAt' => time() + $maxAge,
129
                    'createdAt' => time(),
130 2
                    'etag' => $response->getHeader('ETag'),
131 2
                ]);
132 1
                $this->pool->save($cacheItem);
133
            }
134
135 1
            return $response;
136 1
        });
137
    }
138
139
    /**
140
     * Verify that we can cache this response.
141 2
     *
142
     * @param ResponseInterface $response
143 2
     *
144
     * @return bool
145
     */
146
    protected function isCacheable(ResponseInterface $response)
147
    {
148
        if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) {
149
            return false;
150
        }
151 3
        if (!$this->config['respect_cache_headers']) {
152
            return true;
153 3
        }
154
        if ($this->getCacheControlDirective($response, 'no-store') || $this->getCacheControlDirective($response, 'private')) {
155
            return false;
156
        }
157
158
        return true;
159
    }
160
161
    /**
162
     * Get the value of a parameter in the cache control header.
163 2
     *
164
     * @param ResponseInterface $response
165 2
     * @param string            $name     The field of Cache-Control to fetch
166
     *
167
     * @return bool|string The value of the directive, true if directive without value, false if directive not present
168
     */
169
    private function getCacheControlDirective(ResponseInterface $response, $name)
170 2
    {
171 2
        $headers = $response->getHeader('Cache-Control');
172 1
        foreach ($headers as $header) {
173 1
            if (preg_match(sprintf('|%s=?([0-9]+)?|i', $name), $header, $matches)) {
174 1
175
                // return the value for $name if it exists
176
                if (isset($matches[1])) {
177
                    return $matches[1];
178
                }
179
180
                return true;
181 1
            }
182 1
        }
183
184 1
        return false;
185
    }
186 1
187
    /**
188
     * @param RequestInterface $request
189
     *
190
     * @return string
191
     */
192
    private function createCacheKey(RequestInterface $request)
193
    {
194 6
        return md5($request->getMethod().' '.$request->getUri());
195
    }
196 6
197 6
    /**
198 6
     * Get a ttl in seconds. It could return null if we do not respect cache headers and got no defaultTtl.
199 6
     *
200
     * @param ResponseInterface $response
201 6
     *
202 6
     * @return int|null
203 6
     */
204
    private function getMaxAge(ResponseInterface $response)
205
    {
206
        if (!$this->config['respect_cache_headers']) {
207
            return $this->config['default_ttl'];
208
        }
209
210
        // check for max age in the Cache-Control header
211
        $maxAge = $this->getCacheControlDirective($response, 'max-age');
212
        if (!is_bool($maxAge)) {
213
            $ageHeaders = $response->getHeader('Age');
214
            foreach ($ageHeaders as $age) {
215
                return $maxAge - ((int) $age);
216
            }
217
218
            return (int) $maxAge;
219
        }
220
221
        // check for ttl in the Expires header
222
        $headers = $response->getHeader('Expires');
223
        foreach ($headers as $header) {
224
            return (new \DateTime($header))->getTimestamp() - (new \DateTime())->getTimestamp();
225
        }
226
227
        return $this->config['default_ttl'];
228
    }
229
230
    /**
231
     * Configure an options resolver.
232
     *
233
     * @param OptionsResolver $resolver
234
     */
235
    private function configureOptions(OptionsResolver $resolver)
236
    {
237
        $resolver->setDefaults([
238
            'cache_lifetime' => 2592000, // 30 days
239
            'default_ttl' => null,
240
            'respect_cache_headers' => true,
241
        ]);
242
243
        $resolver->setAllowedTypes('cache_lifetime', 'int');
244
        $resolver->setAllowedTypes('default_ttl', ['int', 'null']);
245
        $resolver->setAllowedTypes('respect_cache_headers', 'bool');
246
    }
247
248
    /**
249
     * @param CacheItemInterface $cacheItem
250
     *
251
     * @return ResponseInterface
252
     */
253
    private function createResponseFromCacheItem(CacheItemInterface $cacheItem)
254
    {
255
        $data = $cacheItem->get();
256
257
        /** @var ResponseInterface $response */
258
        $response = $data['response'];
259
        $response = $response->withBody($this->streamFactory->createStream($data['body']));
260
261
        return $response;
262
    }
263
264
    /**
265
     * Get the timestamp when the cached response was stored.
266
     *
267
     * @param CacheItemInterface $cacheItem
268
     *
269
     * @return int|null
270
     */
271
    private function getModifiedAt(CacheItemInterface $cacheItem)
272
    {
273
        $data = $cacheItem->get();
274
        if (!isset($data['createdAt'])) {
275
            return;
276
        }
277
278
        return $data['createdAt'];
279
    }
280
281
    /**
282
     * Get the ETag from the cached response.
283
     *
284
     * @param CacheItemInterface $cacheItem
285
     *
286
     * @return string|null
287
     */
288
    private function getETag(CacheItemInterface $cacheItem)
289
    {
290
        $data = $cacheItem->get();
291
        if (!isset($data['etag'])) {
292
            return;
293
        }
294
295
        if (is_array($data['etag'])) {
296
            foreach ($data['etag'] as $etag) {
297
                if (!empty($etag)) {
298
                    return $etag;
299
                }
300
            }
301
302
            return;
303
        }
304
305
        return $data['etag'];
306
    }
307
}
308