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

HttpCache::setCacheLimiter()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 6
nop 0
dl 0
loc 18
rs 9.9332
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
13
/**
14
 * HttpCache implements client-side caching by utilizing the `Last-Modified` and `ETag` HTTP headers.
15
 */
16
final class HttpCache implements MiddlewareInterface
17
{
18
    private const DEFAULT_HEADER = 'public, max-age=3600';
19
    /**
20
     * @var callable a PHP callback that returns the UNIX timestamp of the last modification time.
21
     * The callback's signature should be:
22
     *
23
     * ```php
24
     * function ($action, $params)
25
     * ```
26
     *
27
     * where `$action` is the [[Action]] object that this filter is currently handling;
28
     * `$params` takes the value of [[params]]. The callback should return a UNIX timestamp.
29
     *
30
     * @see http://tools.ietf.org/html/rfc7232#section-2.2
31
     */
32
    private $lastModified;
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 ($action, $params)
39
     * ```
40
     *
41
     * where `$action` is the [[Action]] object that this filter is currently handling;
42
     * `$params` takes the value of [[params]]. The callback should return a string serving
43
     * as the seed for generating an ETag.
44
     */
45
    private $etagSeed;
46
    /**
47
     * @var bool whether to generate weak ETags.
48
     *
49
     * Weak ETags should be used if the content should be considered semantically equivalent, but not byte-equal.
50
     *
51
     * @see http://tools.ietf.org/html/rfc7232#section-2.3
52
     */
53
    private $weakEtag = false;
54
    /**
55
     * @var mixed additional parameters that should be passed to the [[lastModified]] and [[etagSeed]] callbacks.
56
     */
57
    private $params;
58
    /**
59
     * @var string the value of the `Cache-Control` HTTP header. If null, the header will not be sent.
60
     * @see http://tools.ietf.org/html/rfc2616#section-14.9
61
     */
62
    private $cacheControlHeader = self::DEFAULT_HEADER;
63
    /**
64
     * @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)
65
     * is called. The default value is an empty string, meaning turning off automatic sending of cache headers entirely.
66
     * You may set this property to be `public`, `private`, `private_no_expire`, and `nocache`.
67
     * Please refer to [session_cache_limiter()](https://secure.php.net/manual/en/function.session-cache-limiter.php)
68
     * for detailed explanation of these values.
69
     *
70
     * If this property is `null`, then `session_cache_limiter()` will not be called. As a result,
71
     * PHP will send headers according to the `session.cache_limiter` PHP ini setting.
72
     */
73
    private string $sessionCacheLimiter = '';
74
    /**
75
     * @var bool a value indicating whether this filter should be enabled.
76
     */
77
    private bool $enabled = true;
78
79
    private ResponseFactoryInterface $responseFactory;
80
    private SessionInterface $session;
81
    private LoggerInterface $logger;
82
83
    public function __construct(ResponseFactoryInterface $responseFactory, SessionInterface $session, LoggerInterface $logger)
84
    {
85
        $this->responseFactory = $responseFactory;
86
        $this->session = $session;
87
        $this->logger = $logger;
88
    }
89
90
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
91
    {
92
        if (!$this->enabled) {
93
            return $handler->handle($request);
94
        }
95
96
        $method = $request->getMethod();
97
        if (!\in_array($method, [Method::GET, Method::HEAD]) || $this->lastModified === null && $this->etagSeed === null) {
98
            return $handler->handle($request);
99
        }
100
101
        $lastModified = $etag = null;
102
        if ($this->lastModified !== null) {
103
            $lastModified = call_user_func($this->lastModified, $request, $this->params);
104
        }
105
        if ($this->etagSeed !== null) {
106
            $seed = call_user_func($this->etagSeed, $request, $this->params);
107
            if ($seed !== null) {
108
                $etag = $this->generateEtag($seed);
109
            }
110
        }
111
112
        $this->sendCacheControlHeader($request);
113
114
        $response = $handler->handle($request);
115
        if ($this->cacheControlHeader !== null) {
116
            $response = $response->withHeader('Cache-Control', $this->cacheControlHeader);
117
        }
118
        if ($etag !== null) {
119
            $response = $response->withHeader('Etag', $etag);
120
        }
121
122
        $cacheValid = $this->validateCache($request, $lastModified, $etag);
123
        // https://tools.ietf.org/html/rfc7232#section-4.1
124
        if ($lastModified !== null && (!$cacheValid || ($cacheValid && $etag === null))) {
125
            $response = $response->withHeader('Last-Modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
126
        }
127
        if ($cacheValid) {
128
            $response = $this->responseFactory->createResponse(304);
129
            $response->getBody()->write('Not Modified');
130
            return $response;
131
        }
132
        return $response;
133
    }
134
135
    /**
136
     * Validates if the HTTP cache contains valid content.
137
     * If both Last-Modified and ETag are null, returns false.
138
     * @param ServerRequestInterface $request
139
     * @param int $lastModified the calculated Last-Modified value in terms of a UNIX timestamp.
140
     * If null, the Last-Modified header will not be validated.
141
     * @param string $etag the calculated ETag value. If null, the ETag header will not be validated.
142
     * @return bool whether the HTTP cache is still valid.
143
     */
144
    private function validateCache(ServerRequestInterface $request, $lastModified, $etag)
145
    {
146
        if ($request->hasHeader('If-None-Match')) {
147
            // HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
148
            // http://tools.ietf.org/html/rfc7232#section-3.3
149
            return $etag !== null && in_array($etag, $this->getETags($request), true);
150
        } elseif ($request->hasHeader('If-Modified-Since')) {
151
            return $lastModified !== null && @strtotime($request->getHeader('If-Modified-Since')) >= $lastModified;
0 ignored issues
show
Bug introduced by
$request->getHeader('If-Modified-Since') of type string[] is incompatible with the type string expected by parameter $time of strtotime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

151
            return $lastModified !== null && @strtotime(/** @scrutinizer ignore-type */ $request->getHeader('If-Modified-Since')) >= $lastModified;
Loading history...
152
        }
153
154
        return false;
155
    }
156
157
    /**
158
     * Sends the cache control header to the client.
159
     * @param ServerRequestInterface $request
160
     * @see cacheControlHeader
161
     */
162
    private function sendCacheControlHeader(ServerRequestInterface $request): void
163
    {
164
        if ($this->sessionCacheLimiter !== null) {
165
            if ($this->sessionCacheLimiter === '' && !headers_sent() && $this->session->isActive()) {
166
                header_remove('Expires');
167
                header_remove('Cache-Control');
168
                header_remove('Last-Modified');
169
                header_remove('Pragma');
170
            }
171
172
            $this->setCacheLimiter();
173
        }
174
    }
175
176
    /**
177
     * Generates an ETag from the given seed string.
178
     * @param string $seed Seed for the ETag
179
     * @return string the generated ETag
180
     */
181
    private function generateEtag($seed): string
182
    {
183
        $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"';
184
        return $this->weakEtag ? 'W/' . $etag : $etag;
185
    }
186
187
    /**
188
     * Gets the Etags.
189
     *
190
     * @param ServerRequestInterface $request
191
     * @return array The entity tags
192
     */
193
    private function getETags(ServerRequestInterface $request): array
194
    {
195
        if ($request->hasHeader('If-None-Match')) {
196
            return \preg_split('/[\s,]+/', \str_replace('-gzip', '', $request->getHeader('If-None-Match')), -1, PREG_SPLIT_NO_EMPTY);
0 ignored issues
show
Bug introduced by
str_replace('-gzip', '',...eader('If-None-Match')) of type string[] is incompatible with the type string expected by parameter $subject of preg_split(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

196
            return \preg_split('/[\s,]+/', /** @scrutinizer ignore-type */ \str_replace('-gzip', '', $request->getHeader('If-None-Match')), -1, PREG_SPLIT_NO_EMPTY);
Loading history...
Bug Best Practice introduced by
The expression return preg_split('/[\s,...re\PREG_SPLIT_NO_EMPTY) 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...
197
        }
198
199
        return [];
200
    }
201
202
    private function setCacheLimiter()
203
    {
204
        $sessionData = null;
205
        if ($this->session->isActive()) {
206
            if (isset($_SESSION)) {
207
                $sessionData = $_SESSION;
208
            }
209
            $this->session->close();
210
        }
211
212
        session_cache_limiter($this->sessionCacheLimiter);
213
214
        if (null !== $sessionData) {
0 ignored issues
show
introduced by
The condition null !== $sessionData is always false.
Loading history...
215
216
            $this->session->open();
217
218
            $_SESSION = $sessionData;
219
            $sessionData = null;
220
        }
221
    }
222
}
223