Passed
Pull Request — master (#199)
by Rustam
02:00
created

HttpCache::setLastModified()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
namespace Yiisoft\Yii\Web\Middleware;
3
4
use Psr\Http\Message\ResponseFactoryInterface;
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Server\RequestHandlerInterface;
9
use Yiisoft\Http\Method;
10
11
/**
12
 * HttpCache implements client-side caching by utilizing the `Last-Modified` and `ETag` HTTP headers.
13
 */
14
final class HttpCache implements MiddlewareInterface
15
{
16
    private const DEFAULT_HEADER = 'public, max-age=3600';
17
18
    /**
19
     * @var callable a PHP callback that returns the UNIX timestamp of the last modification time.
20
     * The callback's signature should be:
21
     *
22
     * ```php
23
     * function (ServerRequestInterface $request, $params): int
24
     * ```
25
     *
26
     * where `$request` is the {@see ServerRequestInterface} object that this filter is currently handling;
27
     * `$params` takes the value of {@see params}. The callback should return a UNIX timestamp.
28
     *
29
     * @see http://tools.ietf.org/html/rfc7232#section-2.2
30
     */
31
    private $lastModified;
32
33
    /**
34
     * @var callable a PHP callback that generates the ETag seed string.
35
     * The callback's signature should be:
36
     *
37
     * ```php
38
     * function (ServerRequestInterface $request, $params): string
39
     * ```
40
     *
41
     * where `$request` is the {@see ServerRequestInterface} object that this middleware is currently handling;
42
     * `$params` takes the value of {@see $params}. The callback should return a string serving
43
     * as the seed for generating an ETag.
44
     */
45
    private $etagSeed;
46
47
    /**
48
     * @var bool whether to generate weak ETags.
49
     *
50
     * Weak ETags should be used if the content should be considered semantically equivalent, but not byte-equal.
51
     *
52
     * @see http://tools.ietf.org/html/rfc7232#section-2.3
53
     */
54
    private bool $weakEtag = false;
55
56
    /**
57
     * @var mixed additional parameters that should be passed to the {@see $lastModified} and {@see etagSeed} callbacks.
58
     */
59
    private $params;
60
61
    /**
62
     * @var string the value of the `Cache-Control` HTTP header. If null, the header will not be sent.
63
     * @see http://tools.ietf.org/html/rfc2616#section-14.9
64
     */
65
    private ?string $cacheControlHeader = self::DEFAULT_HEADER;
66
67
    private ResponseFactoryInterface $responseFactory;
68
69
    public function __construct(ResponseFactoryInterface $responseFactory)
70
    {
71
        $this->responseFactory = $responseFactory;
72
    }
73
74
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
75
    {
76
        $method = $request->getMethod();
77
        if (
78
            !\in_array($method, [Method::GET, Method::HEAD])
79
            || ($this->lastModified === null && $this->etagSeed === null)
80
        ) {
81
            return $handler->handle($request);
82
        }
83
84
        $lastModified = $etag = null;
85
        if ($this->lastModified !== null) {
86
            $lastModified = call_user_func($this->lastModified, $request, $this->params);
87
        }
88
89
        if ($this->etagSeed !== null) {
90
            $seed = call_user_func($this->etagSeed, $request, $this->params);
91
            if ($seed !== null) {
92
                $etag = $this->generateEtag($seed);
93
            }
94
        }
95
96
        $cacheValid = $this->validateCache($request, $lastModified, $etag);
97
        if ($cacheValid) {
98
            $response = $this->responseFactory->createResponse(304);
99
            $response = $response->withHeader(
100
                'Last-Modified',
101
                gmdate('D, d M Y H:i:s', $lastModified) . ' GMT'
102
            );
103
            return $response;
104
        }
105
106
        $response = $handler->handle($request);
107
        if ($this->cacheControlHeader !== null) {
108
            $response = $response->withHeader('Cache-Control', $this->cacheControlHeader);
109
        }
110
        if ($etag !== null) {
111
            $response = $response->withHeader('Etag', $etag);
112
        }
113
114
        // https://tools.ietf.org/html/rfc7232#section-4.1
115
        if ($lastModified !== null && (!$cacheValid || ($cacheValid && $etag === null))) {
116
            $response = $response->withHeader(
117
                'Last-Modified',
118
                gmdate('D, d M Y H:i:s', $lastModified) . ' GMT'
119
            );
120
        }
121
122
        return $response;
123
    }
124
125
    /**
126
     * Validates if the HTTP cache contains valid content.
127
     * If both Last-Modified and ETag are null, returns false.
128
     * @param ServerRequestInterface $request
129
     * @param int|null $lastModified the calculated Last-Modified value in terms of a UNIX timestamp.
130
     * If null, the Last-Modified header will not be validated.
131
     * @param string|null $etag the calculated ETag value. If null, the ETag header will not be validated.
132
     * @return bool whether the HTTP cache is still valid.
133
     */
134
    private function validateCache(ServerRequestInterface $request, ?int $lastModified, ?string $etag): bool
135
    {
136
        if ($request->hasHeader('If-None-Match')) {
137
            // HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
138
            // http://tools.ietf.org/html/rfc7232#section-3.3
139
            return $etag !== null && \in_array($etag, $this->getETags($request), true);
140
        }
141
142
        if ($request->hasHeader('If-Modified-Since')) {
143
            $header = $request->getHeaderLine('If-Modified-Since');
144
            return $lastModified !== null && @strtotime($header) >= $lastModified;
145
        }
146
147
        return false;
148
    }
149
150
    /**
151
     * Generates an ETag from the given seed string.
152
     * @param string $seed Seed for the ETag
153
     * @return string the generated ETag
154
     */
155
    private function generateEtag(string $seed): string
156
    {
157
        $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"';
158
        return $this->weakEtag ? 'W/' . $etag : $etag;
159
    }
160
161
    /**
162
     * Gets the Etags.
163
     *
164
     * @param ServerRequestInterface $request
165
     * @return array The entity tags
166
     */
167
    private function getETags(ServerRequestInterface $request): array
168
    {
169
        if ($request->hasHeader('If-None-Match')) {
170
            $header = $request->getHeaderLine('If-None-Match');
171
            $header = \str_replace('-gzip', '', $header);
172
            return \preg_split('/[\s,]+/', $header, -1, PREG_SPLIT_NO_EMPTY) ?: [];
173
        }
174
175
        return [];
176
    }
177
178
    public function setLastModified(callable $lastModified): void
179
    {
180
        $this->lastModified = $lastModified;
181
    }
182
183
    public function setEtagSeed(callable $etagSeed): void
184
    {
185
        $this->etagSeed = $etagSeed;
186
    }
187
188
    public function setWeakTag(bool $weakTag): void
189
    {
190
        $this->weakEtag = $weakTag;
191
    }
192
193
    public function setParams($params): void
194
    {
195
        $this->params = $params;
196
    }
197
198
    public function setCacheControlHeader(?string $header): void
199
    {
200
        $this->cacheControlHeader = $header;
201
    }
202
}
203