Passed
Pull Request — master (#199)
by Rustam
01:53
created

HttpCache::setEnabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
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 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(
99
        ResponseFactoryInterface $responseFactory,
100
        SessionInterface $session,
101
        LoggerInterface $logger
102
    ) {
103
        $this->responseFactory = $responseFactory;
104
        $this->session = $session;
105
        $this->logger = $logger;
106
    }
107
108
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
109
    {
110
        if (!$this->enabled) {
111
            return $handler->handle($request);
112
        }
113
114
        $method = $request->getMethod();
115
        if (
116
            !in_array($method, [Method::GET, Method::HEAD])
117
            || $this->lastModified === null
118
            && $this->etagSeed === null
119
        ) {
120
            return $handler->handle($request);
121
        }
122
123
        $lastModified = $etag = null;
124
        if ($this->lastModified !== null) {
125
            $lastModified = call_user_func($this->lastModified, $request, $this->params);
126
        }
127
        if ($this->etagSeed !== null) {
128
            $seed = call_user_func($this->etagSeed, $request, $this->params);
129
            if ($seed !== null) {
130
                $etag = $this->generateEtag($seed);
131
            }
132
        }
133
134
        $this->sendCacheControlHeader($request);
135
136
        $response = $handler->handle($request);
137
        if ($this->cacheControlHeader !== null) {
138
            $response = $response->withHeader('Cache-Control', $this->cacheControlHeader);
139
        }
140
        if ($etag !== null) {
141
            $response = $response->withHeader('Etag', $etag);
142
        }
143
144
        $cacheValid = $this->validateCache($request, $lastModified, $etag);
145
        // https://tools.ietf.org/html/rfc7232#section-4.1
146
        if ($lastModified !== null && (!$cacheValid || ($cacheValid && $etag === null))) {
147
            $response = $response->withHeader(
148
                'Last-Modified',
149
                gmdate('D, d M Y H:i:s', $lastModified) . ' GMT'
150
            );
151
        }
152
        if ($cacheValid) {
153
            $response = $this->responseFactory->createResponse(304);
154
            $response->getBody()->write('Not Modified');
155
            return $response;
156
        }
157
        return $response;
158
    }
159
160
    /**
161
     * Validates if the HTTP cache contains valid content.
162
     * If both Last-Modified and ETag are null, returns false.
163
     * @param ServerRequestInterface $request
164
     * @param int $lastModified the calculated Last-Modified value in terms of a UNIX timestamp.
165
     * If null, the Last-Modified header will not be validated.
166
     * @param string $etag the calculated ETag value. If null, the ETag header will not be validated.
167
     * @return bool whether the HTTP cache is still valid.
168
     */
169
    private function validateCache(ServerRequestInterface $request, $lastModified, $etag)
170
    {
171
        if ($request->hasHeader('If-None-Match')) {
172
            // HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
173
            // http://tools.ietf.org/html/rfc7232#section-3.3
174
            return $etag !== null && in_array($etag, $this->getETags($request), true);
175
        } elseif ($request->hasHeader('If-Modified-Since')) {
176
            $header = reset($request->getHeader('If-Modified-Since'));
177
            return $lastModified !== null && @strtotime($header) >= $lastModified;
178
        }
179
180
        return false;
181
    }
182
183
    /**
184
     * Sends the cache control header to the client.
185
     * @param ServerRequestInterface $request
186
     * @see cacheControlHeader
187
     */
188
    private function sendCacheControlHeader(ServerRequestInterface $request): void
189
    {
190
        if ($this->sessionCacheLimiter !== null) {
191
            if ($this->sessionCacheLimiter === '' && !headers_sent() && $this->session->isActive()) {
192
                header_remove('Expires');
193
                header_remove('Cache-Control');
194
                header_remove('Last-Modified');
195
                header_remove('Pragma');
196
            }
197
198
            $this->setCacheLimiter();
199
        }
200
    }
201
202
    /**
203
     * Generates an ETag from the given seed string.
204
     * @param string $seed Seed for the ETag
205
     * @return string the generated ETag
206
     */
207
    private function generateEtag($seed): string
208
    {
209
        $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"';
210
        return $this->weakEtag ? 'W/' . $etag : $etag;
211
    }
212
213
    /**
214
     * Gets the Etags.
215
     *
216
     * @param ServerRequestInterface $request
217
     * @return array The entity tags
218
     */
219
    private function getETags(ServerRequestInterface $request): array
220
    {
221
        if ($request->hasHeader('If-None-Match')) {
222
            $header = str_replace('-gzip', '', reset($request->getHeader('If-None-Match')));
223
            return preg_split('/[\s,]+/', $header, -1, PREG_SPLIT_NO_EMPTY) ?: [];
224
        }
225
226
        return [];
227
    }
228
229
    private function setCacheLimiter()
230
    {
231
        if ($this->session->isActive()) {
232
            if (isset($_SESSION)) {
233
                $this->sessionData = $_SESSION;
234
            }
235
            $this->session->close();
236
        }
237
238
        session_cache_limiter($this->sessionCacheLimiter);
239
240
        if (null !== $this->sessionData) {
241
            $this->session->open();
242
243
            $_SESSION = $this->sessionData;
244
            $this->sessionData = null;
245
        }
246
    }
247
248
    public function setLastModified(callable $lastModified): void
249
    {
250
        $this->lastModified = $lastModified;
251
    }
252
253
    public function setEtagSeed(callable $etagSeed): void
254
    {
255
        $this->etagSeed = $etagSeed;
256
    }
257
258
    public function setWeakTag(bool $weakTag): void
259
    {
260
        $this->weakEtag = $weakTag;
261
    }
262
263
    public function setParams($params): void
264
    {
265
        $this->params = $params;
266
    }
267
268
    public function setCacheControlHeader(?string $header): void
269
    {
270
        $this->cacheControlHeader = $header;
271
    }
272
273
    public function setSessionCacheLimiter(?string $cacheLimiter): void
274
    {
275
        $this->sessionCacheLimiter = $cacheLimiter;
276
    }
277
278
    public function setEnabled(bool $enabled): void
279
    {
280
        $this->enabled = $enabled;
281
    }
282
}
283