Completed
Push — master ( ae7c4d...f3215d )
by Michel
03:04
created

CacheUtil::hasCurrentState()   D

Complexity

Conditions 9
Paths 16

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 29
ccs 18
cts 18
cp 1
rs 4.909
cc 9
eloc 17
nc 16
nop 3
crap 9
1
<?php
2
/**
3
 * PSR-7 Cache Helpers
4
 *
5
 * @copyright Copyright (c) 2016, Michel Hunziker <[email protected]>
6
 * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD-3-Clause License
7
 */
8
9
namespace Micheh\Cache;
10
11
use DateTime;
12
use DateTimeZone;
13
use Exception;
14
use InvalidArgumentException;
15
use Micheh\Cache\Header\CacheControl;
16
use Micheh\Cache\Header\ResponseCacheControl;
17
use Psr\Http\Message\MessageInterface;
18
use Psr\Http\Message\RequestInterface;
19
use Psr\Http\Message\ResponseInterface;
20
21
/**
22
 * Util class to add cache headers to PSR-7 HTTP messages and to parse PSR-7 cache headers.
23
 */
24
class CacheUtil
25
{
26
    /**
27
     * Method to add a Cache-Control header to a PSR-7 response, which should enable caching.
28
     * Set the `private` parameter to false to enable shared caches to cache the response (for
29
     * example when the response is usable by everyone and does not contain individual information).
30
     * With the `$maxAge` parameter you can specify how many seconds a response should be cached.
31
     *
32
     * By default this method specifies a `private` cache, which caches for 10 minutes. For more
33
     * options use the `withCacheControl` method.
34
     *
35
     * @see withCacheControl
36
     *
37
     * @param ResponseInterface $response PSR-7 response to add the header to
38
     * @param bool $public True for public, false for private
39
     * @param int $maxAge How many seconds the response should be cached. Default: 600 (10 min)
40
     * @return ResponseInterface
41
     * @throws InvalidArgumentException If the type is invalid
42
     */
43 2
    public function withCache(ResponseInterface $response, $public = false, $maxAge = 600)
44
    {
45 2
        $control = new ResponseCacheControl();
46 2
        $control = $public ? $control->withPublic() : $control->withPrivate();
47 2
        $control = $control->withMaxAge($maxAge);
48
49 2
        return $this->withCacheControl($response, $control);
50
    }
51
52
    /**
53
     * Method to add a Cache-Control header to a PSR-7 response, which should prevent caching.
54
     * Adds `no-cache, no-store, must-revalidate`. Use the `withCacheControl` method for more
55
     * options.
56
     *
57
     * @see withCacheControl
58
     *
59
     * @param ResponseInterface $response PSR-7 response to prevent caching
60
     * @return ResponseInterface
61
     */
62 1
    public function withCachePrevention(ResponseInterface $response)
63
    {
64 1
        $control = new ResponseCacheControl();
65 1
        $control = $control->withCachePrevention();
66
67 1
        return $this->withCacheControl($response, $control);
68
    }
69
70
    /**
71
     * Method to add an Expires header to a PSR-7 response. Use this header if you have a specific
72
     * time when the representation will expire, otherwise use the more fine-tuned `Cache-Control`
73
     * header with the `max-age` directive. If you need to support the old HTTP/1.0 protocol and
74
     * want to set a relative expiration, use the `withRelativeExpires` method.
75
     *
76
     * @see withCache
77
     * @see withCacheControl
78
     * @see withRelativeExpires
79
     * @link https://tools.ietf.org/html/rfc7234#section-5.3
80
     *
81
     * @param ResponseInterface $response PSR-7 response to add the header to
82
     * @param int|string|DateTime $time UNIX timestamp, date string or DateTime object
83
     * @return ResponseInterface
84
     * @throws InvalidArgumentException If the time could not be parsed
85
     */
86 3
    public function withExpires(ResponseInterface $response, $time)
87
    {
88 3
        return $response->withHeader('Expires', $this->getTimeFromValue($time));
89
    }
90
91
    /**
92
     * Method to add a relative `Expires` header to a PSR-7 response. Use this header if want to
93
     * support the old HTTP/1.0 protocol and have a relative expiration time. Otherwise use the
94
     * `Cache-Control` header with the `max-age` directive.
95
     *
96
     * @see withCache
97
     * @see withCacheControl
98
     * @see withExpires
99
     * @link https://tools.ietf.org/html/rfc7234#section-5.3
100
     *
101
     * @param ResponseInterface $response PSR-7 response to add the header to
102
     * @param int $seconds Number of seconds the response should be cached
103
     * @return ResponseInterface
104
     * @throws InvalidArgumentException If the seconds parameter is not an integer
105
     */
106 2
    public function withRelativeExpires(ResponseInterface $response, $seconds)
107
    {
108 2
        if (!is_int($seconds)) {
109 1
            throw new InvalidArgumentException(
110 1
                'Expected an integer with the number of seconds, received ' . gettype($seconds) . '.'
111 1
            );
112
        }
113
114 1
        return $response->withHeader('Expires', $this->getTimeFromValue(time() + $seconds));
115
    }
116
117
    /**
118
     * Method to add an ETag header to a PSR-7 response. If possible, always add an ETag to a
119
     * response you want to cache. If the last modified time is easily accessible, use both the
120
     * ETag and Last-Modified header. Use a weak ETag if you want to compare if a resource is only
121
     * semantically the same.
122
     *
123
     * @see withLastModified
124
     * @link https://tools.ietf.org/html/rfc7232#section-2.3
125
     *
126
     * @param ResponseInterface $response PSR-7 response to add the header to
127
     * @param string $eTag ETag to add
128
     * @param bool $weak If the provided ETag is weak
129
     * @return ResponseInterface
130
     * @throws InvalidArgumentException if the ETag value is not valid
131
     */
132 3
    public function withETag(ResponseInterface $response, $eTag, $weak = false)
133
    {
134 3
        $eTag = '"' . trim($eTag, '"') . '"';
135 3
        if ($weak) {
136 1
            $eTag = 'W/' . $eTag;
137 1
        }
138
139 3
        return $response->withHeader('ETag', $eTag);
140
    }
141
142
    /**
143
     * Method to add a Last-Modified header to a PSR-7 response. Add a Last-Modified header if you
144
     * have an easy access to the last modified time, otherwise use only an ETag.
145
     *
146
     * The provided time can be an UNIX timestamp, a parseable string or a DateTime instance.
147
     *
148
     * @see withETag
149
     * @see getTimeFromValue
150
     * @link https://tools.ietf.org/html/rfc7232#section-2.2
151
     *
152
     * @param ResponseInterface $response PSR-7 response to add the header to
153
     * @param int|string|DateTime $time UNIX timestamp, date string or DateTime object
154
     * @return ResponseInterface
155
     * @throws InvalidArgumentException If the time could not be parsed
156
     */
157 1
    public function withLastModified(ResponseInterface $response, $time)
158
    {
159 1
        return $response->withHeader('Last-Modified', $this->getTimeFromValue($time));
160
    }
161
162
    /**
163
     * Method to add a Cache-Control header to the provided PSR-7 message.
164
     *
165
     * @link https://tools.ietf.org/html/rfc7234#section-5.2
166
     *
167
     * @param MessageInterface $message PSR-7 message to add the Cache-Control header to
168
     * @param CacheControl $cacheControl Cache-Control object to add to the message
169
     * @return MessageInterface The PSR-7 message with the added Cache-Control header
170
     * @throws InvalidArgumentException If the Cache-Control header is invalid
171
     */
172 1
    public function withCacheControl(MessageInterface $message, CacheControl $cacheControl)
173
    {
174 1
        return $message->withHeader('Cache-Control', (string) $cacheControl);
175
    }
176
177
    /**
178
     * Checks if a request has included validators (`ETag` and/or `Last-Modified` Date) which allow
179
     * to determine if the client has the current resource state. The method will check if the
180
     * `If-Match` and/or `If-Unmodified-Since` header is present.
181
     *
182
     * This method can be used for unsafe conditional requests (neither GET nor HEAD). If the
183
     * request did not include a state validator (method returns `false`), abort the execution and
184
     * return a `428` http status code (or `403` if you only want to use the original status
185
     * codes). If the requests includes state validators (method returns `true`), you can continue
186
     * and check if the client has the current state with the `hasCurrentState` method.
187
     *
188
     * @see hasCurrentState
189
     * @link https://tools.ietf.org/html/rfc7232#section-6
190
     *
191
     * @param RequestInterface $request PSR-7 request to check
192
     * @return bool True if the request includes state validators, false if it has no validators
193
     */
194 4
    public function hasStateValidator(RequestInterface $request)
195
    {
196 4
        return $request->hasHeader('If-Match') || $request->hasHeader('If-Unmodified-Since');
197
    }
198
199
    /**
200
     * Checks if the provided PSR-7 request has the current resource state. The method will check
201
     * the `If-Match` and `If-Modified-Since` headers with the current ETag (and/or the Last-Modified
202
     * date if provided). In addition, for a request which is not GET or HEAD, the method will check
203
     * the `If-None-Match` header.
204
     *
205
     * Use this method to check conditional unsafe requests and to prevent lost updates. If the
206
     * request does not have the current resource state (method returns `false`), abort and return
207
     * status code `412`. In contrast, if the client has the current version of the resource (method
208
     * returns `true`) you can safely continue the execution and update/delete the resource.
209
     *
210
     * @link https://tools.ietf.org/html/rfc7232#section-6
211
     *
212
     * @param RequestInterface $request PSR-7 request to check
213
     * @param string $eTag Current ETag of the resource
214
     * @param null|int|string|DateTime $lastModified Current Last-Modified date (optional)
215
     * @return bool True if the request has the current resource state, false if the state is outdated
216
     * @throws InvalidArgumentException If the Last-Modified date could not be parsed
217
     */
218 17
    public function hasCurrentState(RequestInterface $request, $eTag, $lastModified = null)
219
    {
220 17
        if ($eTag) {
221 11
            $eTag = '"' . trim($eTag, '"') . '"';
222 11
        }
223
224 17
        $ifMatch = $request->getHeaderLine('If-Match');
225 17
        if ($ifMatch) {
226 8
            if (!$this->matchesETag($eTag, $ifMatch)) {
227 4
                return false;
228
            }
229 4
        } else {
230 9
            $ifUnmodified = $request->getHeaderLine('If-Unmodified-Since');
231 9
            if ($ifUnmodified && !$this->matchesModified($lastModified, $ifUnmodified)) {
232 2
                return false;
233
            }
234
        }
235
236 11
        if (in_array($request->getMethod(), ['GET', 'HEAD'], true)) {
237 1
            return true;
238
        }
239
240 10
        $ifNoneMatch = $request->getHeaderLine('If-None-Match');
241 10
        if ($ifNoneMatch && $this->matchesETag($eTag, $ifNoneMatch)) {
1 ignored issue
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !($ifNoneMatch &&...($eTag, $ifNoneMatch));.
Loading history...
242 2
            return false;
243
        }
244
245 8
        return true;
246
    }
247
248
    /**
249
     * Method to check if the response is not modified and the request still has a valid cache, by
250
     * comparing the `ETag` headers. If no `ETag` is available and the method is GET or HEAD, the
251
     * `Last-Modified` header is used for comparison.
252
     *
253
     * Returns `true` if the request is not modified and the cache is still valid. In this case the
254
     * application should return an empty response with the status code `304`. If the returned
255
     * value is `false`, the client either has no cached representation or has an outdated cache.
256
     *
257
     * @link https://tools.ietf.org/html/rfc7232#section-6
258
     *
259
     * @param RequestInterface $request Request to check against
260
     * @param ResponseInterface $response Response with ETag and/or Last-Modified header
261
     * @return bool True if not modified, false if invalid cache
262
     * @throws InvalidArgumentException If the current Last-Modified date could not be parsed
263
     */
264 12
    public function isNotModified(RequestInterface $request, ResponseInterface $response)
265
    {
266 12
        $noneMatch = $request->getHeaderLine('If-None-Match');
267 12
        if ($noneMatch) {
268 7
            return $this->matchesETag($response->getHeaderLine('ETag'), $noneMatch);
269
        }
270
271 5
        if (!in_array($request->getMethod(), ['GET', 'HEAD'], true)) {
272 1
            return false;
273
        }
274
275 4
        $lastModified = $response->getHeaderLine('Last-Modified');
276 4
        $modifiedSince = $request->getHeaderLine('If-Modified-Since');
277
278 4
        return $this->matchesModified($lastModified, $modifiedSince);
279
    }
280
281
    /**
282
     * Method to check if a response can be cached by a shared cache. The method will check if the
283
     * response status is cacheable and if the Cache-Control header explicitly disallows caching.
284
     * The method does NOT check if the response is fresh. If you want to store the response on the
285
     * application side, check both `isCacheable` and `isFresh`.
286
     *
287
     * @see isFresh
288
     * @link https://tools.ietf.org/html/rfc7234#section-3
289
     *
290
     * @param ResponseInterface $response Response to check if it is cacheable
291
     * @return bool True if the response is cacheable by a shared cache and false otherwise
292
     */
293 4
    public function isCacheable(ResponseInterface $response)
294
    {
295 4
        if (!in_array($response->getStatusCode(), [200, 203, 204, /*206,*/ 300, 301, 404, 405, 410, 414, 501], true)) {
296 1
            return false;
297
        }
298
299 3
        if (!$response->hasHeader('Cache-Control')) {
300 1
            return true;
301
        }
302
303 2
        $cacheControl = $this->getCacheControl($response);
304 2
        return !$cacheControl->hasNoStore() && !$cacheControl->isPrivate();
305
    }
306
307
    /**
308
     * Method to check if a response is still fresh. This is useful if you want to know if can still
309
     * serve a saved response or if you have to create a new response. The method returns true if the
310
     * lifetime of the response is available and is greater than the age of the response. If the
311
     * method returns false, the response is outdated and should be renewed. In case no lifetime
312
     * information is available (no Cache-Control and Expires header), the method returns `null`.
313
     *
314
     * @see getLifetime
315
     * @see getAge
316
     * @link https://tools.ietf.org/html/rfc7234#section-4.2
317
     *
318
     * @param ResponseInterface $response Response to check
319
     * @return bool|null True if the response is still fresh and false otherwise. Null if unknown
320
     */
321 4
    public function isFresh(ResponseInterface $response)
322
    {
323 4
        $lifetime = $this->getLifetime($response);
324 4
        if ($lifetime !== null) {
325 3
            return $lifetime > $this->getAge($response);
326
        }
327
328 1
        return null;
329
    }
330
331
    /**
332
     * Returns the lifetime of the provided response (how long the response should be cached once it
333
     * is created). The method will lookup the `s-maxage` Cache-Control directive first and fallback
334
     * to the `max-age` directive. If both Cache-Control directives are not available, the `Expires`
335
     * header is used to compute the lifetime. Returns the lifetime in seconds if available and
336
     * `null` if the lifetime cannot be calculated.
337
     *
338
     * @param ResponseInterface $response Response to get the lifetime from
339
     * @return int|null Lifetime in seconds or null if not available
340
     */
341 7
    public function getLifetime(ResponseInterface $response)
342
    {
343 7
        if ($response->hasHeader('Cache-Control')) {
344 4
            $lifetime = $this->getCacheControl($response)->getLifetime();
345
346 4
            if ($lifetime !== null) {
347 3
                return $lifetime;
348
            }
349 1
        }
350
351 4
        $expires = $response->getHeaderLine('Expires');
352 4
        if ($expires) {
353 2
            $now = $response->getHeaderLine('Date');
354 2
            $now = $now ? strtotime($now) : time();
355 2
            return max(0, strtotime($expires) - $now);
356
        }
357
358 2
        return null;
359
    }
360
361
    /**
362
     * Returns the age of the response (how long the response is already cached). Uses the `Age`
363
     * header to determine the age. If the header is not available, the `Date` header is used
364
     * instead. The method will return the age in seconds or `null` if the age cannot be calculated.
365
     *
366
     * @param ResponseInterface $response Response to get the age from
367
     * @return int|null Age in seconds or null if not available
368
     */
369 3
    public function getAge(ResponseInterface $response)
370
    {
371 3
        $age = $response->getHeaderLine('Age');
372 3
        if ($age !== '') {
373 1
            return (int) $age;
374
        }
375
376 2
        $date = $response->getHeaderLine('Date');
377 2
        if ($date) {
378 1
            return max(0, time() - strtotime($date));
379
        }
380
381 1
        return null;
382
    }
383
384
    /**
385
     * Returns a formatted timestamp of the time parameter, to use in the HTTP headers. The time
386
     * parameter can be an UNIX timestamp, a parseable string or a DateTime object.
387
     *
388
     * @link https://secure.php.net/manual/en/datetime.formats.php
389
     *
390
     * @param int|string|DateTime $time Timestamp, date string or DateTime object
391
     * @return string Formatted timestamp
392
     * @throws InvalidArgumentException If the time could not be parsed
393
     */
394 6
    protected function getTimeFromValue($time)
395
    {
396 6
        $format = 'D, d M Y H:i:s \G\M\T';
397
398 6
        if (is_int($time)) {
399 2
            return gmdate($format, $time);
400
        }
401
402 4
        if (is_string($time)) {
403
            try {
404 2
                $time = new DateTime($time);
405 2
            } catch (Exception $exception) {
406
                // if it is an invalid date string an exception is thrown below
407
            }
408 2
        }
409
410 4
        if ($time instanceof DateTime) {
411 3
            $time = clone $time;
412 3
            $time->setTimezone(new DateTimeZone('UTC'));
413 3
            return $time->format($format);
414
        }
415
416 1
        throw new InvalidArgumentException('Could not create a valid date from ' . gettype($time) . '.');
417
    }
418
419
    /**
420
     * Returns the Unix timestamp of the time parameter. The parameter can be an Unix timestamp,
421
     * string or a DateTime object.
422
     *
423
     * @param int|string|DateTime $time
424
     * @return int Unix timestamp
425
     * @throws InvalidArgumentException If the time could not be parsed
426
     */
427 4
    protected function getTimestampFromValue($time)
428
    {
429 4
        if (is_int($time)) {
430 1
            return $time;
431
        }
432
433 3
        if ($time instanceof DateTime) {
434 1
            return $time->getTimestamp();
435
        }
436
437 2
        if (is_string($time)) {
438 1
            return strtotime($time);
439
        }
440
441 1
        throw new InvalidArgumentException('Could not create timestamp from ' . gettype($time) . '.');
442
    }
443
444
    /**
445
     * Parses the Cache-Control header of a response and returns the Cache-Control object.
446
     *
447
     * @param ResponseInterface $response
448
     * @return ResponseCacheControl
449
     */
450 1
    protected function getCacheControl(ResponseInterface $response)
451
    {
452 1
        return ResponseCacheControl::fromString($response->getHeaderLine('Cache-Control'));
453
    }
454
455
    /**
456
     * Method to check if the current ETag matches the ETag of the request.
457
     *
458
     * @link https://tools.ietf.org/html/rfc7232#section-2.3.2
459
     *
460
     * @param string $currentETag The current ETag
461
     * @param string $requestETags The ETags from the request
462
     * @return bool True if the current ETag matches the ETags of the request, false otherwise
463
     */
464 19
    private function matchesETag($currentETag, $requestETags)
465
    {
466 19
        if ($requestETags === '*') {
467 6
            return (bool) $currentETag;
468
        }
469
470
        // TODO Add weak and strong comparison
471 13
        return in_array($currentETag, preg_split('/\s*,\s*/', $requestETags), true);
472
    }
473
474
    /**
475
     * Method to check if the current Last-Modified date matches the date of the request.
476
     *
477
     * @param int|string|DateTime $currentModified Current Last-Modified date
478
     * @param string $requestModified Last-Modified date of the request
479
     * @return bool True if the current date matches the date of the request, false otherwise
480
     * @throws InvalidArgumentException If the current date could not be parsed
481
     */
482 8
    private function matchesModified($currentModified, $requestModified)
483
    {
484 8
        if (!$currentModified) {
485 1
            return false;
486
        }
487
488 7
        return $this->getTimestampFromValue($currentModified) <= strtotime($requestModified);
489
    }
490
}
491