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

HttpCache::validateCache()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 6
c 2
b 0
f 0
nc 5
nop 3
dl 0
loc 12
rs 9.6111
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 Psr\Log\LoggerInterface;
10
use Yiisoft\Router\Method;
11
use Yiisoft\Yii\Web\Session\SessionInterface;
12
use function in_array;
13
use function preg_split;
14
use function reset;
15
use function str_replace;
16
17
/**
18
 * HttpCache implements client-side caching by utilizing the `Last-Modified` and `ETag` HTTP headers.
19
 */
20
final class HttpCache implements MiddlewareInterface
21
{
22
    private const DEFAULT_HEADER = 'public, max-age=3600';
23
    /**
24
     * @internal Frozen session data
25
     */
26
    private ?array $sessionData;
27
28
    /**
29
     * @var callable a PHP callback that returns the UNIX timestamp of the last modification time.
30
     * The callback's signature should be:
31
     *
32
     * ```php
33
     * function ($request, $params)
34
     * ```
35
     *
36
     * where `$request` is the [[ServerRequestInterface]] object that this filter is currently handling;
37
     * `$params` takes the value of [[params]]. The callback should return a UNIX timestamp.
38
     *
39
     * @see http://tools.ietf.org/html/rfc7232#section-2.2
40
     */
41
    private $lastModified;
42
43
    /**
44
     * @var callable a PHP callback that generates the ETag seed string.
45
     * The callback's signature should be:
46
     *
47
     * ```php
48
     * function ($request, $params)
49
     * ```
50
     *
51
     * where `$request` is the [[ServerRequestInterface]] object that this filter is currently handling;
52
     * `$params` takes the value of [[params]]. The callback should return a string serving
53
     * as the seed for generating an ETag.
54
     */
55
    private $etagSeed;
56
57
    /**
58
     * @var bool whether to generate weak ETags.
59
     *
60
     * Weak ETags should be used if the content should be considered semantically equivalent, but not byte-equal.
61
     *
62
     * @see http://tools.ietf.org/html/rfc7232#section-2.3
63
     */
64
    private bool $weakEtag = false;
65
66
    /**
67
     * @var mixed additional parameters that should be passed to the [[lastModified]] and [[etagSeed]] callbacks.
68
     */
69
    private $params;
70
71
    /**
72
     * @var string the value of the `Cache-Control` HTTP header. If null, the header will not be sent.
73
     * @see http://tools.ietf.org/html/rfc2616#section-14.9
74
     */
75
    private ?string $cacheControlHeader = self::DEFAULT_HEADER;
76
77
    /**
78
     * @var string the name of the cache limiter to be set when [session_cache_limiter()](https://secure.php.net/manual/en/function.session-cache-limiter.php)
79
     * is called. The default value is an empty string, meaning turning off automatic sending of cache headers entirely.
80
     * You may set this property to be `public`, `private`, `private_no_expire`, and `nocache`.
81
     * Please refer to [session_cache_limiter()](https://secure.php.net/manual/en/function.session-cache-limiter.php)
82
     * for detailed explanation of these values.
83
     *
84
     * If this property is `null`, then `session_cache_limiter()` will not be called. As a result,
85
     * PHP will send headers according to the `session.cache_limiter` PHP ini setting.
86
     */
87
    private ?string $sessionCacheLimiter = '';
88
89
    /**
90
     * @var bool a value indicating whether this filter should be enabled.
91
     */
92
    private bool $enabled = true;
93
94
    private ResponseFactoryInterface $responseFactory;
95
    private SessionInterface $session;
96
    private LoggerInterface $logger;
97
98
    public function __construct(ResponseFactoryInterface $responseFactory, SessionInterface $session, LoggerInterface $logger)
99
    {
100
        $this->responseFactory = $responseFactory;
101
        $this->session = $session;
102
        $this->logger = $logger;
103
    }
104
105
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
106
    {
107
        if (!$this->enabled) {
108
            return $handler->handle($request);
109
        }
110
111
        $method = $request->getMethod();
112
        if (!in_array($method, [Method::GET, Method::HEAD]) || $this->lastModified === null && $this->etagSeed === null) {
113
            return $handler->handle($request);
114
        }
115
116
        $lastModified = $etag = null;
117
        if ($this->lastModified !== null) {
118
            $lastModified = call_user_func($this->lastModified, $request, $this->params);
119
        }
120
        if ($this->etagSeed !== null) {
121
            $seed = call_user_func($this->etagSeed, $request, $this->params);
122
            if ($seed !== null) {
123
                $etag = $this->generateEtag($seed);
124
            }
125
        }
126
127
        $this->sendCacheControlHeader($request);
128
129
        $response = $handler->handle($request);
130
        if ($this->cacheControlHeader !== null) {
131
            $response = $response->withHeader('Cache-Control', $this->cacheControlHeader);
132
        }
133
        if ($etag !== null) {
134
            $response = $response->withHeader('Etag', $etag);
135
        }
136
137
        $cacheValid = $this->validateCache($request, $lastModified, $etag);
138
        // https://tools.ietf.org/html/rfc7232#section-4.1
139
        if ($lastModified !== null && (!$cacheValid || ($cacheValid && $etag === null))) {
140
            $response = $response->withHeader('Last-Modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
141
        }
142
        if ($cacheValid) {
143
            $response = $this->responseFactory->createResponse(304);
144
            $response->getBody()->write('Not Modified');
145
            return $response;
146
        }
147
        return $response;
148
    }
149
150
    /**
151
     * Validates if the HTTP cache contains valid content.
152
     * If both Last-Modified and ETag are null, returns false.
153
     * @param ServerRequestInterface $request
154
     * @param int $lastModified the calculated Last-Modified value in terms of a UNIX timestamp.
155
     * If null, the Last-Modified header will not be validated.
156
     * @param string $etag the calculated ETag value. If null, the ETag header will not be validated.
157
     * @return bool whether the HTTP cache is still valid.
158
     */
159
    private function validateCache(ServerRequestInterface $request, $lastModified, $etag)
160
    {
161
        if ($request->hasHeader('If-None-Match')) {
162
            // HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
163
            // http://tools.ietf.org/html/rfc7232#section-3.3
164
            return $etag !== null && in_array($etag, $this->getETags($request), true);
165
        } elseif ($request->hasHeader('If-Modified-Since')) {
166
            $header = reset($request->getHeader('If-Modified-Since'));
167
            return $lastModified !== null && @strtotime($header) >= $lastModified;
168
        }
169
170
        return false;
171
    }
172
173
    /**
174
     * Sends the cache control header to the client.
175
     * @param ServerRequestInterface $request
176
     * @see cacheControlHeader
177
     */
178
    private function sendCacheControlHeader(ServerRequestInterface $request): void
179
    {
180
        if ($this->sessionCacheLimiter !== null) {
181
            if ($this->sessionCacheLimiter === '' && !headers_sent() && $this->session->isActive()) {
182
                header_remove('Expires');
183
                header_remove('Cache-Control');
184
                header_remove('Last-Modified');
185
                header_remove('Pragma');
186
            }
187
188
            $this->setCacheLimiter();
189
        }
190
    }
191
192
    /**
193
     * Generates an ETag from the given seed string.
194
     * @param string $seed Seed for the ETag
195
     * @return string the generated ETag
196
     */
197
    private function generateEtag($seed): string
198
    {
199
        $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"';
200
        return $this->weakEtag ? 'W/' . $etag : $etag;
201
    }
202
203
    /**
204
     * Gets the Etags.
205
     *
206
     * @param ServerRequestInterface $request
207
     * @return array The entity tags
208
     */
209
    private function getETags(ServerRequestInterface $request): array
210
    {
211
        if ($request->hasHeader('If-None-Match')) {
212
            $header = reset($request->getHeader('If-None-Match'));
213
            return preg_split('/[\s,]+/', str_replace('-gzip', '', $header), -1, PREG_SPLIT_NO_EMPTY) ?? [];
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_split('/[\s,...IT_NO_EMPTY) ?? array() could return the type false which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
214
        }
215
216
        return [];
217
    }
218
219
    private function setCacheLimiter()
220
    {
221
        if ($this->session->isActive()) {
222
            if (isset($_SESSION)) {
223
                $this->sessionData = $_SESSION;
224
            }
225
            $this->session->close();
226
        }
227
228
        session_cache_limiter($this->sessionCacheLimiter);
229
230
        if (null !== $this->sessionData) {
231
            $this->session->open();
232
233
            $_SESSION = $this->sessionData;
234
            $this->sessionData = null;
235
        }
236
    }
237
238
    public function setLastModified(callable $lastModified): void
239
    {
240
        $this->lastModified = $lastModified;
241
    }
242
243
    public function setEtagSeed(callable $etagSeed): void
244
    {
245
        $this->etagSeed = $etagSeed;
246
    }
247
248
    public function setWeakTag(bool $weakTag): void
249
    {
250
        $this->weakEtag = $weakTag;
251
    }
252
253
    public function setParams($params): void
254
    {
255
        $this->params = $params;
256
    }
257
258
    public function setCacheControlHeader(?string $header): void
259
    {
260
        $this->cacheControlHeader = $header;
261
    }
262
263
    public function setSessionCacheLimiter(?string $cacheLimiter): void
264
    {
265
        $this->sessionCacheLimiter = $cacheLimiter;
266
    }
267
268
    public function setEnabled(bool $enabled): void
269
    {
270
        $this->enabled = $enabled;
271
    }
272
}
273