-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathCache.php
More file actions
108 lines (92 loc) · 3.07 KB
/
Copy pathCache.php
File metadata and controls
108 lines (92 loc) · 3.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace Slim\HttpCache;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class Cache
{
/**
* Cache-Control type (public or private)
*
* @var string
*/
protected $type;
/**
* Cache-Control max age in seconds
*
* @var int
*/
protected $maxAge;
/**
* Cache-Control includes must-revalidate flag
*
* @var bool
*/
protected $mustRevalidate;
/**
* Create new HTTP cache
*
* @param string $type The cache type: "public" or "private"
* @param int $maxAge The maximum age of client-side cache
* @param bool $mustRevalidate must-revalidate
*/
public function __construct($type = 'private', $maxAge = 86400, $mustRevalidate = false)
{
$this->type = $type;
$this->maxAge = $maxAge;
$this->mustRevalidate = $mustRevalidate;
}
/**
* Invoke cache middleware
*
* @param RequestInterface $request A PSR7 request object
* @param ResponseInterface $response A PSR7 response object
* @param callable $next The next middleware callable
*
* @return ResponseInterface A PSR7 response object
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$response = $next($request, $response);
// Cache-Control header
if (!$response->hasHeader('Cache-Control')) {
if ($this->maxAge === 0) {
$response = $response->withHeader('Cache-Control', sprintf(
'%s, no-cache%s',
$this->type,
$this->mustRevalidate ? ', must-revalidate' : ''
));
} else {
$response = $response->withHeader('Cache-Control', sprintf(
'%s, max-age=%s%s',
$this->type,
$this->maxAge,
$this->mustRevalidate ? ', must-revalidate' : ''
));
}
}
// ETag header and conditional GET check
$etag = $response->getHeader('ETag');
$etag = reset($etag);
if ($etag) {
$ifNoneMatch = $request->getHeaderLine('If-None-Match');
if ($ifNoneMatch) {
$etagList = preg_split('@\s*,\s*@', $ifNoneMatch);
if (in_array($etag, $etagList) || in_array('*', $etagList)) {
return $response->withStatus(304);
}
}
}
// Last-Modified header and conditional GET check
$lastModified = $response->getHeaderLine('Last-Modified');
if ($lastModified) {
if (!is_integer($lastModified)) {
$lastModified = strtotime($lastModified);
}
$ifModifiedSince = $request->getHeaderLine('If-Modified-Since');
if ($ifModifiedSince && $lastModified <= strtotime($ifModifiedSince)) {
return $response->withStatus(304);
}
}
return $response;
}
}