Completed
Pull Request — master (#8)
by Tobias
10:50
created

CachePlugin::getETag()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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