Passed
Pull Request — master (#199)
by Rustam
01:57
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\Router\Method;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Router\Method was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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