Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
 
12
namespace Symfony\Component\HttpKernel\HttpCache;
13
 
14
use Symfony\Component\HttpFoundation\Response;
15
 
16
/**
17
 * ResponseCacheStrategy knows how to compute the Response cache HTTP header
18
 * based on the different response cache headers.
19
 *
20
 * This implementation changes the main response TTL to the smallest TTL received
21
 * or force validation if one of the surrogates has validation cache strategy.
22
 *
23
 * @author Fabien Potencier <fabien@symfony.com>
24
 */
25
class ResponseCacheStrategy implements ResponseCacheStrategyInterface
26
{
27
    /**
28
     * Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
29
     */
30
    private const OVERRIDE_DIRECTIVES = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
31
 
32
    /**
33
     * Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
34
     */
35
    private const INHERIT_DIRECTIVES = ['public', 'immutable'];
36
 
37
    private int $embeddedResponses = 0;
38
    private bool $isNotCacheableResponseEmbedded = false;
39
    private int $age = 0;
40
    private \DateTimeInterface|null|false $lastModified = null;
41
    private array $flagDirectives = [
42
        'no-cache' => null,
43
        'no-store' => null,
44
        'no-transform' => null,
45
        'must-revalidate' => null,
46
        'proxy-revalidate' => null,
47
        'public' => null,
48
        'private' => null,
49
        'immutable' => null,
50
    ];
51
    private array $ageDirectives = [
52
        'max-age' => null,
53
        's-maxage' => null,
54
        'expires' => null,
55
    ];
56
 
57
    public function add(Response $response)
58
    {
59
        ++$this->embeddedResponses;
60
 
61
        foreach (self::OVERRIDE_DIRECTIVES as $directive) {
62
            if ($response->headers->hasCacheControlDirective($directive)) {
63
                $this->flagDirectives[$directive] = true;
64
            }
65
        }
66
 
67
        foreach (self::INHERIT_DIRECTIVES as $directive) {
68
            if (false !== $this->flagDirectives[$directive]) {
69
                $this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
70
            }
71
        }
72
 
73
        $age = $response->getAge();
74
        $this->age = max($this->age, $age);
75
 
76
        if ($this->willMakeFinalResponseUncacheable($response)) {
77
            $this->isNotCacheableResponseEmbedded = true;
78
 
79
            return;
80
        }
81
 
82
        $isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public');
83
        $maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
84
        $this->storeRelativeAgeDirective('max-age', $maxAge, $age, $isHeuristicallyCacheable);
85
        $sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
86
        $this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge, $age, $isHeuristicallyCacheable);
87
 
88
        $expires = $response->getExpires();
89
        $expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
90
        $this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable);
91
 
92
        if (false !== $this->lastModified) {
93
            $lastModified = $response->getLastModified();
94
            $this->lastModified = $lastModified ? max($this->lastModified, $lastModified) : false;
95
        }
96
    }
97
 
98
    public function update(Response $response)
99
    {
100
        // if we have no embedded Response, do nothing
101
        if (0 === $this->embeddedResponses) {
102
            return;
103
        }
104
 
105
        // Remove Etag since it cannot be merged from embedded responses.
106
        $response->setEtag(null);
107
 
108
        $this->add($response);
109
 
110
        $response->headers->set('Age', $this->age);
111
 
112
        if ($this->isNotCacheableResponseEmbedded) {
113
            $response->setLastModified(null);
114
 
115
            if ($this->flagDirectives['no-store']) {
116
                $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
117
            } else {
118
                $response->headers->set('Cache-Control', 'no-cache, must-revalidate');
119
            }
120
 
121
            return;
122
        }
123
 
124
        $response->setLastModified($this->lastModified ?: null);
125
 
126
        $flags = array_filter($this->flagDirectives);
127
 
128
        if (isset($flags['must-revalidate'])) {
129
            $flags['no-cache'] = true;
130
        }
131
 
132
        $response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
133
 
134
        $maxAge = null;
135
 
136
        if (is_numeric($this->ageDirectives['max-age'])) {
137
            $maxAge = $this->ageDirectives['max-age'] + $this->age;
138
            $response->headers->addCacheControlDirective('max-age', $maxAge);
139
        }
140
 
141
        if (is_numeric($this->ageDirectives['s-maxage'])) {
142
            $sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
143
 
144
            if ($maxAge !== $sMaxage) {
145
                $response->headers->addCacheControlDirective('s-maxage', $sMaxage);
146
            }
147
        }
148
 
149
        if (is_numeric($this->ageDirectives['expires'])) {
150
            $date = clone $response->getDate();
151
            $date->modify('+'.($this->ageDirectives['expires'] + $this->age).' seconds');
152
            $response->setExpires($date);
153
        }
154
    }
