Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/Response.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\HttpFoundation;
13
14 // Help opcache.preload discover always-needed symbols
15 class_exists(ResponseHeaderBag::class);
16
17 /**
18 * Response represents an HTTP response.
19 *
20 * @author Fabien Potencier <[email protected]>
21 */
22 class Response
23 {
24 public const HTTP_CONTINUE = 100;
25 public const HTTP_SWITCHING_PROTOCOLS = 101;
26 public const HTTP_PROCESSING = 102; // RFC2518
27 public const HTTP_EARLY_HINTS = 103; // RFC8297
28 public const HTTP_OK = 200;
29 public const HTTP_CREATED = 201;
30 public const HTTP_ACCEPTED = 202;
31 public const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
32 public const HTTP_NO_CONTENT = 204;
33 public const HTTP_RESET_CONTENT = 205;
34 public const HTTP_PARTIAL_CONTENT = 206;
35 public const HTTP_MULTI_STATUS = 207; // RFC4918
36 public const HTTP_ALREADY_REPORTED = 208; // RFC5842
37 public const HTTP_IM_USED = 226; // RFC3229
38 public const HTTP_MULTIPLE_CHOICES = 300;
39 public const HTTP_MOVED_PERMANENTLY = 301;
40 public const HTTP_FOUND = 302;
41 public const HTTP_SEE_OTHER = 303;
42 public const HTTP_NOT_MODIFIED = 304;
43 public const HTTP_USE_PROXY = 305;
44 public const HTTP_RESERVED = 306;
45 public const HTTP_TEMPORARY_REDIRECT = 307;
46 public const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238
47 public const HTTP_BAD_REQUEST = 400;
48 public const HTTP_UNAUTHORIZED = 401;
49 public const HTTP_PAYMENT_REQUIRED = 402;
50 public const HTTP_FORBIDDEN = 403;
51 public const HTTP_NOT_FOUND = 404;
52 public const HTTP_METHOD_NOT_ALLOWED = 405;
53 public const HTTP_NOT_ACCEPTABLE = 406;
54 public const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
55 public const HTTP_REQUEST_TIMEOUT = 408;
56 public const HTTP_CONFLICT = 409;
57 public const HTTP_GONE = 410;
58 public const HTTP_LENGTH_REQUIRED = 411;
59 public const HTTP_PRECONDITION_FAILED = 412;
60 public const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
61 public const HTTP_REQUEST_URI_TOO_LONG = 414;
62 public const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
63 public const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
64 public const HTTP_EXPECTATION_FAILED = 417;
65 public const HTTP_I_AM_A_TEAPOT = 418; // RFC2324
66 public const HTTP_MISDIRECTED_REQUEST = 421; // RFC7540
67 public const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
68 public const HTTP_LOCKED = 423; // RFC4918
69 public const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
70 public const HTTP_TOO_EARLY = 425; // RFC-ietf-httpbis-replay-04
71 public const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
72 public const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
73 public const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
74 public const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
75 public const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; // RFC7725
76 public const HTTP_INTERNAL_SERVER_ERROR = 500;
77 public const HTTP_NOT_IMPLEMENTED = 501;
78 public const HTTP_BAD_GATEWAY = 502;
79 public const HTTP_SERVICE_UNAVAILABLE = 503;
80 public const HTTP_GATEWAY_TIMEOUT = 504;
81 public const HTTP_VERSION_NOT_SUPPORTED = 505;
82 public const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
83 public const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918
84 public const HTTP_LOOP_DETECTED = 508; // RFC5842
85 public const HTTP_NOT_EXTENDED = 510; // RFC2774
86 public const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
87
88 /**
89 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
90 */
91 private const HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES = [
92 'must_revalidate' => false,
93 'no_cache' => false,
94 'no_store' => false,
95 'no_transform' => false,
96 'public' => false,
97 'private' => false,
98 'proxy_revalidate' => false,
99 'max_age' => true,
100 's_maxage' => true,
101 'stale_if_error' => true, // RFC5861
102 'stale_while_revalidate' => true, // RFC5861
103 'immutable' => false,
104 'last_modified' => true,
105 'etag' => true,
106 ];
107
108 public ResponseHeaderBag $headers;
109
110 protected string $content;
111 protected string $version;
112 protected int $statusCode;
113 protected string $statusText;
114 protected ?string $charset = null;
115
116 /**
117 * Status codes translation table.
118 *
119 * The list of codes is complete according to the
120 * {@link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Hypertext Transfer Protocol (HTTP) Status Code Registry}
121 * (last updated 2021-10-01).
122 *
123 * Unless otherwise noted, the status code is defined in RFC2616.
124 *
125 * @var array<int, string>
126 */
127 public static array $statusTexts = [
128 100 => 'Continue',
129 101 => 'Switching Protocols',
130 102 => 'Processing', // RFC2518
131 103 => 'Early Hints',
132 200 => 'OK',
133 201 => 'Created',
134 202 => 'Accepted',
135 203 => 'Non-Authoritative Information',
136 204 => 'No Content',
137 205 => 'Reset Content',
138 206 => 'Partial Content',
139 207 => 'Multi-Status', // RFC4918
140 208 => 'Already Reported', // RFC5842
141 226 => 'IM Used', // RFC3229
142 300 => 'Multiple Choices',
143 301 => 'Moved Permanently',
144 302 => 'Found',
145 303 => 'See Other',
146 304 => 'Not Modified',
147 305 => 'Use Proxy',
148 307 => 'Temporary Redirect',
149 308 => 'Permanent Redirect', // RFC7238
150 400 => 'Bad Request',
151 401 => 'Unauthorized',
152 402 => 'Payment Required',
153 403 => 'Forbidden',
154 404 => 'Not Found',
155 405 => 'Method Not Allowed',
156 406 => 'Not Acceptable',
157 407 => 'Proxy Authentication Required',
158 408 => 'Request Timeout',
159 409 => 'Conflict',
160 410 => 'Gone',
161 411 => 'Length Required',
162 412 => 'Precondition Failed',
163 413 => 'Content Too Large', // RFC-ietf-httpbis-semantics
164 414 => 'URI Too Long',
165 415 => 'Unsupported Media Type',
166 416 => 'Range Not Satisfiable',
167 417 => 'Expectation Failed',
168 418 => 'I\'m a teapot', // RFC2324
169 421 => 'Misdirected Request', // RFC7540
170 422 => 'Unprocessable Content', // RFC-ietf-httpbis-semantics
171 423 => 'Locked', // RFC4918
172 424 => 'Failed Dependency', // RFC4918
173 425 => 'Too Early', // RFC-ietf-httpbis-replay-04
174 426 => 'Upgrade Required', // RFC2817
175 428 => 'Precondition Required', // RFC6585
176 429 => 'Too Many Requests', // RFC6585
177 431 => 'Request Header Fields Too Large', // RFC6585
178 451 => 'Unavailable For Legal Reasons', // RFC7725
179 500 => 'Internal Server Error',
180 501 => 'Not Implemented',
181 502 => 'Bad Gateway',
182 503 => 'Service Unavailable',
183 504 => 'Gateway Timeout',
184 505 => 'HTTP Version Not Supported',
185 506 => 'Variant Also Negotiates', // RFC2295
186 507 => 'Insufficient Storage', // RFC4918
187 508 => 'Loop Detected', // RFC5842
188 510 => 'Not Extended', // RFC2774
189 511 => 'Network Authentication Required', // RFC6585
190 ];
191
192 /**
193 * Tracks headers already sent in informational responses.
194 */
195 private array $sentHeaders;
196
197 /**
198 * @param int $status The HTTP status code (200 "OK" by default)
199 *
200 * @throws \InvalidArgumentException When the HTTP status code is not valid
201 */
202 public function __construct(?string $content = '', int $status = 200, array $headers = [])
203 {
204 $this->headers = new ResponseHeaderBag($headers);
205 $this->setContent($content);
206 $this->setStatusCode($status);
207 $this->setProtocolVersion('1.0');
208 }
209
210 /**
211 * Returns the Response as an HTTP string.
212 *
213 * The string representation of the Response is the same as the
214 * one that will be sent to the client only if the prepare() method
215 * has been called before.
216 *
217 * @see prepare()
218 */
219 public function __toString(): string
220 {
221 return
222 \sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
223 $this->headers."\r\n".
224 $this->getContent();
225 }
226
227 /**
228 * Clones the current Response instance.
229 */
230 public function __clone()
231 {
232 $this->headers = clone $this->headers;
233 }
234
235 /**
236 * Prepares the Response before it is sent to the client.
237 *
238 * This method tweaks the Response to ensure that it is
239 * compliant with RFC 2616. Most of the changes are based on
240 * the Request that is "associated" with this Response.
241 *
242 * @return $this
243 */
244 public function prepare(Request $request): static
245 {
246 $headers = $this->headers;
247
248 if ($this->isInformational() || $this->isEmpty()) {
249 $this->setContent(null);
250 $headers->remove('Content-Type');
251 $headers->remove('Content-Length');
252 // prevent PHP from sending the Content-Type header based on default_mimetype
253 ini_set('default_mimetype', '');
254 } else {
255 // Content-type based on the Request
256 if (!$headers->has('Content-Type')) {
257 $format = $request->getRequestFormat(null);
258 if (null !== $format && $mimeType = $request->getMimeType($format)) {
259 $headers->set('Content-Type', $mimeType);
260 }
261 }
262
263 // Fix Content-Type
264 $charset = $this->charset ?: 'utf-8';
265 if (!$headers->has('Content-Type')) {
266 $headers->set('Content-Type', 'text/html; charset='.$charset);
267 } elseif (0 === stripos($headers->get('Content-Type') ?? '', 'text/') && false === stripos($headers->get('Content-Type') ?? '', 'charset')) {
268 // add the charset
269 $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
270 }
271
272 // Fix Content-Length
273 if ($headers->has('Transfer-Encoding')) {
274 $headers->remove('Content-Length');
275 }
276
277 if ($request->isMethod('HEAD')) {
278 // cf. RFC2616 14.13
279 $length = $headers->get('Content-Length');
280 $this->setContent(null);
281 if ($length) {
282 $headers->set('Content-Length', $length);
283 }
284 }
285 }
286
287 // Fix protocol
288 if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
289 $this->setProtocolVersion('1.1');
290 }
291
292 // Check if we need to send extra expire info headers
293 if ('1.0' == $this->getProtocolVersion() && str_contains($headers->get('Cache-Control', ''), 'no-cache')) {
294 $headers->set('pragma', 'no-cache');
295 $headers->set('expires', -1);
296 }
297
298 $this->ensureIEOverSSLCompatibility($request);
299
300 if ($request->isSecure()) {
301 foreach ($headers->getCookies() as $cookie) {
302 $cookie->setSecureDefault(true);
303 }
304 }
305
306 return $this;
307 }
308
309 /**
310 * Sends HTTP headers.
311 *
312 * @param positive-int|null $statusCode The status code to use, override the statusCode property if set and not null
313 *
314 * @return $this
315 */
316 public function sendHeaders(?int $statusCode = null): static
317 {
318 // headers have already been sent by the developer
319 if (headers_sent()) {
320 if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
321 $statusCode ??= $this->statusCode;
322 trigger_deprecation('symfony/http-foundation', '7.4', 'Trying to use "%s::sendHeaders()" after headers have already been sent is deprecated and will throw a PHP warning in 8.0. Use a "StreamedResponse" instead.', static::class);
323 // header(\sprintf('HTTP/%s %s %s', $this->version, $statusCode, $this->statusText), true, $statusCode);
324 }
325
326 return $this;
327 }
328
329 $informationalResponse = $statusCode >= 100 && $statusCode < 200;
330 if ($informationalResponse && !\function_exists('headers_send')) {
331 // skip informational responses if not supported by the SAPI
332 return $this;
333 }
334
335 // headers
336 foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
337 // As recommended by RFC 8297, PHP automatically copies headers from previous 103 responses, we need to deal with that if headers changed
338 $previousValues = $this->sentHeaders[$name] ?? null;
339 if ($previousValues === $values) {
340 // Header already sent in a previous response, it will be automatically copied in this response by PHP
341 continue;
342 }
343
344 $replace = 0 === strcasecmp($name, 'Content-Type');
345
346 if (null !== $previousValues && array_diff($previousValues, $values)) {
347 header_remove($name);
348 $previousValues = null;
349 }
350
351 $newValues = null === $previousValues ? $values : array_diff($values, $previousValues);
352
353 foreach ($newValues as $value) {
354 header($name.': '.$value, $replace, $this->statusCode);
355 }
356
357 if ($informationalResponse) {
358 $this->sentHeaders[$name] = $values;
359 }
360 }
361
362 // cookies
363 foreach ($this->headers->getCookies() as $cookie) {
364 header('Set-Cookie: '.$cookie, false, $this->statusCode);
365 }
366
367 if ($informationalResponse) {
368 headers_send($statusCode);
369
370 return $this;
371 }
372
373 $statusCode ??= $this->statusCode;
374
375 // status
376 header(\sprintf('HTTP/%s %s %s', $this->version, $statusCode, $this->statusText), true, $statusCode);
377
378 return $this;
379 }
380
381 /**
382 * Sends content for the current web response.
383 *
384 * @return $this
385 */
386 public function sendContent(): static
387 {
388 echo $this->content;
389
390 return $this;
391 }
392
393 /**
394 * Sends HTTP headers and content.
395 *
396 * @param bool $flush Whether output buffers should be flushed
397 *
398 * @return $this
399 */
400 public function send(bool $flush = true): static
401 {
402 $this->sendHeaders();
403 $this->sendContent();
404
405 if (!$flush) {
406 return $this;
407 }
408
409 if (\function_exists('fastcgi_finish_request')) {
410 fastcgi_finish_request();
411 } elseif (\function_exists('litespeed_finish_request')) {
412 litespeed_finish_request();
413 } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
414 static::closeOutputBuffers(0, true);
415 flush();
416 }
417
418 return $this;
419 }
420
421 /**
422 * Sets the response content.
423 *
424 * @return $this
425 */
426 public function setContent(?string $content): static
427 {
428 $this->content = $content ?? '';
429
430 return $this;
431 }
432
433 /**
434 * Gets the current response content.
435 */
436 public function getContent(): string|false
437 {
438 return $this->content;
439 }
440
441 /**
442 * Sets the HTTP protocol version (1.0 or 1.1).
443 *
444 * @return $this
445 *
446 * @final
447 */
448 public function setProtocolVersion(string $version): static
449 {
450 $this->version = $version;
451
452 return $this;
453 }
454
455 /**
456 * Gets the HTTP protocol version.
457 *
458 * @final
459 */
460 public function getProtocolVersion(): string
461 {
462 return $this->version;
463 }
464
465 /**
466 * Sets the response status code.
467 *
468 * If the status text is null it will be automatically populated for the known
469 * status codes and left empty otherwise.
470 *
471 * @return $this
472 *
473 * @throws \InvalidArgumentException When the HTTP status code is not valid
474 *
475 * @final
476 */
477 public function setStatusCode(int $code, ?string $text = null): static
478 {
479 $this->statusCode = $code;
480 if ($this->isInvalid()) {
481 throw new \InvalidArgumentException(\sprintf('The HTTP status code "%s" is not valid.', $code));
482 }
483
484 if (null === $text) {
485 $this->statusText = self::$statusTexts[$code] ?? 'unknown status';
486
487 return $this;
488 }
489
490 $this->statusText = $text;
491
492 return $this;
493 }
494
495 /**
496 * Retrieves the status code for the current web response.
497 *
498 * @final
499 */
500 public function getStatusCode(): int
501 {
502 return $this->statusCode;
503 }
504
505 /**
506 * Sets the response charset.
507 *
508 * @return $this
509 *
510 * @final
511 */
512 public function setCharset(string $charset): static
513 {
514 $this->charset = $charset;
515
516 return $this;
517 }
518
519 /**
520 * Retrieves the response charset.
521 *
522 * @final
523 */
524 public function getCharset(): ?string
525 {
526 return $this->charset;
527 }
528
529 /**
530 * Returns true if the response may safely be kept in a shared (surrogate) cache.
531 *
532 * Responses marked "private" with an explicit Cache-Control directive are
533 * considered uncacheable.
534 *
535 * Responses with neither a freshness lifetime (Expires, max-age) nor cache
536 * validator (Last-Modified, ETag) are considered uncacheable because there is
537 * no way to tell when or how to remove them from the cache.
538 *
539 * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
540 * for example "status codes that are defined as cacheable by default [...]
541 * can be reused by a cache with heuristic expiration unless otherwise indicated"
542 * (https://tools.ietf.org/html/rfc7231#section-6.1)
543 *
544 * @final
545 */
546 public function isCacheable(): bool
547 {
548 if (!\in_array($this->statusCode, [200, 203, 300, 301, 302, 404, 410], true)) {
549 return false;
550 }
551
552 if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
553 return false;
554 }
555
556 return $this->isValidateable() || $this->isFresh();
557 }
558
559 /**
560 * Returns true if the response is "fresh".
561 *
562 * Fresh responses may be served from cache without any interaction with the
563 * origin. A response is considered fresh when it includes a Cache-Control/max-age
564 * indicator or Expires header and the calculated age is less than the freshness lifetime.
565 *
566 * @final
567 */
568 public function isFresh(): bool
569 {
570 return $this->getTtl() > 0;
571 }
572
573 /**
574 * Returns true if the response includes headers that can be used to validate
575 * the response with the origin server using a conditional GET request.
576 *
577 * @final
578 */
579 public function isValidateable(): bool
580 {
581 return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
582 }
583
584 /**
585 * Marks the response as "private".
586 *
587 * It makes the response ineligible for serving other clients.
588 *
589 * @return $this
590 *
591 * @final
592 */
593 public function setPrivate(): static
594 {
595 $this->headers->removeCacheControlDirective('public');
596 $this->headers->addCacheControlDirective('private');
597
598 return $this;
599 }
600
601 /**
602 * Marks the response as "public".
603 *
604 * It makes the response eligible for serving other clients.
605 *
606 * @return $this
607 *
608 * @final
609 */
610 public function setPublic(): static
611 {
612 $this->headers->addCacheControlDirective('public');
613 $this->headers->removeCacheControlDirective('private');
614
615 return $this;
616 }
617
618 /**
619 * Marks the response as "immutable".
620 *
621 * @return $this
622 *
623 * @final
624 */
625 public function setImmutable(bool $immutable = true): static
626 {
627 if ($immutable) {
628 $this->headers->addCacheControlDirective('immutable');
629 } else {
630 $this->headers->removeCacheControlDirective('immutable');
631 }
632
633 return $this;
634 }
635
636 /**
637 * Returns true if the response is marked as "immutable".
638 *
639 * @final
640 */
641 public function isImmutable(): bool
642 {
643 return $this->headers->hasCacheControlDirective('immutable');
644 }
645
646 /**
647 * Returns true if the response must be revalidated by shared caches once it has become stale.
648 *
649 * This method indicates that the response must not be served stale by a
650 * cache in any circumstance without first revalidating with the origin.
651 * When present, the TTL of the response should not be overridden to be
652 * greater than the value provided by the origin.
653 *
654 * @final
655 */
656 public function mustRevalidate(): bool
657 {
658 return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
659 }
660
661 /**
662 * Returns the Date header as a DateTime instance.
663 *
664 * @throws \RuntimeException When the header is not parseable
665 *
666 * @final
667 */
668 public function getDate(): ?\DateTimeImmutable
669 {
670 return $this->headers->getDate('Date');
671 }
672
673 /**
674 * Sets the Date header.
675 *
676 * @return $this
677 *
678 * @final
679 */
680 public function setDate(\DateTimeInterface $date): static
681 {
682 $date = \DateTimeImmutable::createFromInterface($date);
683 $date = $date->setTimezone(new \DateTimeZone('UTC'));
684 $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
685
686 return $this;
687 }
688
689 /**
690 * Returns the age of the response in seconds.
691 *
692 * @final
693 */
694 public function getAge(): int
695 {
696 if (null !== $age = $this->headers->get('Age')) {
697 return (int) $age;
698 }
699
700 return max(time() - (int) $this->getDate()->format('U'), 0);
701 }
702
703 /**
704 * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
705 *
706 * @return $this
707 */
708 public function expire(): static
709 {
710 if ($this->isFresh()) {
711 $this->headers->set('Age', $this->getMaxAge());
712 $this->headers->remove('Expires');
713 }
714
715 return $this;
716 }
717
718 /**
719 * Returns the value of the Expires header as a DateTime instance.
720 *
721 * @final
722 */
723 public function getExpires(): ?\DateTimeImmutable
724 {
725 try {
726 return $this->headers->getDate('Expires');
727 } catch (\RuntimeException) {
728 // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
729 return \DateTimeImmutable::createFromFormat('U', time() - 172800);
730 }
731 }
732
733 /**
734 * Sets the Expires HTTP header with a DateTime instance.
735 *
736 * Passing null as value will remove the header.
737 *
738 * @return $this
739 *
740 * @final
741 */
742 public function setExpires(?\DateTimeInterface $date): static
743 {
744 if (null === $date) {
745 $this->headers->remove('Expires');
746
747 return $this;
748 }
749
750 $date = \DateTimeImmutable::createFromInterface($date);
751 $date = $date->setTimezone(new \DateTimeZone('UTC'));
752 $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
753
754 return $this;
755 }
756
757 /**
758 * Returns the number of seconds after the time specified in the response's Date
759 * header when the response should no longer be considered fresh.
760 *
761 * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
762 * back on an expires header. It returns null when no maximum age can be established.
763 *
764 * @final
765 */
766 public function getMaxAge(): ?int
767 {
768 if ($this->headers->hasCacheControlDirective('s-maxage')) {
769 return (int) $this->headers->getCacheControlDirective('s-maxage');
770 }
771
772 if ($this->headers->hasCacheControlDirective('max-age')) {
773 return (int) $this->headers->getCacheControlDirective('max-age');
774 }
775
776 if (null !== $expires = $this->getExpires()) {
777 $maxAge = (int) $expires->format('U') - (int) $this->getDate()->format('U');
778
779 return max($maxAge, 0);
780 }
781
782 return null;
783 }
784
785 /**
786 * Sets the number of seconds after which the response should no longer be considered fresh.
787 *
788 * This method sets the Cache-Control max-age directive.
789 *
790 * @return $this
791 *
792 * @final
793 */
794 public function setMaxAge(int $value): static
795 {
796 $this->headers->addCacheControlDirective('max-age', $value);
797
798 return $this;
799 }
800
801 /**
802 * Sets the number of seconds after which the response should no longer be returned by shared caches when backend is down.
803 *
804 * This method sets the Cache-Control stale-if-error directive.
805 *
806 * @return $this
807 *
808 * @final
809 */
810 public function setStaleIfError(int $value): static
811 {
812 $this->headers->addCacheControlDirective('stale-if-error', $value);
813
814 return $this;
815 }
816
817 /**
818 * Sets the number of seconds after which the response should no longer return stale content by shared caches.
819 *
820 * This method sets the Cache-Control stale-while-revalidate directive.
821 *
822 * @return $this
823 *
824 * @final
825 */
826 public function setStaleWhileRevalidate(int $value): static
827 {
828 $this->headers->addCacheControlDirective('stale-while-revalidate', $value);
829
830 return $this;
831 }
832
833 /**
834 * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
835 *
836 * This method sets the Cache-Control s-maxage directive.
837 *
838 * @return $this
839 *
840 * @final
841 */
842 public function setSharedMaxAge(int $value): static
843 {
844 $this->setPublic();
845 $this->headers->addCacheControlDirective('s-maxage', $value);
846
847 return $this;
848 }
849
850 /**
851 * Returns the response's time-to-live in seconds.
852 *
853 * It returns null when no freshness information is present in the response.
854 *
855 * When the response's TTL is 0, the response may not be served from cache without first
856 * revalidating with the origin.
857 *
858 * @final
859 */
860 public function getTtl(): ?int
861 {
862 $maxAge = $this->getMaxAge();
863
864 return null !== $maxAge ? max($maxAge - $this->getAge(), 0) : null;
865 }
866
867 /**
868 * Sets the response's time-to-live for shared caches in seconds.
869 *
870 * This method adjusts the Cache-Control/s-maxage directive.
871 *
872 * @return $this
873 *
874 * @final
875 */
876 public function setTtl(int $seconds): static
877 {
878 $this->setSharedMaxAge($this->getAge() + $seconds);
879
880 return $this;
881 }
882
883 /**
884 * Sets the response's time-to-live for private/client caches in seconds.
885 *
886 * This method adjusts the Cache-Control/max-age directive.
887 *
888 * @return $this
889 *
890 * @final
891 */
892 public function setClientTtl(int $seconds): static
893 {
894 $this->setMaxAge($this->getAge() + $seconds);
895
896 return $this;
897 }
898
899 /**
900 * Returns the Last-Modified HTTP header as a DateTime instance.
901 *
902 * @throws \RuntimeException When the HTTP header is not parseable
903 *
904 * @final
905 */
906 public function getLastModified(): ?\DateTimeImmutable
907 {
908 return $this->headers->getDate('Last-Modified');
909 }
910
911 /**
912 * Sets the Last-Modified HTTP header with a DateTime instance.
913 *
914 * Passing null as value will remove the header.
915 *
916 * @return $this
917 *
918 * @final
919 */
920 public function setLastModified(?\DateTimeInterface $date): static
921 {
922 if (null === $date) {
923 $this->headers->remove('Last-Modified');
924
925 return $this;
926 }
927
928 $date = \DateTimeImmutable::createFromInterface($date);
929 $date = $date->setTimezone(new \DateTimeZone('UTC'));
930 $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
931
932 return $this;
933 }
934
935 /**
936 * Returns the literal value of the ETag HTTP header.
937 *
938 * @final
939 */
940 public function getEtag(): ?string
941 {
942 return $this->headers->get('ETag');
943 }
944
945 /**
946 * Sets the ETag value.
947 *
948 * @param string|null $etag The ETag unique identifier or null to remove the header
949 * @param bool $weak Whether you want a weak ETag or not
950 *
951 * @return $this
952 *
953 * @final
954 */
955 public function setEtag(?string $etag, bool $weak = false): static
956 {
957 if (null === $etag) {
958 $this->headers->remove('Etag');
959 } else {
960 if (!str_starts_with($etag, '"')) {
961 $etag = '"'.$etag.'"';
962 }
963
964 $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
965 }
966
967 return $this;
968 }
969
970 /**
971 * Sets the response's cache headers (validation and/or expiration).
972 *
973 * Available options are: must_revalidate, no_cache, no_store, no_transform, public, private, proxy_revalidate, max_age, s_maxage, immutable, last_modified and etag.
974 *
975 * @return $this
976 *
977 * @throws \InvalidArgumentException
978 *
979 * @final
980 */
981 public function setCache(array $options): static
982 {
983 if ($diff = array_diff(array_keys($options), array_keys(self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES))) {
984 throw new \InvalidArgumentException(\sprintf('Response does not support the following options: "%s".', implode('", "', $diff)));
985 }
986
987 if (isset($options['etag'])) {
988 $this->setEtag($options['etag']);
989 }
990
991 if (isset($options['last_modified'])) {
992 $this->setLastModified($options['last_modified']);
993 }
994
995 if (isset($options['max_age'])) {
996 $this->setMaxAge($options['max_age']);
997 }
998
999 if (isset($options['s_maxage'])) {
1000 $this->setSharedMaxAge($options['s_maxage']);
1001 }
1002
1003 if (isset($options['stale_while_revalidate'])) {
1004 $this->setStaleWhileRevalidate($options['stale_while_revalidate']);
1005 }
1006
1007 if (isset($options['stale_if_error'])) {
1008 $this->setStaleIfError($options['stale_if_error']);
1009 }
1010
1011 foreach (self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES as $directive => $hasValue) {
1012 if (!$hasValue && isset($options[$directive])) {
1013 if ($options[$directive]) {
1014 $this->headers->addCacheControlDirective(str_replace('_', '-', $directive));
1015 } else {
1016 $this->headers->removeCacheControlDirective(str_replace('_', '-', $directive));
1017 }
1018 }
1019 }
1020
1021 if (isset($options['public'])) {
1022 if ($options['public']) {
1023 $this->setPublic();
1024 } else {
1025 $this->setPrivate();
1026 }
1027 }
1028
1029 if (isset($options['private'])) {
1030 if ($options['private']) {
1031 $this->setPrivate();
1032 } else {
1033 $this->setPublic();
1034 }
1035 }
1036
1037 return $this;
1038 }
1039
1040 /**
1041 * Modifies the response so that it conforms to the rules defined for a 304 status code.
1042 *
1043 * This sets the status, removes the body, and discards any headers
1044 * that MUST NOT be included in 304 responses.
1045 *
1046 * @return $this
1047 *
1048 * @see https://tools.ietf.org/html/rfc2616#section-10.3.5
1049 *
1050 * @final
1051 */
1052 public function setNotModified(): static
1053 {
1054 $this->setStatusCode(304);
1055 $this->setContent(null);
1056
1057 // remove headers that MUST NOT be included with 304 Not Modified responses
1058 foreach (['Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified'] as $header) {
1059 $this->headers->remove($header);
1060 }
1061
1062 return $this;
1063 }
1064
1065 /**
1066 * Returns true if the response includes a Vary header.
1067 *
1068 * @final
1069 */
1070 public function hasVary(): bool
1071 {
1072 return null !== $this->headers->get('Vary');
1073 }
1074
1075 /**
1076 * Returns an array of header names given in the Vary header.
1077 *
1078 * @final
1079 */
1080 public function getVary(): array
1081 {
1082 if (!$vary = $this->headers->all('Vary')) {
1083 return [];
1084 }
1085
1086 $ret = [];
1087 foreach ($vary as $item) {
1088 $ret[] = preg_split('/[\s,]+/', $item);
1089 }
1090
1091 return array_merge([], ...$ret);
1092 }
1093
1094 /**
1095 * Sets the Vary header.
1096 *
1097 * @param bool $replace Whether to replace the actual value or not (true by default)
1098 *
1099 * @return $this
1100 *
1101 * @final
1102 */
1103 public function setVary(string|array $headers, bool $replace = true): static
1104 {
1105 $this->headers->set('Vary', $headers, $replace);
1106
1107 return $this;
1108 }
1109
1110 /**
1111 * Determines if the Response validators (ETag, Last-Modified) match
1112 * a conditional value specified in the Request.
1113 *
1114 * If the Response is not modified, it sets the status code to 304 and
1115 * removes the actual content by calling the setNotModified() method.
1116 *
1117 * @final
1118 */
1119 public function isNotModified(Request $request): bool
1120 {
1121 if (!$request->isMethodCacheable()) {
1122 return false;
1123 }
1124
1125 $notModified = false;
1126 $lastModified = $this->headers->get('Last-Modified');
1127 $modifiedSince = $request->headers->get('If-Modified-Since');
1128
1129 if (($ifNoneMatchEtags = $request->getETags()) && (null !== $etag = $this->getEtag())) {
1130 if (0 == strncmp($etag, 'W/', 2)) {
1131 $etag = substr($etag, 2);
1132 }
1133
1134 // Use weak comparison as per https://tools.ietf.org/html/rfc7232#section-3.2.
1135 foreach ($ifNoneMatchEtags as $ifNoneMatchEtag) {
1136 if (0 == strncmp($ifNoneMatchEtag, 'W/', 2)) {
1137 $ifNoneMatchEtag = substr($ifNoneMatchEtag, 2);
1138 }
1139
1140 if ($ifNoneMatchEtag === $etag || '*' === $ifNoneMatchEtag) {
1141 $notModified = true;
1142 break;
1143 }
1144 }
1145 }
1146 // Only do If-Modified-Since date comparison when If-None-Match is not present as per https://tools.ietf.org/html/rfc7232#section-3.3.
1147 elseif ($modifiedSince && $lastModified) {
1148 $notModified = strtotime($modifiedSince) >= strtotime($lastModified);
1149 }
1150
1151 if ($notModified) {
1152 $this->setNotModified();
1153 }
1154
1155 return $notModified;
1156 }
1157
1158 /**
1159 * Is response invalid?
1160 *
1161 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
1162 *
1163 * @final
1164 */
1165 public function isInvalid(): bool
1166 {
1167 return $this->statusCode < 100 || $this->statusCode >= 600;
1168 }
1169
1170 /**
1171 * Is response informative?
1172 *
1173 * @final
1174 */
1175 public function isInformational(): bool
1176 {
1177 return $this->statusCode >= 100 && $this->statusCode < 200;
1178 }
1179
1180 /**
1181 * Is response successful?
1182 *
1183 * @final
1184 */
1185 public function isSuccessful(): bool
1186 {
1187 return $this->statusCode >= 200 && $this->statusCode < 300;
1188 }
1189
1190 /**
1191 * Is the response a redirect?
1192 *
1193 * @final
1194 */
1195 public function isRedirection(): bool
1196 {
1197 return $this->statusCode >= 300 && $this->statusCode < 400;
1198 }
1199
1200 /**
1201 * Is there a client error?
1202 *
1203 * @final
1204 */
1205 public function isClientError(): bool
1206 {
1207 return $this->statusCode >= 400 && $this->statusCode < 500;
1208 }
1209
1210 /**
1211 * Was there a server side error?
1212 *
1213 * @final
1214 */
1215 public function isServerError(): bool
1216 {
1217 return $this->statusCode >= 500 && $this->statusCode < 600;
1218 }
1219
1220 /**
1221 * Is the response OK?
1222 *
1223 * @final
1224 */
1225 public function isOk(): bool
1226 {
1227 return 200 === $this->statusCode;
1228 }
1229
1230 /**
1231 * Is the response forbidden?
1232 *
1233 * @final
1234 */
1235 public function isForbidden(): bool
1236 {
1237 return 403 === $this->statusCode;
1238 }
1239
1240 /**
1241 * Is the response a not found error?
1242 *
1243 * @final
1244 */
1245 public function isNotFound(): bool
1246 {
1247 return 404 === $this->statusCode;
1248 }
1249
1250 /**
1251 * Is the response a redirect of some form?
1252 *
1253 * @final
1254 */
1255 public function isRedirect(?string $location = null): bool
1256 {
1257 return \in_array($this->statusCode, [201, 301, 302, 303, 307, 308], true) && (null === $location ?: $location == $this->headers->get('Location'));
1258 }
1259
1260 /**
1261 * Is the response empty?
1262 *
1263 * @final
1264 */
1265 public function isEmpty(): bool
1266 {
1267 return \in_array($this->statusCode, [204, 304], true);
1268 }
1269
1270 /**
1271 * Cleans or flushes output buffers up to target level.
1272 *
1273 * Resulting level can be greater than target level if a non-removable buffer has been encountered.
1274 *
1275 * @final
1276 */
1277 public static function closeOutputBuffers(int $targetLevel, bool $flush): void
1278 {
1279 $status = ob_get_status(true);
1280 $level = \count($status);
1281 $flags = \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE);
1282
1283 while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
1284 if ($flush) {
1285 ob_end_flush();
1286 } else {
1287 ob_end_clean();
1288 }
1289 }
1290 }
1291
1292 /**
1293 * Marks a response as safe according to RFC8674.
1294 *
1295 * @see https://tools.ietf.org/html/rfc8674
1296 */
1297 public function setContentSafe(bool $safe = true): void
1298 {
1299 if ($safe) {
1300 $this->headers->set('Preference-Applied', 'safe');
1301 } elseif ('safe' === $this->headers->get('Preference-Applied')) {
1302 $this->headers->remove('Preference-Applied');
1303 }
1304
1305 $this->setVary('Prefer', false);
1306 }
1307
1308 /**
1309 * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
1310 *
1311 * @see http://support.microsoft.com/kb/323308
1312 *
1313 * @final
1314 */
1315 protected function ensureIEOverSSLCompatibility(Request $request): void
1316 {
1317 if (false !== stripos($this->headers->get('Content-Disposition') ?? '', 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT') ?? '', $match) && true === $request->isSecure()) {
1318 if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
1319 $this->headers->remove('Cache-Control');
1320 }
1321 }
1322 }
1323 }