Completed
Pull Request — master (#21)
by Tobias
10:41 queued 43s
created

CachePlugin::setConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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