Completed
Pull Request — master (#39)
by Jérôme
02:40
created

PrivateCacheStrategy::fetch()   D

Complexity

Conditions 9
Paths 20

Size

Total Lines 37
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 37
rs 4.909
cc 9
eloc 19
nc 20
nop 1
1
<?php
2
3
namespace Kevinrob\GuzzleCache\Strategy;
4
5
use Kevinrob\GuzzleCache\CacheEntry;
6
use Kevinrob\GuzzleCache\KeyValueHttpHeader;
7
use Kevinrob\GuzzleCache\Storage\CacheStorageInterface;
8
use Kevinrob\GuzzleCache\Storage\VolatileRuntimeStorage;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
12
/**
13
 * This strategy represent a "private" HTTP client.
14
 * Pay attention to share storage between application with caution!
15
 *
16
 * For example, a response with cache-control header "private, max-age=60"
17
 * will be cached by this strategy.
18
 *
19
 * The rules applied are from RFC 7234.
20
 *
21
 * @see https://tools.ietf.org/html/rfc7234
22
 */
23
class PrivateCacheStrategy implements CacheStrategyInterface
24
{
25
    /**
26
     * @var CacheStorageInterface
27
     */
28
    protected $storage;
29
30
    /**
31
     * @var int[]
32
     */
33
    protected $statusAccepted = [
34
        200 => 200,
35
        203 => 203,
36
        204 => 204,
37
        300 => 300,
38
        301 => 301,
39
        404 => 404,
40
        405 => 405,
41
        410 => 410,
42
        414 => 414,
43
        418 => 418,
44
        501 => 501,
45
    ];
46
47
    /**
48
     * @var string[]
49
     */
50
    protected $ageKey = [
51
        'max-age',
52
    ];
53
54
    public function __construct(CacheStorageInterface $cache = null)
55
    {
56
        $this->storage = $cache !== null ? $cache : new VolatileRuntimeStorage();
57
    }
58
59
    /**
60
     * @param RequestInterface $request
61
     * @param ResponseInterface $response
62
     * @return CacheEntry|null entry to save, null if can't cache it
63
     */
64
    protected function getCacheObject(RequestInterface $request, ResponseInterface $response)
65
    {
66
        if (!isset($this->statusAccepted[$response->getStatusCode()])) {
67
            // Don't cache it
68
            return;
69
        }
70
71
        $cacheControl = new KeyValueHttpHeader($response->getHeader('Cache-Control'));
72
        $varyHeader = new KeyValueHttpHeader($response->getHeader('Vary'));
73
74
        if ($varyHeader->has('*')) {
75
            // This will never match with a request
76
            return;
77
        }
78
79
        if ($cacheControl->has('no-store')) {
80
            // No store allowed (maybe some sensitives data...)
81
            return;
82
        }
83
84
        if ($cacheControl->has('no-cache')) {
85
            // Stale response see RFC7234 section 5.2.1.4
86
            $entry = new CacheEntry($request, $response, new \DateTime('-1 seconds'));
87
88
            return $entry->hasValidationInformation() ? $entry : null;
89
        }
90
91
        foreach ($this->ageKey as $key) {
92
            if ($cacheControl->has($key)) {
93
                return new CacheEntry(
94
                    $request,
95
                    $response,
96
                    new \DateTime('+'.(int) $cacheControl->get($key).'seconds')
97
                );
98
            }
99
        }
100
101
        if ($response->hasHeader('Expires')) {
102
            $expireAt = \DateTime::createFromFormat(\DateTime::RFC1123, $response->getHeaderLine('Expires'));
103
            if ($expireAt !== false) {
104
                return new CacheEntry(
105
                    $request,
106
                    $response,
107
                    $expireAt
108
                );
109
            }
110
        }
111
112
        return new CacheEntry($request, $response, new \DateTime('-1 seconds'));
113
    }
114
115
    /**
116
     * @param RequestInterface $request
117
     *
118
     * @return string
119
     */
120
    protected function getCacheKey(RequestInterface $request)
121
    {
122
        return sha1(
123
            $request->getMethod().$request->getUri()
124
        );
125
    }
126
127
    /**
128
     * Return a CacheEntry or null if no cache.
129
     *
130
     * @param RequestInterface $request
131
     *
132
     * @return CacheEntry|null
133
     */
134
    public function fetch(RequestInterface $request)
135
    {
136
        /** @var int|null $maxAge */
137
        $maxAge = null;
138
139
        if ($request->hasHeader('Cache-Control')) {
140
            $reqCacheControl = new KeyValueHttpHeader($request->getHeader('Cache-Control'));
141
            if ($reqCacheControl->has('no-cache')) {
142
                // Can't return cache
143
                return null;
144
            }
145
146
            $maxAge = $reqCacheControl->get('max-age', null);
147
        } elseif ($request->hasHeader('Pragma')) {
148
            $pragma = new KeyValueHttpHeader($request->getHeader('Pragma'));
149
            if ($pragma->has('no-cache')) {
150
                // Can't return cache
151
                return null;
152
            }
153
        }
154
155
        $cache = $this->storage->fetch($this->getCacheKey($request));
156
        if ($cache !== null) {
157
            if ($maxAge !== null) {
158
                if ($cache->getAge() > $maxAge) {
159
                    // Cache entry is too old for the request requirements!
160
                    return null;
161
                }
162
            }
163
164
            if (!$cache->isVaryEquals($request)) {
165
                return null;
166
            }
167
        }
168
169
        return $cache;
170
    }
171
172
    /**
173
     * @param RequestInterface  $request
174
     * @param ResponseInterface $response
175
     *
176
     * @return bool true if success
177
     */
178
    public function cache(RequestInterface $request, ResponseInterface $response)
179
    {
180
        $reqCacheControl = new KeyValueHttpHeader($request->getHeader('Cache-Control'));
181
        if ($reqCacheControl->has('no-store')) {
182
            // No caching allowed
183
            return false;
184
        }
185
186
        $cacheObject = $this->getCacheObject($request, $response);
187
        if ($cacheObject !== null) {
188
            return $this->storage->save(
189
                $this->getCacheKey($request),
190
                $cacheObject
191
            );
192
        }
193
194
        return false;
195
    }
196
197
    public function invalidate(RequestInterface $request)
198
    {
199
        return $this->storage->delete(
200
            $this->getCacheKey($request)
201
        );
202
    }
203
}
204