Passed
Pull Request — master (#199)
by Rustam
15:14
created

HttpCache::validateCache()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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