155
 
156
    /**
157
     * RFC2616, Section 13.4.
158
     *
159
     * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
160
     */
161
    private function willMakeFinalResponseUncacheable(Response $response): bool
162
    {
163
        // RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
164
        // MAY be stored by a cache […] unless a cache-control directive prohibits caching.
165
        if ($response->headers->hasCacheControlDirective('no-cache')
166
            || $response->headers->hasCacheControlDirective('no-store')
167
        ) {
168
            return true;
169
        }
170
 
171
        // Etag headers cannot be merged, they render the response uncacheable
172
        // by default (except if the response also has max-age etc.).
173
        if (null === $response->getEtag() && \in_array($response->getStatusCode(), [200, 203, 300, 301, 410])) {
174
            return false;
175
        }
176
 
177
        // RFC2616: A response received with any other status code (e.g. status codes 302 and 307)
178
        // MUST NOT be returned in a reply to a subsequent request unless there are
179
        // cache-control directives or another header(s) that explicitly allow it.
180
        $cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private'];
181
        foreach ($cacheControl as $key) {
182
            if ($response->headers->hasCacheControlDirective($key)) {
183
                return false;
184
            }
185
        }
186
 
187
        if ($response->headers->has('Expires')) {
188
            return false;
189
        }
190
 
191
        return true;
192
    }
193
 
194
    /**
195
     * Store lowest max-age/s-maxage/expires for the final response.
196
     *
197
     * The response might have been stored in cache a while ago. To keep things comparable,
198
     * we have to subtract the age so that the value is normalized for an age of 0.
199
     *
200
     * If the value is lower than the currently stored value, we update the value, to keep a rolling
201
     * minimal value of each instruction.
202
     *
203
     * If the value is NULL and the isHeuristicallyCacheable parameter is false, the directive will
204
     * not be set on the final response. In this case, not all responses had the directive set and no
205
     * value can be found that satisfies the requirements of all responses. The directive will be dropped
206
     * from the final response.
207
     *
208
     * If the isHeuristicallyCacheable parameter is true, however, the current response has been marked
209
     * as cacheable in a public (shared) cache, but did not provide an explicit lifetime that would serve
210
     * as an upper bound. In this case, we can proceed and possibly keep the directive on the final response.
211
     */
212
    private function storeRelativeAgeDirective(string $directive, ?int $value, int $age, bool $isHeuristicallyCacheable)
213
    {
214
        if (null === $value) {
215
            if ($isHeuristicallyCacheable) {
216
                /*
217
                 * See https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
218
                 * This particular response does not require maximum lifetime; heuristics might be applied.
219
                 * Other responses, however, might have more stringent requirements on maximum lifetime.
220
                 * So, return early here so that the final response can have the more limiting value set.
221
                 */
222
                return;
223
            }
224
            $this->ageDirectives[$directive] = false;
225
        }
226
 
227
        if (false !== $this->ageDirectives[$directive]) {
228
            $value -= $age;
229
            $this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value;
230
        }
231
    }
232
}