Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/CachingHttpClient.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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\HttpClient;
13
14 use Symfony\Component\HttpClient\Caching\Freshness;
15 use Symfony\Component\HttpClient\Chunk\ErrorChunk;
16 use Symfony\Component\HttpClient\Exception\ChunkCacheItemNotFoundException;
17 use Symfony\Component\HttpClient\Response\AsyncContext;
18 use Symfony\Component\HttpClient\Response\AsyncResponse;
19 use Symfony\Component\HttpClient\Response\MockResponse;
20 use Symfony\Component\HttpClient\Response\ResponseStream;
21 use Symfony\Component\HttpFoundation\Request;
22 use Symfony\Component\HttpKernel\HttpCache\HttpCache;
23 use Symfony\Component\HttpKernel\HttpCache\StoreInterface;
24 use Symfony\Component\HttpKernel\HttpClientKernel;
25 use Symfony\Contracts\Cache\ItemInterface;
26 use Symfony\Contracts\Cache\TagAwareCacheInterface;
27 use Symfony\Contracts\HttpClient\ChunkInterface;
28 use Symfony\Contracts\HttpClient\HttpClientInterface;
29 use Symfony\Contracts\HttpClient\ResponseInterface;
30 use Symfony\Contracts\HttpClient\ResponseStreamInterface;
31 use Symfony\Contracts\Service\ResetInterface;
32
33 /**
34 * Adds caching on top of an HTTP client (per RFC 9111).
35 *
36 * Known omissions / partially supported features per RFC 9111:
37 * 1. Range requests:
38 * - All range requests ("partial content") are passed through and never cached.
39 * 2. stale-while-revalidate:
40 * - There's no actual "background revalidation" for stale responses, they will
41 * always be revalidated.
42 * 3. min-fresh, max-stale:
43 * - These request directives are not parsed; the client ignores them.
44 *
45 * @see https://www.rfc-editor.org/rfc/rfc9111
46 */
47 class CachingHttpClient implements HttpClientInterface, ResetInterface
48 {
49 use AsyncDecoratorTrait {
50 stream as asyncStream;
51 AsyncDecoratorTrait::withOptions insteadof HttpClientTrait;
52 }
53 use HttpClientTrait;
54
55 /**
56 * The status codes that are cacheable by default.
57 */
58 private const DEFAULT_CACHEABLE_STATUS_CODES = [200, 203, 204, 300, 301, 308, 404, 405, 410, 414, 501];
59 /**
60 * The HTTP methods that are always cacheable.
61 */
62 private const CACHEABLE_METHODS = ['GET', 'HEAD'];
63 /**
64 * The HTTP methods that are considered safe per RFC 9110.
65 */
66 private const SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS', 'TRACE'];
67 /**
68 * Headers that influence the response and may affect caching behavior.
69 */
70 private const RESPONSE_INFLUENCING_HEADERS = [
71 'accept' => true,
72 'accept-charset' => true,
73 'accept-encoding' => true,
74 'accept-language' => true,
75 'authorization' => true,
76 'cookie' => true,
77 'expect' => true,
78 'host' => true,
79 'user-agent' => true,
80 ];
81 /**
82 * Headers that MUST NOT be stored as per RFC 9111 Section 3.1.
83 */
84 private const EXCLUDED_HEADERS = [
85 'connection' => true,
86 'keep-alive' => true,
87 'proxy-authenticate' => true,
88 'proxy-authentication-info' => true,
89 'proxy-authorization' => true,
90 'te' => true,
91 'trailer' => true,
92 'transfer-encoding' => true,
93 'upgrade' => true,
94 ];
95 /**
96 * Maximum heuristic freshness lifetime in seconds (24 hours).
97 */
98 private const MAX_HEURISTIC_FRESHNESS_TTL = 86400;
99 /**
100 * RFC 9111 recommends a heuristic freshness lifetime of 10% of the time since Last-Modified.
101 */
102 private const HEURISTIC_FRESHNESS_FRACTION = 0.1;
103
104 private TagAwareCacheInterface|HttpCache $cache;
105 private array $defaultOptions = self::OPTIONS_DEFAULTS;
106 private bool $isInnerRequest = false;
107
108 /**
109 * @param bool $sharedCache Indicates whether this cache is shared or private. When true, responses
110 * may be skipped from caching in presence of certain headers
111 * (e.g. Authorization) unless explicitly marked as public.
112 * @param int|null $maxTtl The maximum time-to-live (in seconds) for cached responses.
113 * If a server-provided TTL exceeds this value, it will be capped
114 * to this maximum.
115 */
116 public function __construct(
117 private HttpClientInterface $client,
118 TagAwareCacheInterface|StoreInterface $cache,
119 array $defaultOptions = [],
120 private readonly bool $sharedCache = true,
121 private readonly ?int $maxTtl = null,
122 ) {
123 if ($cache instanceof StoreInterface) {
124 trigger_deprecation('symfony/http-client', '7.4', 'Passing a "%s" as constructor\'s 2nd argument of "%s" is deprecated, "%s" expected.', StoreInterface::class, __CLASS__, TagAwareCacheInterface::class);
125
126 if (!class_exists(HttpClientKernel::class)) {
127 throw new \LogicException(\sprintf('Using "%s" requires the HttpKernel component, try running "composer require symfony/http-kernel".', __CLASS__));
128 }
129
130 $kernel = new HttpClientKernel($client);
131 $this->cache = new HttpCache($kernel, $cache, null, $defaultOptions);
132
133 unset($defaultOptions['debug']);
134 unset($defaultOptions['default_ttl']);
135 unset($defaultOptions['private_headers']);
136 unset($defaultOptions['skip_response_headers']);
137 unset($defaultOptions['allow_reload']);
138 unset($defaultOptions['allow_revalidate']);
139 unset($defaultOptions['stale_while_revalidate']);
140 unset($defaultOptions['stale_if_error']);
141 unset($defaultOptions['trace_level']);
142 unset($defaultOptions['trace_header']);
143 } else {
144 $this->cache = $cache;
145 }
146
147 if ($defaultOptions) {
148 [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
149 }
150 }
151
152 public function request(string $method, string $url, array $options = []): ResponseInterface
153 {
154 if ($this->isInnerRequest) {
155 return $this->client->request($method, $url, $options);
156 }
157
158 if ($this->cache instanceof HttpCache) {
159 return $this->legacyRequest($method, $url, $options);
160 }
161
162 [$fullUrl, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
163
164 $fullUrl = implode('', $fullUrl);
165 $fullUrlTag = self::hash($fullUrl);
166 $requestCacheControl = self::parseRequestCacheControlHeader($options['normalized_headers']['cache-control'] ?? []);
167
168 if ('' !== $options['body'] || ($options['extra']['no_cache'] ?? false) || isset($options['normalized_headers']['range']) || !\in_array($method, self::CACHEABLE_METHODS, true)) {
169 if (isset($requestCacheControl['only-if-cached'])) {
170 return self::createGatewayTimeoutResponse($method, $url, $options);
171 }
172
173 $passthru = function (ChunkInterface $chunk, AsyncContext $context) use ($method, $fullUrlTag): \Generator {
174 if (null !== $chunk->getError() || $chunk->isTimeout() || !$chunk->isFirst()) {
175 yield $chunk;
176
177 return;
178 }
179
180 $statusCode = $context->getStatusCode();
181 if ($statusCode >= 200 && $statusCode < 400 && !\in_array($method, self::SAFE_METHODS, true)) {
182 $this->cache->invalidateTags([$fullUrlTag]);
183 }
184
185 $context->passthru();
186
187 yield $chunk;
188 };
189
190 $this->isInnerRequest = true;
191
192 try {
193 return new AsyncResponse($this, $method, $url, $options, $passthru);
194 } finally {
195 $this->isInnerRequest = false;
196 }
197 }
198
199 if (isset($requestCacheControl['no-store'])) {
200 return new AsyncResponse($this->client, $method, $url, $options);
201 }
202
203 $requestHash = self::hash($method.$fullUrl.serialize(array_intersect_key($options['normalized_headers'], self::RESPONSE_INFLUENCING_HEADERS)));
204 $varyKey = "vary_{$requestHash}";
205 $varyFields = $this->cache->get($varyKey, static fn ($item, &$save): array => ($save = false) ?: [], 0);
206
207 $metadataKey = self::getMetadataKey($requestHash, $options['normalized_headers'], $varyFields);
208 $cachedData = $this->cache->get($metadataKey, static fn ($item, &$save): array => ($save = false) ?: [], 0);
209 $hasClientConditionalValidator = isset($options['normalized_headers']['if-none-match']) || isset($options['normalized_headers']['if-modified-since']);
210 $sentCacheValidator = false;
211 $allowStaleFallback = true;
212
213 $freshness = null;
214 if ($cachedData) {
215 $freshness = $this->evaluateCacheFreshness($cachedData);
216 $cachedResponseAcceptable = $this->isCachedResponseAcceptable($cachedData, $requestCacheControl, $freshness);
217 $allowStaleFallback = $cachedResponseAcceptable || !$this->requestCacheControlRequiresRevalidation($cachedData, $requestCacheControl);
218
219 if ($cachedResponseAcceptable) {
220 if ($hasClientConditionalValidator && self::clientValidatorMatchesCachedResponse($options['normalized_headers'], $cachedData)) {
221 return self::createNotModifiedResponse($method, $url, $options, $cachedData['headers']);
222 }
223
224 return $this->createResponseFromCache($cachedData, $method, $url, $options, $metadataKey);
225 }
226
227 if (isset($requestCacheControl['only-if-cached'])) {
228 return self::createGatewayTimeoutResponse($method, $url, $options);
229 }
230
231 if (!$hasClientConditionalValidator) {
232 if (isset($cachedData['headers']['etag'])) {
233 $options['headers']['If-None-Match'] = implode(', ', $cachedData['headers']['etag']);
234 $sentCacheValidator = true;
235 }
236
237 if (isset($cachedData['headers']['last-modified'][0])) {
238 $options['headers']['If-Modified-Since'] = $cachedData['headers']['last-modified'][0];
239 $sentCacheValidator = true;
240 }
241 }
242 }
243
244 if (isset($requestCacheControl['only-if-cached'])) {
245 return self::createGatewayTimeoutResponse($method, $url, $options);
246 }
247
248 // consistent expiration time for all items
249 $expiresAt = null === $this->maxTtl ? null : \DateTimeImmutable::createFromFormat('U', time() + $this->maxTtl);
250
251 $passthru = function (ChunkInterface $chunk, AsyncContext $context) use (
252 $expiresAt,
253 $fullUrlTag,
254 $requestHash,
255 $varyKey,
256 $varyFields,
257 &$metadataKey,
258 $cachedData,
259 $freshness,
260 $url,
261 $method,
262 $options,
263 $hasClientConditionalValidator,
264 $sentCacheValidator,
265 $allowStaleFallback,
266 ): \Generator {
267 static $attemptTag = null;
268 static $firstChunkKey = null;
269 static $chunkKey = null;
270
271 if (null !== $chunk->getError() || $chunk->isTimeout()) {
272 null !== $attemptTag && $this->cache->invalidateTags([$attemptTag]);
273
274 if ($allowStaleFallback && Freshness::StaleButUsable === $freshness) {
275 // avoid throwing exception in ErrorChunk#__destruct()
276 $chunk instanceof ErrorChunk && $chunk->didThrow(true);
277 $context->passthru();
278 $context->replaceResponse($this->createResponseFromCache($cachedData, $method, $url, $options, $metadataKey));
279
280 return;
281 }
282
283 if (Freshness::MustRevalidate === $freshness) {
284 // avoid throwing exception in ErrorChunk#__destruct()
285 $chunk instanceof ErrorChunk && $chunk->didThrow(true);
286 $context->passthru();
287 $context->replaceResponse(self::createGatewayTimeoutResponse($method, $url, $options));
288
289 return;
290 }
291
292 yield $chunk;
293
294 return;
295 }
296
297 $headers = $context->getHeaders();
298
299 if ($chunk->isFirst()) {
300 $statusCode = $context->getStatusCode();
301
302 $attemptTag = self::generateChunkKey();
303
304 if (304 === $statusCode && null !== $freshness) {
305 $shouldUpdateCachedMetadata = ($sentCacheValidator || $hasClientConditionalValidator) && self::notModifiedResponseMatchesCachedResponse($headers, $cachedData);
306
307 if (!$shouldUpdateCachedMetadata) {
308 $context->passthru();
309
310 yield $chunk;
311
312 return;
313 }
314
315 $responseTime = time();
316 $requestTime = (int) ($context->getInfo('start_time') ?? $responseTime);
317 if ($requestTime <= $cachedData['stored_at']) {
318 $requestTime = $responseTime;
319 }
320 $correctedInitialAge = self::getCorrectedInitialAge($headers, $requestTime, $responseTime);
321 $updatedHeaders = self::filterStorableHeaders(array_merge($cachedData['headers'], $headers), self::getExcludedHeaders($headers));
322 $updatedCachedData = array_replace($cachedData, [
323 'stored_at' => $responseTime,
324 'initial_age' => $correctedInitialAge,
325 'headers' => $updatedHeaders,
326 ]);
327
328 $updatedCacheControl = self::parseCacheControlHeader($updatedCachedData['headers']['cache-control'] ?? []);
329 $updatedCachedData['expires_at'] = self::calculateExpiresAt($this->determineMaxAge($updatedCachedData['headers'], $updatedCacheControl, $correctedInitialAge, $requestTime, $responseTime));
330
331 $newVaryFields = $this->parseVaryFields($updatedCachedData['headers']['vary'] ?? []);
332 $updatedMetadataIsCacheable = !\in_array('*', $newVaryFields, true)
333 && $varyFields === $newVaryFields
334 && $this->isServerResponseCacheable($cachedData['status_code'], $options['normalized_headers'], $updatedCachedData['headers'], $updatedCacheControl);
335
336 if (!$updatedMetadataIsCacheable) {
337 $this->cache->delete($metadataKey);
338
339 $context->passthru();
340
341 if (!$hasClientConditionalValidator) {
342 $context->replaceResponse($this->createResponseFromCache($updatedCachedData, $method, $url, $options, $metadataKey, $expiresAt));
343 }
344
345 return;
346 }
347
348 $updatedCachedData = $this->cache->get($metadataKey, static function (ItemInterface $item) use ($updatedCachedData, $expiresAt, $fullUrlTag, $metadataKey): array {
349 $item->expiresAt($expiresAt)->tag([$fullUrlTag, $metadataKey]);
350
351 return $updatedCachedData;
352 }, \INF);
353
354 $context->passthru();
355
356 if (!$hasClientConditionalValidator) {
357 $context->replaceResponse($this->createResponseFromCache($updatedCachedData, $method, $url, $options, $metadataKey, $expiresAt));
358 }
359
360 return;
361 }
362
363 if ($statusCode >= 500 && $statusCode < 600) {
364 if ($allowStaleFallback && Freshness::StaleButUsable === $freshness) {
365 $context->passthru();
366 $context->replaceResponse($this->createResponseFromCache($cachedData, $method, $url, $options, $metadataKey));
367
368 return;
369 }
370
371 if (Freshness::MustRevalidate === $freshness) {
372 $context->passthru();
373 $context->replaceResponse(self::createGatewayTimeoutResponse($method, $url, $options));
374
375 return;
376 }
377 }
378
379 $cacheControl = self::parseCacheControlHeader($headers['cache-control'] ?? []);
380
381 if (!$this->isServerResponseCacheable($statusCode, $options['normalized_headers'], $headers, $cacheControl)) {
382 $context->passthru();
383
384 yield $chunk;
385
386 return;
387 }
388
389 // recomputing vary fields in case it changed or for first request
390 $newVaryFields = $this->parseVaryFields($headers['vary'] ?? []);
391
392 if (\in_array('*', $newVaryFields, true)) {
393 $context->passthru();
394
395 yield $chunk;
396
397 return;
398 }
399
400 sort($newVaryFields);
401
402 if ($varyFields !== $newVaryFields) {
403 $this->cache->invalidateTags([$fullUrlTag]);
404
405 $metadataKey = self::getMetadataKey($requestHash, $options['normalized_headers'], $newVaryFields);
406 }
407
408 $this->cache->get($varyKey, static function (ItemInterface $item) use ($newVaryFields, $expiresAt, $fullUrlTag): array {
409 $item->tag([$fullUrlTag])->expiresAt($expiresAt);
410
411 return $newVaryFields;
412 }, \INF);
413
414 $firstChunkKey = $chunkKey = self::generateChunkKey();
415
416 yield $chunk;
417
418 return;
419 }
420
421 if (null === $chunkKey) {
422 // informational chunks
423 yield $chunk;
424
425 return;
426 }
427
428 if ($chunk->isLast()) {
429 $this->cache->get($chunkKey, static function (ItemInterface $item) use ($expiresAt, $fullUrlTag, $metadataKey, $chunk, $attemptTag): array {
430 $item->tag([$fullUrlTag, $metadataKey, $attemptTag])->expiresAt($expiresAt);
431
432 return [
433 'content' => $chunk->getContent(),
434 'next_chunk' => null,
435 ];
436 }, \INF);
437
438 $requestTime = (int) ($context->getInfo('start_time') ?? time());
439 $responseTime = time();
440 $correctedInitialAge = self::getCorrectedInitialAge($headers, $requestTime, $responseTime);
441 $maxAge = $this->determineMaxAge($headers, self::parseCacheControlHeader($headers['cache-control'] ?? []), $correctedInitialAge, $requestTime, $responseTime);
442 $this->cache->get($metadataKey, static function (ItemInterface $item) use ($context, $headers, $maxAge, $expiresAt, $fullUrlTag, $metadataKey, $attemptTag, $firstChunkKey, $responseTime, $correctedInitialAge): array {
443 $item->tag([$fullUrlTag, $metadataKey, $attemptTag])->expiresAt($expiresAt);
444
445 return [
446 'status_code' => $context->getStatusCode(),
447 'headers' => self::filterStorableHeaders($headers),
448 'initial_age' => $correctedInitialAge,
449 'stored_at' => $responseTime,
450 'expires_at' => self::calculateExpiresAt($maxAge),
451 'next_chunk' => $firstChunkKey,
452 ];
453 }, \INF);
454
455 yield $chunk;
456
457 return;
458 }
459
460 $nextChunkKey = self::generateChunkKey();
461 $this->cache->get($chunkKey, static function (ItemInterface $item) use ($expiresAt, $fullUrlTag, $metadataKey, $attemptTag, $chunk, $nextChunkKey): array {
462 $item->tag([$fullUrlTag, $metadataKey, $attemptTag])->expiresAt($expiresAt);
463
464 return [
465 'content' => $chunk->getContent(),
466 'next_chunk' => $nextChunkKey,
467 ];
468 }, \INF);
469 $chunkKey = $nextChunkKey;
470
471 yield $chunk;
472 };
473
474 $this->isInnerRequest = true;
475
476 try {
477 return new AsyncResponse($this, $method, $url, $options, $passthru);
478 } finally {
479 $this->isInnerRequest = false;
480 }
481 }
482
483 public function stream(ResponseInterface|iterable $responses, ?float $timeout = null): ResponseStreamInterface
484 {
485 if ($responses instanceof ResponseInterface) {
486 $responses = [$responses];
487 }
488
489 $mockResponses = [];
490 $asyncResponses = [];
491 $clientResponses = [];
492
493 foreach ($responses as $response) {
494 if ($response instanceof MockResponse) {
495 $mockResponses[] = $response;
496 } elseif ($response instanceof AsyncResponse) {
497 $asyncResponses[] = $response;
498 } else {
499 $clientResponses[] = $response;
500 }
501 }
502
503 if (!$mockResponses && !$clientResponses) {
504 return $this->asyncStream($asyncResponses, $timeout);
505 }
506
507 if (!$asyncResponses && !$clientResponses) {
508 return new ResponseStream(MockResponse::stream($mockResponses, $timeout));
509 }
510
511 if (!$mockResponses && !$asyncResponses) {
512 return $this->client->stream($clientResponses, $timeout);
513 }
514
515 return new ResponseStream((function () use ($mockResponses, $asyncResponses, $clientResponses, $timeout) {
516 if ($mockResponses) {
517 yield from MockResponse::stream($mockResponses, $timeout);
518 }
519 if ($clientResponses) {
520 yield from $this->client->stream($clientResponses, $timeout);
521 }
522 if ($asyncResponses) {
523 yield from $this->asyncStream($asyncResponses, $timeout);
524 }
525 })());
526 }
527
528 private function legacyRequest(string $method, string $url, array $options = []): ResponseInterface
529 {
530 [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions, true);
531 $url = implode('', $url);
532
533 if (!empty($options['body']) || !empty($options['extra']['no_cache']) || !\in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
534 return new AsyncResponse($this->client, $method, $url, $options);
535 }
536
537 $request = Request::create($url, $method);
538 $request->attributes->set('http_client_options', $options);
539
540 foreach ($options['normalized_headers'] as $name => $values) {
541 if ('cookie' !== $name) {
542 $headerValues = [];
543
544 foreach ($values as $value) {
545 $headerValues[] = substr($value, 2 + \strlen($name));
546 }
547
548 $request->headers->set($name, $headerValues);
549
550 continue;
551 }
552
553 foreach ($values as $cookies) {
554 foreach (explode('; ', substr($cookies, \strlen('Cookie: '))) as $cookie) {
555 if ('' !== $cookie) {
556 $cookie = explode('=', $cookie, 2);
557 $request->cookies->set($cookie[0], $cookie[1] ?? '');
558 }
559 }
560 }
561 }
562
563 $response = $this->cache->handle($request);
564 $response = new MockResponse($response->getContent(), [
565 'http_code' => $response->getStatusCode(),
566 'response_headers' => $response->headers->allPreserveCase(),
567 ]);
568
569 return MockResponse::fromRequest($method, $url, $options, $response);
570 }
571
572 private static function hash(string $toHash): string
573 {
574 return str_replace('/', '_', base64_encode(hash('sha256', $toHash, true)));
575 }
576
577 private static function generateChunkKey(): string
578 {
579 return str_replace('/', '_', base64_encode(random_bytes(6)));
580 }
581
582 /**
583 * Generates a unique metadata key based on the request hash and varying headers.
584 *
585 * @param string $requestHash A hash representing the request details
586 * @param array<string, string|string[]> $normalizedHeaders Normalized headers of the request
587 * @param string[] $varyFields Headers to consider for building the variant key
588 *
589 * @return string The metadata key composed of the request hash and variant key
590 */
591 private static function getMetadataKey(string $requestHash, array $normalizedHeaders, array $varyFields): string
592 {
593 $variantKey = self::hash(self::buildVariantKey($normalizedHeaders, $varyFields));
594
595 return "metadata_{$requestHash}_{$variantKey}";
596 }
597
598 /**
599 * Build a variant key for caching, given an array of normalized headers and the vary fields.
600 *
601 * The key is an ampersand-separated string of "header=value" pairs, with
602 * the special case of "header=" for headers that are not present.
603 *
604 * @param array<string, string|string[]> $normalizedHeaders
605 * @param string[] $varyFields
606 */
607 private static function buildVariantKey(array $normalizedHeaders, array $varyFields): string
608 {
609 $parts = [];
610 foreach ($varyFields as $field) {
611 $lower = strtolower($field);
612 if (!isset($normalizedHeaders[$lower])) {
613 $parts[$lower] = $lower.'=';
614 } else {
615 $parts[$lower] = $lower.'='.implode(',', array_map(rawurlencode(...), (array) $normalizedHeaders[$lower]));
616 }
617 }
618 ksort($parts);
619
620 return implode('&', $parts);
621 }
622
623 /**
624 * Parse the Cache-Control header and return an array of directive names as keys
625 * and their values as values, or true if the directive has no value.
626 *
627 * @param array<string, string|string[]> $header The Cache-Control header as an array of strings
628 *
629 * @return array<string, string|true> The parsed Cache-Control directives
630 */
631 private static function parseCacheControlHeader(array $header): array
632 {
633 $parsed = [];
634 foreach ($header as $line) {
635 foreach (explode(',', $line) as $directive) {
636 if (str_contains($directive, '=')) {
637 [$name, $value] = explode('=', $directive, 2);
638 $normalizedName = strtolower(trim($name));
639 $normalizedValue = self::unquoteCacheControlValue(trim($value));
640 } else {
641 $normalizedName = strtolower(trim($directive));
642 $normalizedValue = true;
643 }
644
645 if ('' === $normalizedName) {
646 continue;
647 }
648
649 if (\array_key_exists($normalizedName, $parsed)) {
650 // Duplicate directive values are ambiguous; make value-based checks fail closed.
651 $parsed[$normalizedName] = '';
652
653 continue;
654 }
655
656 $parsed[$normalizedName] = $normalizedValue;
657 }
658 }
659
660 return $parsed;
661 }
662
663 private static function unquoteCacheControlValue(string $value): string
664 {
665 if (2 <= \strlen($value) && '"' === $value[0] && '"' === $value[-1]) {
666 return substr($value, 1, -1);
667 }
668
669 return $value;
670 }
671
672 private static function parseDeltaSeconds(string|true|null $value): ?int
673 {
674 if (!\is_string($value) || '' === $value || !ctype_digit($value)) {
675 return null;
676 }
677
678 return (int) $value;
679 }
680
681 /**
682 * @param array<string, string[]> $headers
683 *
684 * @return array<string, string[]>
685 */
686 private static function filterStorableHeaders(array $headers, ?array $excludedHeaders = null): array
687 {
688 $excludedHeaders ??= self::getExcludedHeaders($headers);
689
690 return array_diff_key($headers, $excludedHeaders);
691 }
692
693 /**
694 * @param array<string, string[]> $headers
695 *
696 * @return array<string, bool>
697 */
698 private static function getExcludedHeaders(array $headers): array
699 {
700 $excludedHeaders = self::EXCLUDED_HEADERS;
701
702 foreach ($headers['connection'] ?? [] as $connectionHeader) {
703 foreach (explode(',', $connectionHeader) as $headerName) {
704 $headerName = strtolower(trim($headerName));
705
706 if ('' !== $headerName) {
707 $excludedHeaders[$headerName] = true;
708 }
709 }
710 }
711
712 return $excludedHeaders;
713 }
714
715 /**
716 * @param array<string, string[]> $headers
717 * @param array{headers: array<string, string[]>} $cachedData
718 */
719 private static function notModifiedResponseMatchesCachedResponse(array $headers, array $cachedData): bool
720 {
721 if (isset($headers['etag'])) {
722 $cachedEtags = $cachedData['headers']['etag'] ?? [];
723
724 foreach ($headers['etag'] as $etag) {
725 if (!self::isWeakEtag($etag)) {
726 foreach ($cachedEtags as $cachedEtag) {
727 if (!self::isWeakEtag($cachedEtag) && $etag === $cachedEtag) {
728 return true;
729 }
730 }
731
732 return false;
733 }
734 }
735
736 foreach ($headers['etag'] as $etag) {
737 foreach ($cachedEtags as $cachedEtag) {
738 if (self::stripWeakPrefix($etag) === self::stripWeakPrefix($cachedEtag)) {
739 return true;
740 }
741 }
742 }
743
744 return false;
745 }
746
747 foreach ($headers['last-modified'] ?? [] as $lastModified) {
748 return \in_array($lastModified, $cachedData['headers']['last-modified'] ?? [], true);
749 }
750
751 return !isset($cachedData['headers']['etag']) && !isset($cachedData['headers']['last-modified']);
752 }
753
754 /**
755 * @param array<string, string[]> $requestHeaders
756 * @param array{headers: array<string, string[]>} $cachedData
757 */
758 private static function clientValidatorMatchesCachedResponse(array $requestHeaders, array $cachedData): bool
759 {
760 if (isset($requestHeaders['if-none-match'])) {
761 $cachedEtags = $cachedData['headers']['etag'] ?? [];
762
763 foreach ($requestHeaders['if-none-match'] as $ifNoneMatch) {
764 $ifNoneMatch = substr($ifNoneMatch, 15);
765
766 foreach (explode(',', $ifNoneMatch) as $etag) {
767 $etag = trim($etag);
768
769 if ('*' === $etag && [] !== $cachedEtags) {
770 return true;
771 }
772
773 foreach ($cachedEtags as $cachedEtag) {
774 if (self::stripWeakPrefix($etag) === self::stripWeakPrefix($cachedEtag)) {
775 return true;
776 }
777 }
778 }
779 }
780
781 return false;
782 }
783
784 if (!isset($requestHeaders['if-modified-since'], $cachedData['headers']['last-modified'][0])) {
785 return false;
786 }
787
788 $lastModified = strtotime($cachedData['headers']['last-modified'][0]);
789 if (false === $lastModified) {
790 return false;
791 }
792
793 foreach ($requestHeaders['if-modified-since'] as $ifModifiedSince) {
794 $ifModifiedSince = substr($ifModifiedSince, 19);
795
796 if (false !== $modifiedSince = strtotime($ifModifiedSince)) {
797 return $lastModified <= $modifiedSince;
798 }
799 }
800
801 return false;
802 }
803
804 private static function stripWeakPrefix(string $etag): string
805 {
806 return str_starts_with($etag, 'W/') ? substr($etag, 2) : $etag;
807 }
808
809 private static function isWeakEtag(string $etag): bool
810 {
811 return str_starts_with($etag, 'W/');
812 }
813
814 /**
815 * @param string[] $header
816 *
817 * @return array<string, string|true>
818 */
819 private static function parseRequestCacheControlHeader(array $header): array
820 {
821 $cacheControlHeader = [];
822
823 foreach ($header as $line) {
824 // Strip the "Cache-Control: " prefix added by normalizeHeaders(); response headers contain values only.
825 $cacheControlHeader[] = substr($line, 15);
826 }
827
828 return self::parseCacheControlHeader($cacheControlHeader);
829 }
830
831 /**
832 * Evaluates the freshness of a cached response based on its headers and expiration time.
833 *
834 * This method determines the state of the cached response by analyzing the Cache-Control
835 * directives and the expiration timestamp.
836 *
837 * @param array{headers: array<string, string[]>, expires_at: int|null} $data The cached response data, including headers and expiration time
838 */
839 private function evaluateCacheFreshness(array $data): Freshness
840 {
841 $cacheControl = self::parseCacheControlHeader($data['headers']['cache-control'] ?? []);
842
843 if (isset($cacheControl['no-cache'])) {
844 return Freshness::Stale;
845 }
846
847 $now = time();
848 $expires = $data['expires_at'];
849
850 if (null !== $expires && $now < $expires) {
851 return Freshness::Fresh;
852 }
853
854 if (
855 isset($cacheControl['must-revalidate'])
856 || (
857 $this->sharedCache
858 && (
859 isset($cacheControl['proxy-revalidate'])
860 || self::hasValidSharedMaxAge($cacheControl)
861 )
862 )
863 ) {
864 return Freshness::MustRevalidate;
865 }
866
867 if (
868 null !== ($staleIfError = self::parseDeltaSeconds($cacheControl['stale-if-error'] ?? null))
869 && ($now - $expires) <= $staleIfError
870 ) {
871 return Freshness::StaleButUsable;
872 }
873
874 return Freshness::Stale;
875 }
876
877 /**
878 * Determine the maximum age of the response.
879 *
880 * This method first checks for the presence of the s-maxage directive, and if
881 * present, returns its value minus the current age. If s-maxage is not present,
882 * it checks for the presence of the max-age directive, and if present, returns
883 * its value minus the current age. If neither directive is present, it checks
884 * the Expires header for a valid timestamp, and if present, returns the
885 * difference between the timestamp and the current time minus the current age.
886 *
887 * If none of the above directives or headers are present, the method returns null.
888 *
889 * @param array<string, string|string[]> $headers An array of HTTP headers
890 * @param array<string, string|true> $cacheControl An array of parsed Cache-Control directives
891 *
892 * @return int|null The maximum age of the response, or null if it cannot be determined
893 */
894 private function determineMaxAge(array $headers, array $cacheControl, int $correctedInitialAge, int $requestTime, int $responseTime): ?int
895 {
896 $age = $correctedInitialAge;
897
898 if ($this->sharedCache && isset($cacheControl['s-maxage'])) {
899 if (null === $sharedMaxAge = self::parseDeltaSeconds($cacheControl['s-maxage'])) {
900 return null;
901 }
902
903 return max(0, $sharedMaxAge - $age);
904 }
905
906 if (isset($cacheControl['max-age'])) {
907 if (null === $maxAge = self::parseDeltaSeconds($cacheControl['max-age'])) {
908 return null;
909 }
910
911 return max(0, $maxAge - $age);
912 }
913
914 foreach ($headers['expires'] ?? [] as $expire) {
915 if (false !== $expirationTimestamp = strtotime($expire)) {
916 $dateTimestamp = self::getDateHeaderTimestamp($headers) ?? $responseTime;
917 $timeUntilExpiration = $expirationTimestamp - $dateTimestamp - $age;
918
919 return max($timeUntilExpiration, 0);
920 }
921 }
922
923 if (null !== $heuristicFreshnessLifetime = $this->determineHeuristicFreshnessLifetime($headers, $cacheControl, $requestTime)) {
924 return max(0, $heuristicFreshnessLifetime - $age);
925 }
926
927 return null;
928 }
929
930 /**
931 * @param array<string, string|string[]> $headers
932 * @param array<string, string|true> $cacheControl
933 */
934 private function determineHeuristicFreshnessLifetime(array $headers, array $cacheControl, int $requestTime): ?int
935 {
936 if (!$this->allowsHeuristicFreshness($headers, $cacheControl)) {
937 return null;
938 }
939
940 foreach ($headers['last-modified'] as $lastModified) {
941 if (false === $lastModifiedTimestamp = strtotime($lastModified)) {
942 continue;
943 }
944
945 $secondsSinceLastModified = $requestTime - $lastModifiedTimestamp;
946
947 if (0 >= $secondsSinceLastModified) {
948 continue;
949 }
950
951 $heuristicFreshnessLifetime = (int) ($secondsSinceLastModified * self::HEURISTIC_FRESHNESS_FRACTION);
952
953 return min($heuristicFreshnessLifetime, self::MAX_HEURISTIC_FRESHNESS_TTL);
954 }
955
956 return null;
957 }
958
959 /**
960 * Retrieves the current age of the response from the headers.
961 *
962 * @param array<string, string|string[]> $headers An array of HTTP headers
963 *
964 * @return int The age of the response in seconds, defaults to 0 if not present
965 */
966 private static function getCurrentAge(array $headers): int
967 {
968 return (int) ($headers['age'][0] ?? 0);
969 }
970
971 /**
972 * @param array<string, string|string[]> $headers
973 */
974 private static function getDateHeaderTimestamp(array $headers): ?int
975 {
976 foreach ($headers['date'] ?? [] as $date) {
977 if (false !== $timestamp = strtotime($date)) {
978 return $timestamp;
979 }
980 }
981
982 return null;
983 }
984
985 /**
986 * @param array<string, string|string[]> $headers
987 */
988 private static function getCorrectedInitialAge(array $headers, int $requestTime, int $responseTime): int
989 {
990 $ageValue = self::getCurrentAge($headers);
991 $dateValue = self::getDateHeaderTimestamp($headers);
992 $apparentAge = null === $dateValue ? 0 : max(0, $responseTime - $dateValue);
993 $responseDelay = max(0, $responseTime - $requestTime);
994 $correctedAgeValue = $ageValue + $responseDelay;
995
996 return max($apparentAge, $correctedAgeValue);
997 }
998
999 /**
1000 * @param array{initial_age: int, stored_at: int} $cachedData
1001 * @param array<string, string|true> $requestCacheControl
1002 */
1003 private function isCachedResponseAcceptable(array $cachedData, array $requestCacheControl, Freshness $freshness): bool
1004 {
1005 if (Freshness::Fresh !== $freshness || isset($requestCacheControl['no-cache'])) {
1006 return false;
1007 }
1008
1009 if (!isset($requestCacheControl['max-age'])) {
1010 return true;
1011 }
1012
1013 if (null === $maxAge = self::parseDeltaSeconds($requestCacheControl['max-age'])) {
1014 return true;
1015 }
1016
1017 if (0 === $maxAge) {
1018 return false;
1019 }
1020
1021 return $this->getCachedResponseAge($cachedData) <= $maxAge;
1022 }
1023
1024 /**
1025 * @param array{initial_age: int, stored_at: int} $cachedData
1026 * @param array<string, string|true> $requestCacheControl
1027 */
1028 private function requestCacheControlRequiresRevalidation(array $cachedData, array $requestCacheControl): bool
1029 {
1030 if (isset($requestCacheControl['no-cache'])) {
1031 return true;
1032 }
1033
1034 if (null === $maxAge = self::parseDeltaSeconds($requestCacheControl['max-age'] ?? null)) {
1035 return false;
1036 }
1037
1038 return $this->getCachedResponseAge($cachedData) > $maxAge;
1039 }
1040
1041 /**
1042 * @param array{initial_age: int, stored_at: int} $cachedData
1043 */
1044 private function getCachedResponseAge(array $cachedData): int
1045 {
1046 return $cachedData['initial_age'] + (time() - $cachedData['stored_at']);
1047 }
1048
1049 /**
1050 * Calculates the expiration time of the response given the maximum age.
1051 *
1052 * @param int|null $maxAge The maximum age of the response in seconds, or null if it cannot be determined
1053 *
1054 * @return int|null The expiration time of the response as a Unix timestamp, or null if the maximum age is null
1055 */
1056 private static function calculateExpiresAt(?int $maxAge): ?int
1057 {
1058 if (null === $maxAge) {
1059 return null;
1060 }
1061
1062 return time() + $maxAge;
1063 }
1064
1065 /**
1066 * @param string[] $varyHeaders
1067 *
1068 * @return string[]
1069 */
1070 private function parseVaryFields(array $varyHeaders): array
1071 {
1072 $varyFields = [];
1073 foreach ($varyHeaders as $vary) {
1074 foreach (explode(',', $vary) as $field) {
1075 $field = strtolower(trim($field));
1076 if ('cookie' === $field ? $this->sharedCache : !preg_match('/^[!#$%&\'*+\-.^_`|~0-9A-Za-z]+$/D', $field)) {
1077 $field = '*';
1078 }
1079 $varyFields[] = $field;
1080 }
1081 }
1082
1083 sort($varyFields);
1084
1085 return $varyFields;
1086 }
1087
1088 /**
1089 * Checks if the server response is cacheable according to the HTTP 1.1
1090 * specification (RFC 9111).
1091 *
1092 * This function will return true if the server response can be cached,
1093 * false otherwise.
1094 *
1095 * @param array<string, string|string[]> $requestHeaders
1096 * @param array<string, string|string[]> $responseHeaders
1097 * @param array<string, string|true> $cacheControl
1098 */
1099 private function isServerResponseCacheable(int $statusCode, array $requestHeaders, array $responseHeaders, array $cacheControl): bool
1100 {
1101 // Only final status codes are cacheable by RFC 9111 Section 3.
1102 if ($statusCode < 200 || $statusCode > 599 || self::isStatusCodeExcludedFromStorage($statusCode)) {
1103 return false;
1104 }
1105
1106 // no-store => skip caching
1107 if (isset($cacheControl['no-store'])) {
1108 return false;
1109 }
1110
1111 if ($this->sharedCache) {
1112 if (
1113 !isset($cacheControl['public']) && !self::hasValidSharedMaxAge($cacheControl) && !isset($cacheControl['must-revalidate'])
1114 && isset($requestHeaders['authorization'])
1115 ) {
1116 return false;
1117 }
1118
1119 if (isset($cacheControl['private'])) {
1120 return false;
1121 }
1122
1123 if (isset($responseHeaders['authentication-info']) || isset($responseHeaders['set-cookie']) || isset($responseHeaders['www-authenticate'])) {
1124 return false;
1125 }
1126 }
1127
1128 if (\in_array($statusCode, self::DEFAULT_CACHEABLE_STATUS_CODES, true)) {
1129 return true;
1130 }
1131
1132 if ($this->hasExplicitFreshness($responseHeaders, $cacheControl)) {
1133 return true;
1134 }
1135
1136 return $this->allowsHeuristicFreshnessForNonDefaultStatus($responseHeaders, $cacheControl);
1137 }
1138
1139 private static function isStatusCodeExcludedFromStorage(int $statusCode): bool
1140 {
1141 // 206 is only cacheable for range requests, which this client does not store.
1142 return 206 === $statusCode || 304 === $statusCode;
1143 }
1144
1145 /**
1146 * Checks if the response has explicit freshness.
1147 *
1148 * This function will return true if the response has explicit freshness
1149 * specified in the headers or in the Cache-Control directives,
1150 * false otherwise.
1151 *
1152 * @param array<string, string|string[]> $headers
1153 * @param array<string, string|true> $cacheControl
1154 */
1155 private function hasExplicitFreshness(array $headers, array $cacheControl): bool
1156 {
1157 if (($this->sharedCache && self::hasValidSharedMaxAge($cacheControl)) || null !== self::parseDeltaSeconds($cacheControl['max-age'] ?? null)) {
1158 return true;
1159 }
1160
1161 foreach ($headers['expires'] ?? [] as $expires) {
1162 if (false !== strtotime($expires)) {
1163 return true;
1164 }
1165 }
1166
1167 return false;
1168 }
1169
1170 /**
1171 * @param array<string, string|true> $cacheControl
1172 */
1173 private static function hasValidSharedMaxAge(array $cacheControl): bool
1174 {
1175 return null !== self::parseDeltaSeconds($cacheControl['s-maxage'] ?? null);
1176 }
1177
1178 /**
1179 * @param array<string, string|string[]> $headers
1180 * @param array<string, string|true> $cacheControl
1181 */
1182 private function allowsHeuristicFreshnessForNonDefaultStatus(array $headers, array $cacheControl): bool
1183 {
1184 return isset($cacheControl['public']) && $this->allowsHeuristicFreshness($headers, $cacheControl);
1185 }
1186
1187 /**
1188 * @param array<string, string|string[]> $headers
1189 * @param array<string, string|true> $cacheControl
1190 */
1191 private function allowsHeuristicFreshness(array $headers, array $cacheControl): bool
1192 {
1193 return !isset($cacheControl['no-cache'])
1194 && !isset($cacheControl['no-store'])
1195 && isset($headers['last-modified']);
1196 }
1197
1198 /**
1199 * Creates a MockResponse object from cached data.
1200 *
1201 * This function constructs a MockResponse from the cached data, including
1202 * the original request method, URL, and options, as well as the cached
1203 * response headers and content. The constructed MockResponse is then
1204 * returned.
1205 *
1206 * @param array{next_chunk: string, status_code: int, initial_age: int, headers: array<string, string|string[]>, stored_at: int} $cachedData
1207 */
1208 private function createResponseFromCache(array $cachedData, string $method, string $url, array $options, string $metadataKey, \DateTimeImmutable|false|null $newExpiresAt = false): MockResponse
1209 {
1210 $cache = $this->cache;
1211
1212 $beta = 0;
1213 $callback = static function (ItemInterface $item) use ($cache, $metadataKey): never {
1214 $cache->invalidateTags([$metadataKey]);
1215
1216 throw new ChunkCacheItemNotFoundException(\sprintf('Missing cache item for chunk with key "%s". This indicates an internal cache inconsistency.', $item->getKey()));
1217 };
1218
1219 if (false !== $newExpiresAt) {
1220 $beta = \INF;
1221 $callback = static function (ItemInterface $item) use ($callback, $newExpiresAt): array {
1222 if (!$item->isHit()) {
1223 $callback($item);
1224 }
1225
1226 $item->expiresAt($newExpiresAt);
1227
1228 return $item->get();
1229 };
1230 }
1231
1232 $body = static function () use ($cache, $cachedData, $callback, $beta): \Generator {
1233 while (null !== $cachedData['next_chunk']) {
1234 $cachedData = $cache->get($cachedData['next_chunk'], $callback, $beta);
1235
1236 if ('' !== $cachedData['content']) {
1237 yield $cachedData['content'];
1238 }
1239 }
1240 };
1241
1242 return MockResponse::fromRequest($method, $url, $options, new MockResponse($body(), [
1243 'http_code' => $cachedData['status_code'],
1244 'response_headers' => [
1245 'age' => $this->getCachedResponseAge($cachedData),
1246 ] + $cachedData['headers'],
1247 ]));
1248 }
1249
1250 private static function createGatewayTimeoutResponse(string $method, string $url, array $options): MockResponse
1251 {
1252 return MockResponse::fromRequest($method, $url, $options, new MockResponse('', ['http_code' => 504]));
1253 }
1254
1255 /**
1256 * @param array<string, string|string[]> $headers
1257 */
1258 private static function createNotModifiedResponse(string $method, string $url, array $options, array $headers): MockResponse
1259 {
1260 return MockResponse::fromRequest($method, $url, $options, new MockResponse('', [
1261 'http_code' => 304,
1262 'response_headers' => array_diff_key($headers, self::EXCLUDED_HEADERS),
1263 ]));
1264 }
1265 }