Completed
Pull Request — master (#21)
by Tobias
04:07 queued 26s
created

CachePlugin::configureOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 9.4286
cc 1
eloc 6
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Http\Client\Tools\Promise\FulfilledPromise;
6
use Http\Message\StreamFactory;
7
use Psr\Cache\CacheItemPoolInterface;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use Symfony\Component\OptionsResolver\OptionsResolver;
11
12
/**
13
 * Allow for caching a response.
14
 *
15
 * @author Tobias Nyholm <[email protected]>
16
 */
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
    /**
30
     * @var array
31
     */
32
    private $config;
33
34
    /**
35
     * Available options are
36
     *  - respect_cache_headers: Whether to look at the cache directives or ignore them.
37
     *  - default_ttl: If we do not respect cache headers or can't calculate a good ttl, use this value.
38
     *
39
     * @param CacheItemPoolInterface $pool
40
     * @param StreamFactory          $streamFactory
41
     * @param array                  $config
42
     */
43 6
    public function __construct(CacheItemPoolInterface $pool, StreamFactory $streamFactory, array $config = [])
44
    {
45 6
        $this->pool = $pool;
46 6
        $this->streamFactory = $streamFactory;
47
48 6
        $optionsResolver = new OptionsResolver();
49 6
        $this->configureOptions($optionsResolver);
50 6
        $this->config = $optionsResolver->resolve($config);
51 6
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 4
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
57
    {
58 4
        $method = strtoupper($request->getMethod());
59
60
        // if the request not is cachable, move to $next
61 4
        if ($method !== 'GET' && $method !== 'HEAD') {
62 1
            return $next($request);
63
        }
64
65
        // If we can cache the request
66 3
        $key = $this->createCacheKey($request);
67 3
        $cacheItem = $this->pool->getItem($key);
68
69 3
        if ($cacheItem->isHit()) {
70
            // return cached response
71
            $data = $cacheItem->get();
72
            $response = $data['response'];
73
            $response = $response->withBody($this->streamFactory->createStream($data['body']));
74
75
            return new FulfilledPromise($response);
76
        }
77
78 3
        return $next($request)->then(function (ResponseInterface $response) use ($cacheItem) {
79 3
            if ($this->isCacheable($response)) {
80 2
                $cacheItem->set(['response' => $response, 'body' => $response->getBody()->__toString()])
81 2
                    ->expiresAfter($this->getMaxAge($response));
82 2
                $this->pool->save($cacheItem);
83 2
            }
84
85 3
            return $response;
86 3
        });
87
    }
88
89
    /**
90
     * Verify that we can cache this response.
91
     *
92
     * @param ResponseInterface $response
93
     *
94
     * @return bool
95
     */
96 3
    protected function isCacheable(ResponseInterface $response)
97
    {
98 3
        if (!in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 404, 410])) {
99 1
            return false;
100
        }
101 2
        if (!$this->config['respect_cache_headers']) {
102
            return true;
103
        }
104 2
        if ($this->getCacheControlDirective($response, 'no-store') || $this->getCacheControlDirective($response, 'private')) {
105
            return false;
106
        }
107
108 2
        return true;
109
    }
110
111
    /**
112
     * Get the value of a parameter in the cache control header.
113
     *
114
     * @param ResponseInterface $response
115
     * @param string            $name     The field of Cache-Control to fetch
116
     *
117
     * @return bool|string The value of the directive, true if directive without value, false if directive not present.
118
     */
119 2
    private function getCacheControlDirective(ResponseInterface $response, $name)
120
    {
121 2
        $headers = $response->getHeader('Cache-Control');
122 2
        foreach ($headers as $header) {
123 1
            if (preg_match(sprintf('|%s=?([0-9]+)?|i', $name), $header, $matches)) {
124
125
                // return the value for $name if it exists
126 1
                if (isset($matches[1])) {
127 1
                    return $matches[1];
128
                }
129
130
                return true;
131
            }
132 2
        }
133
134 2
        return false;
135
    }
136
137
    /**
138
     * @param RequestInterface $request
139
     *
140
     * @return string
141
     */
142 3
    private function createCacheKey(RequestInterface $request)
143
    {
144 3
        return md5($request->getMethod().' '.$request->getUri());
145
    }
146
147
    /**
148
     * Get a ttl in seconds. It could return null if we do not respect cache headers and got no defaultTtl.
149
     *
150
     * @param ResponseInterface $response
151
     *
152
     * @return int|null
153
     */
154 2
    private function getMaxAge(ResponseInterface $response)
155
    {
156 2
        if (!$this->config['respect_cache_headers']) {
157
            return $this->config['default_ttl'];
158
        }
159
160
        // check for max age in the Cache-Control header
161 2
        $maxAge = $this->getCacheControlDirective($response, 'max-age');
162 2
        if (!is_bool($maxAge)) {
163 1
            $ageHeaders = $response->getHeader('Age');
164 1
            foreach ($ageHeaders as $age) {
165 1
                return $maxAge - ((int) $age);
166
            }
167
168
            return $maxAge;
169
        }
170
171
        // check for ttl in the Expires header
172 1
        $headers = $response->getHeader('Expires');
173 1
        foreach ($headers as $header) {
174
            return (new \DateTime($header))->getTimestamp() - (new \DateTime())->getTimestamp();
175 1
        }
176
177 1
        return $this->config['default_ttl'];
178
    }
179
180
    /**
181
     * Configure an options resolver.
182
     *
183
     * @param OptionsResolver $resolver
184
     *
185
     * @return array
186
     */
187 6
    private function configureOptions(OptionsResolver $resolver)
188
    {
189 6
        $resolver->setDefaults([
190 6
            'default_ttl' => null,
191 6
            'respect_cache_headers' => true,
192 6
        ]);
193
194 6
        $resolver->setAllowedTypes('default_ttl', ['int', 'null']);
195 6
        $resolver->setAllowedTypes('respect_cache_headers', 'bool');
196 6
    }
197
}
198