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

HttpCache::setParams()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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