vendor/symfony/http-foundation/Response.php line 898

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