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

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