Passed
Pull Request — master (#199)
by Alexander
03:28
created

HttpCache::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 4
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->getBody()->write('Not Modified');
100
            return $response;
101
        }
102
103
        $response = $handler->handle($request);
104
        if ($this->cacheControlHeader !== null) {
105
            $response = $response->withHeader('Cache-Control', $this->cacheControlHeader);
106
        }
107
        if ($etag !== null) {
108
            $response = $response->withHeader('Etag', $etag);
109
        }
110
111
        // https://tools.ietf.org/html/rfc7232#section-4.1
112
        if ($lastModified !== null && (!$cacheValid || ($cacheValid && $etag === null))) {
113
            $response = $response->withHeader(
114
                'Last-Modified',
115
                gmdate('D, d M Y H:i:s', $lastModified) . ' GMT'
116
            );
117
        }
118
119
        return $response;
120
    }
121
122
    /**
123
     * Validates if the HTTP cache contains valid content.
124
     * If both Last-Modified and ETag are null, returns false.
125
     * @param ServerRequestInterface $request
126
     * @param int|null $lastModified the calculated Last-Modified value in terms of a UNIX timestamp.
127
     * If null, the Last-Modified header will not be validated.
128
     * @param string|null $etag the calculated ETag value. If null, the ETag header will not be validated.
129
     * @return bool whether the HTTP cache is still valid.
130
     */
131
    private function validateCache(ServerRequestInterface $request, ?int $lastModified, ?string $etag): bool
132
    {
133
        if ($request->hasHeader('If-None-Match')) {
134
            // HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
135
            // http://tools.ietf.org/html/rfc7232#section-3.3
136
            return $etag !== null && \in_array($etag, $this->getETags($request), true);
137
        }
138
139
        if ($request->hasHeader('If-Modified-Since')) {
140
            $header = $request->getHeaderLine('If-Modified-Since');
141
            return $lastModified !== null && @strtotime($header) >= $lastModified;
142
        }
143
144
        return false;
145
    }
146
147
    /**
148
     * Generates an ETag from the given seed string.
149
     * @param string $seed Seed for the ETag
150
     * @return string the generated ETag
151
     */
152
    private function generateEtag(string $seed): string
153
    {
154
        $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"';
155
        return $this->weakEtag ? 'W/' . $etag : $etag;
156
    }
157
158
    /**
159
     * Gets the Etags.
160
     *
161
     * @param ServerRequestInterface $request
162
     * @return array The entity tags
163
     */
164
    private function getETags(ServerRequestInterface $request): array
165
    {
166
        if ($request->hasHeader('If-None-Match')) {
167
            $header = $request->getHeaderLine('If-None-Match');
168
            $header = \str_replace('-gzip', '', $header);
169
            return \preg_split('/[\s,]+/', $header, -1, PREG_SPLIT_NO_EMPTY) ?: [];
170
        }
171
172
        return [];
173
    }
174
175
    public function setLastModified(callable $lastModified): void
176
    {
177
        $this->lastModified = $lastModified;
178
    }
179
180
    public function setEtagSeed(callable $etagSeed): void
181
    {
182
        $this->etagSeed = $etagSeed;
183
    }
184
185
    public function setWeakTag(bool $weakTag): void
186
    {
187
        $this->weakEtag = $weakTag;
188
    }
189
190
    public function setParams($params): void
191
    {
192
        $this->params = $params;
193
    }
194
195
    public function setCacheControlHeader(?string $header): void
196
    {
197
        $this->cacheControlHeader = $header;
198
    }
199
}
200