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

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  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 <[email protected]>
  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.         '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 (=== 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 === 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: '.$cookiefalse$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(0true);
  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.     public function getContent(): string|false
  364.     {
  365.         return $this->content;
  366.     }
  367.     /**
  368.      * Sets the HTTP protocol version (1.0 or 1.1).
  369.      *
  370.      * @return $this
  371.      *
  372.      * @final
  373.      */
  374.     public function setProtocolVersion(string $version): static
  375.     {
  376.         $this->version $version;
  377.         return $this;
  378.     }
  379.     /**
  380.      * Gets the HTTP protocol version.
  381.      *
  382.      * @final
  383.      */
  384.     public function getProtocolVersion(): string
  385.     {
  386.         return $this->version;
  387.     }
  388.     /**
  389.      * Sets the response status code.
  390.      *
  391.      * If the status text is null it will be automatically populated for the known
  392.      * status codes and left empty otherwise.
  393.      *
  394.      * @return $this
  395.      *
  396.      * @throws \InvalidArgumentException When the HTTP status code is not valid
  397.      *
  398.      * @final
  399.      */
  400.     public function setStatusCode(int $codestring $text null): static
  401.     {
  402.         $this->statusCode $code;
  403.         if ($this->isInvalid()) {
  404.             throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.'$code));
  405.         }
  406.         if (null === $text) {
  407.             $this->statusText self::$statusTexts[$code] ?? 'unknown status';
  408.             return $this;
  409.         }
  410.         if (false === $text) {
  411.             $this->statusText '';
  412.             return $this;
  413.         }
  414.         $this->statusText $text;
  415.         return $this;
  416.     }
  417.     /**
  418.      * Retrieves the status code for the current web response.
  419.      *
  420.      * @final
  421.      */
  422.     public function getStatusCode(): int
  423.     {
  424.         return $this->statusCode;
  425.     }
  426.     /**
  427.      * Sets the response charset.
  428.      *
  429.      * @return $this
  430.      *
  431.      * @final
  432.      */
  433.     public function setCharset(string $charset): static
  434.     {
  435.         $this->charset $charset;
  436.         return $this;
  437.     }
  438.     /**
  439.      * Retrieves the response charset.
  440.      *
  441.      * @final
  442.      */
  443.     public function getCharset(): ?string
  444.     {
  445.         return $this->charset;
  446.     }
  447.     /**
  448.      * Returns true if the response may safely be kept in a shared (surrogate) cache.
  449.      *
  450.      * Responses marked "private" with an explicit Cache-Control directive are
  451.      * considered uncacheable.
  452.      *
  453.      * Responses with neither a freshness lifetime (Expires, max-age) nor cache
  454.      * validator (Last-Modified, ETag) are considered uncacheable because there is
  455.      * no way to tell when or how to remove them from the cache.
  456.      *
  457.      * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
  458.      * for example "status codes that are defined as cacheable by default [...]
  459.      * can be reused by a cache with heuristic expiration unless otherwise indicated"
  460.      * (https://tools.ietf.org/html/rfc7231#section-6.1)
  461.      *
  462.      * @final
  463.      */
  464.     public function isCacheable(): bool
  465.     {
  466.         if (!\in_array($this->statusCode, [200203300301302404410])) {
  467.             return false;
  468.         }
  469.         if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
  470.             return false;
  471.         }
  472.         return $this->isValidateable() || $this->isFresh();
  473.     }
  474.     /**
  475.      * Returns true if the response is "fresh".
  476.      *
  477.      * Fresh responses may be served from cache without any interaction with the
  478.      * origin. A response is considered fresh when it includes a Cache-Control/max-age
  479.      * indicator or Expires header and the calculated age is less than the freshness lifetime.
  480.      *
  481.      * @final
  482.      */
  483.     public function isFresh(): bool
  484.     {
  485.         return $this->getTtl() > 0;
  486.     }
  487.     /**
  488.      * Returns true if the response includes headers that can be used to validate
  489.      * the response with the origin server using a conditional GET request.
  490.      *
  491.      * @final
  492.      */
  493.     public function isValidateable(): bool
  494.     {
  495.         return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
  496.     }
  497.     /**
  498.      * Marks the response as "private".
  499.      *
  500.      * It makes the response ineligible for serving other clients.
  501.      *
  502.      * @return $this
  503.      *
  504.      * @final
  505.      */
  506.     public function setPrivate(): static
  507.     {
  508.         $this->headers->removeCacheControlDirective('public');
  509.         $this->headers->addCacheControlDirective('private');
  510.         return $this;
  511.     }
  512.     /**
  513.      * Marks the response as "public".
  514.      *
  515.      * It makes the response eligible for serving other clients.
  516.      *
  517.      * @return $this
  518.      *
  519.      * @final
  520.      */
  521.     public function setPublic(): static
  522.     {
  523.         $this->headers->addCacheControlDirective('public');
  524.         $this->headers->removeCacheControlDirective('private');
  525.         return $this;
  526.     }
  527.     /**
  528.      * Marks the response as "immutable".
  529.      *
  530.      * @return $this
  531.      *
  532.      * @final
  533.      */
  534.     public function setImmutable(bool $immutable true): static
  535.     {
  536.         if ($immutable) {
  537.             $this->headers->addCacheControlDirective('immutable');
  538.         } else {
  539.             $this->headers->removeCacheControlDirective('immutable');
  540.         }
  541.         return $this;
  542.     }
  543.     /**
  544.      * Returns true if the response is marked as "immutable".
  545.      *
  546.      * @final
  547.      */
  548.     public function isImmutable(): bool
  549.     {
  550.         return $this->headers->hasCacheControlDirective('immutable');
  551.     }
  552.     /**
  553.      * Returns true if the response must be revalidated by shared caches once it has become stale.
  554.      *
  555.      * This method indicates that the response must not be served stale by a
  556.      * cache in any circumstance without first revalidating with the origin.
  557.      * When present, the TTL of the response should not be overridden to be
  558.      * greater than the value provided by the origin.
  559.      *
  560.      * @final
  561.      */
  562.     public function mustRevalidate(): bool
  563.     {
  564.         return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
  565.     }
  566.     /**
  567.      * Returns the Date header as a DateTime instance.
  568.      *
  569.      * @throws \RuntimeException When the header is not parseable
  570.      *
  571.      * @final
  572.      */
  573.     public function getDate(): ?\DateTimeInterface
  574.     {
  575.         return $this->headers->getDate('Date');
  576.     }
  577.     /**
  578.      * Sets the Date header.
  579.      *
  580.      * @return $this
  581.      *
  582.      * @final
  583.      */
  584.     public function setDate(\DateTimeInterface $date): static
  585.     {
  586.         if ($date instanceof \DateTime) {
  587.             $date \DateTimeImmutable::createFromMutable($date);
  588.         }
  589.         $date $date->setTimezone(new \DateTimeZone('UTC'));
  590.         $this->headers->set('Date'$date->format('D, d M Y H:i:s').' GMT');
  591.         return $this;
  592.     }
  593.     /**
  594.      * Returns the age of the response in seconds.
  595.      *
  596.      * @final
  597.      */
  598.     public function getAge(): int
  599.     {
  600.         if (null !== $age $this->headers->get('Age')) {
  601.             return (int) $age;
  602.         }
  603.         return max(time() - (int) $this->getDate()->format('U'), 0);
  604.     }
  605.     /**
  606.      * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
  607.      *
  608.      * @return $this
  609.      */
  610.     public function expire(): static
  611.     {
  612.         if ($this->isFresh()) {
  613.             $this->headers->set('Age'$this->getMaxAge());
  614.             $this->headers->remove('Expires');
  615.         }
  616.         return $this;
  617.     }
  618.     /**
  619.      * Returns the value of the Expires header as a DateTime instance.
  620.      *
  621.      * @final
  622.      */
  623.     public function getExpires(): ?\DateTimeInterface
  624.     {
  625.         try {
  626.             return $this->headers->getDate('Expires');
  627.         } catch (\RuntimeException $e) {
  628.             // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
  629.             return \DateTime::createFromFormat('U'time() - 172800);
  630.         }
  631.     }
  632.     /**
  633.      * Sets the Expires HTTP header with a DateTime instance.
  634.      *
  635.      * Passing null as value will remove the header.
  636.      *
  637.      * @return $this
  638.      *
  639.      * @final
  640.      */
  641.     public function setExpires(\DateTimeInterface $date null): static
  642.     {
  643.         if (null === $date) {
  644.             $this->headers->remove('Expires');
  645.             return $this;
  646.         }
  647.         if ($date instanceof \DateTime) {
  648.             $date \DateTimeImmutable::createFromMutable($date);
  649.         }
  650.         $date $date->setTimezone(new \DateTimeZone('UTC'));
  651.         $this->headers->set('Expires'$date->format('D, d M Y H:i:s').' GMT');
  652.         return $this;
  653.     }
  654.     /**
  655.      * Returns the number of seconds after the time specified in the response's Date
  656.      * header when the response should no longer be considered fresh.
  657.      *
  658.      * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
  659.      * back on an expires header. It returns null when no maximum age can be established.
  660.      *
  661.      * @final
  662.      */
  663.     public function getMaxAge(): ?int
  664.     {
  665.         if ($this->headers->hasCacheControlDirective('s-maxage')) {
  666.             return (int) $this->headers->getCacheControlDirective('s-maxage');
  667.         }
  668.         if ($this->headers->hasCacheControlDirective('max-age')) {
  669.             return (int) $this->headers->getCacheControlDirective('max-age');
  670.         }
  671.         if (null !== $this->getExpires()) {
  672.             return (int) $this->getExpires()->format('U') - (int) $this->getDate()->format('U');
  673.         }
  674.         return null;
  675.     }
  676.     /**
  677.      * Sets the number of seconds after which the response should no longer be considered fresh.
  678.      *
  679.      * This methods sets the Cache-Control max-age directive.
  680.      *
  681.      * @return $this
  682.      *
  683.      * @final
  684.      */
  685.     public function setMaxAge(int $value): static
  686.     {
  687.         $this->headers->addCacheControlDirective('max-age'$value);
  688.         return $this;
  689.     }
  690.     /**
  691.      * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
  692.      *
  693.      * This methods sets the Cache-Control s-maxage directive.
  694.      *
  695.      * @return $this
  696.      *
  697.      * @final
  698.      */
  699.     public function setSharedMaxAge(int $value): static
  700.     {
  701.         $this->setPublic();
  702.         $this->headers->addCacheControlDirective('s-maxage'$value);
  703.         return $this;
  704.     }
  705.     /**
  706.      * Returns the response's time-to-live in seconds.
  707.      *
  708.      * It returns null when no freshness information is present in the response.
  709.      *
  710.      * When the responses TTL is <= 0, the response may not be served from cache without first
  711.      * revalidating with the origin.
  712.      *
  713.      * @final
  714.      */
  715.     public function getTtl(): ?int
  716.     {
  717.         $maxAge $this->getMaxAge();
  718.         return null !== $maxAge $maxAge $this->getAge() : null;
  719.     }
  720.     /**
  721.      * Sets the response's time-to-live for shared caches in seconds.
  722.      *
  723.      * This method adjusts the Cache-Control/s-maxage directive.
  724.      *
  725.      * @return $this
  726.      *
  727.      * @final
  728.      */
  729.     public function setTtl(int $seconds): static
  730.     {
  731.         $this->setSharedMaxAge($this->getAge() + $seconds);
  732.         return $this;
  733.     }
  734.     /**
  735.      * Sets the response's time-to-live for private/client caches in seconds.
  736.      *
  737.      * This method adjusts the Cache-Control/max-age directive.
  738.      *
  739.      * @return $this
  740.      *
  741.      * @final
  742.      */
  743.     public function setClientTtl(int $seconds): static
  744.     {
  745.         $this->setMaxAge($this->getAge() + $seconds);
  746.         return $this;
  747.     }
  748.     /**
  749.      * Returns the Last-Modified HTTP header as a DateTime instance.
  750.      *
  751.      * @throws \RuntimeException When the HTTP header is not parseable
  752.      *
  753.      * @final
  754.      */
  755.     public function getLastModified(): ?\DateTimeInterface
  756.     {
  757.         return $this->headers->getDate('Last-Modified');
  758.     }
  759.     /**
  760.      * Sets the Last-Modified HTTP header with a DateTime instance.
  761.      *
  762.      * Passing null as value will remove the header.
  763.      *
  764.      * @return $this
  765.      *
  766.      * @final
  767.      */
  768.     public function setLastModified(\DateTimeInterface $date null): static
  769.     {
  770.         if (null === $date) {
  771.             $this->headers->remove('Last-Modified');
  772.             return $this;
  773.         }
  774.         if ($date instanceof \DateTime) {
  775.             $date \DateTimeImmutable::createFromMutable($date);
  776.         }
  777.         $date $date->setTimezone(new \DateTimeZone('UTC'));
  778.         $this->headers->set('Last-Modified'$date->format('D, d M Y H:i:s').' GMT');
  779.         return $this;
  780.     }
  781.     /**
  782.      * Returns the literal value of the ETag HTTP header.
  783.      *
  784.      * @final
  785.      */
  786.     public function getEtag(): ?string
  787.     {
  788.         return $this->headers->get('ETag');
  789.     }
  790.     /**
  791.      * Sets the ETag value.
  792.      *
  793.      * @param string|null $etag The ETag unique identifier or null to remove the header
  794.      * @param bool        $weak Whether you want a weak ETag or not
  795.      *
  796.      * @return $this
  797.      *
  798.      * @final
  799.      */
  800.     public function setEtag(string $etag nullbool $weak false): static
  801.     {
  802.         if (null === $etag) {
  803.             $this->headers->remove('Etag');
  804.         } else {
  805.             if (!str_starts_with($etag'"')) {
  806.                 $etag '"'.$etag.'"';
  807.             }
  808.             $this->headers->set('ETag', (true === $weak 'W/' '').$etag);
  809.         }
  810.         return $this;
  811.     }
  812.     /**
  813.      * Sets the response's cache headers (validation and/or expiration).
  814.      *
  815.      * Available options are: must_revalidate, no_cache, no_store, no_transform, public, private, proxy_revalidate, max_age, s_maxage, immutable, last_modified and etag.
  816.      *
  817.      * @return $this
  818.      *
  819.      * @throws \InvalidArgumentException
  820.      *
  821.      * @final
  822.      */
  823.     public function setCache(array $options): static
  824.     {
  825.         if ($diff array_diff(array_keys($options), array_keys(self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES))) {
  826.             throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".'implode('", "'$diff)));
  827.         }
  828.         if (isset($options['etag'])) {
  829.             $this->setEtag($options['etag']);
  830.         }
  831.         if (isset($options['last_modified'])) {
  832.             $this->setLastModified($options['last_modified']);
  833.         }
  834.         if (isset($options['max_age'])) {
  835.             $this->setMaxAge($options['max_age']);
  836.         }
  837.         if (isset($options['s_maxage'])) {
  838.             $this->setSharedMaxAge($options['s_maxage']);
  839.         }
  840.         foreach (self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES as $directive => $hasValue) {
  841.             if (!$hasValue && isset($options[$directive])) {
  842.                 if ($options[$directive]) {
  843.                     $this->headers->addCacheControlDirective(str_replace('_''-'$directive));
  844.                 } else {
  845.                     $this->headers->removeCacheControlDirective(str_replace('_''-'$directive));
  846.                 }
  847.             }
  848.         }
  849.         if (isset($options['public'])) {
  850.             if ($options['public']) {
  851.                 $this->setPublic();
  852.             } else {
  853.                 $this->setPrivate();
  854.             }
  855.         }
  856.         if (isset($options['private'])) {
  857.             if ($options['private']) {
  858.                 $this->setPrivate();
  859.             } else {
  860.                 $this->setPublic();
  861.             }
  862.         }
  863.         return $this;
  864.     }
  865.     /**
  866.      * Modifies the response so that it conforms to the rules defined for a 304 status code.
  867.      *
  868.      * This sets the status, removes the body, and discards any headers
  869.      * that MUST NOT be included in 304 responses.
  870.      *
  871.      * @return $this
  872.      *
  873.      * @see https://tools.ietf.org/html/rfc2616#section-10.3.5
  874.      *
  875.      * @final
  876.      */
  877.     public function setNotModified(): static
  878.     {
  879.         $this->setStatusCode(304);
  880.         $this->setContent(null);
  881.         // remove headers that MUST NOT be included with 304 Not Modified responses
  882.         foreach (['Allow''Content-Encoding''Content-Language''Content-Length''Content-MD5''Content-Type''Last-Modified'] as $header) {
  883.             $this->headers->remove($header);
  884.         }
  885.         return $this;
  886.     }
  887.     /**
  888.      * Returns true if the response includes a Vary header.
  889.      *
  890.      * @final
  891.      */
  892.     public function hasVary(): bool
  893.     {
  894.         return null !== $this->headers->get('Vary');
  895.     }
  896.     /**
  897.      * Returns an array of header names given in the Vary header.
  898.      *
  899.      * @final
  900.      */
  901.     public function getVary(): array
  902.     {
  903.         if (!$vary $this->headers->all('Vary')) {
  904.             return [];
  905.         }
  906.         $ret = [];
  907.         foreach ($vary as $item) {
  908.             $ret[] = preg_split('/[\s,]+/'$item);
  909.         }
  910.         return array_merge([], ...$ret);
  911.     }
  912.     /**
  913.      * Sets the Vary header.
  914.      *
  915.      * @param bool $replace Whether to replace the actual value or not (true by default)
  916.      *
  917.      * @return $this
  918.      *
  919.      * @final
  920.      */
  921.     public function setVary(string|array $headersbool $replace true): static
  922.     {
  923.         $this->headers->set('Vary'$headers$replace);
  924.         return $this;
  925.     }
  926.     /**
  927.      * Determines if the Response validators (ETag, Last-Modified) match
  928.      * a conditional value specified in the Request.
  929.      *
  930.      * If the Response is not modified, it sets the status code to 304 and
  931.      * removes the actual content by calling the setNotModified() method.
  932.      *
  933.      * @final
  934.      */
  935.     public function isNotModified(Request $request): bool
  936.     {
  937.         if (!$request->isMethodCacheable()) {
  938.             return false;
  939.         }
  940.         $notModified false;
  941.         $lastModified $this->headers->get('Last-Modified');
  942.         $modifiedSince $request->headers->get('If-Modified-Since');
  943.         if (($ifNoneMatchEtags $request->getETags()) && (null !== $etag $this->getEtag())) {
  944.             if (== strncmp($etag'W/'2)) {
  945.                 $etag substr($etag2);
  946.             }
  947.             // Use weak comparison as per https://tools.ietf.org/html/rfc7232#section-3.2.
  948.             foreach ($ifNoneMatchEtags as $ifNoneMatchEtag) {
  949.                 if (== strncmp($ifNoneMatchEtag'W/'2)) {
  950.                     $ifNoneMatchEtag substr($ifNoneMatchEtag2);
  951.                 }
  952.                 if ($ifNoneMatchEtag === $etag || '*' === $ifNoneMatchEtag) {
  953.                     $notModified true;
  954.                     break;
  955.                 }
  956.             }
  957.         }
  958.         // 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.
  959.         elseif ($modifiedSince && $lastModified) {
  960.             $notModified strtotime($modifiedSince) >= strtotime($lastModified);
  961.         }
  962.         if ($notModified) {
  963.             $this->setNotModified();
  964.         }
  965.         return $notModified;
  966.     }
  967.     /**
  968.      * Is response invalid?
  969.      *
  970.      * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  971.      *
  972.      * @final
  973.      */
  974.     public function isInvalid(): bool
  975.     {
  976.         return $this->statusCode 100 || $this->statusCode >= 600;
  977.     }
  978.     /**
  979.      * Is response informative?
  980.      *
  981.      * @final
  982.      */
  983.     public function isInformational(): bool
  984.     {
  985.         return $this->statusCode >= 100 && $this->statusCode 200;
  986.     }
  987.     /**
  988.      * Is response successful?
  989.      *
  990.      * @final
  991.      */
  992.     public function isSuccessful(): bool
  993.     {
  994.         return $this->statusCode >= 200 && $this->statusCode 300;
  995.     }
  996.     /**
  997.      * Is the response a redirect?
  998.      *
  999.      * @final
  1000.      */
  1001.     public function isRedirection(): bool
  1002.     {
  1003.         return $this->statusCode >= 300 && $this->statusCode 400;
  1004.     }
  1005.     /**
  1006.      * Is there a client error?
  1007.      *
  1008.      * @final
  1009.      */
  1010.     public function isClientError(): bool
  1011.     {
  1012.         return $this->statusCode >= 400 && $this->statusCode 500;
  1013.     }
  1014.     /**
  1015.      * Was there a server side error?
  1016.      *
  1017.      * @final
  1018.      */
  1019.     public function isServerError(): bool
  1020.     {
  1021.         return $this->statusCode >= 500 && $this->statusCode 600;
  1022.     }
  1023.     /**
  1024.      * Is the response OK?
  1025.      *
  1026.      * @final
  1027.      */
  1028.     public function isOk(): bool
  1029.     {
  1030.         return 200 === $this->statusCode;
  1031.     }
  1032.     /**
  1033.      * Is the response forbidden?
  1034.      *
  1035.      * @final
  1036.      */
  1037.     public function isForbidden(): bool
  1038.     {
  1039.         return 403 === $this->statusCode;
  1040.     }
  1041.     /**
  1042.      * Is the response a not found error?
  1043.      *
  1044.      * @final
  1045.      */
  1046.     public function isNotFound(): bool
  1047.     {
  1048.         return 404 === $this->statusCode;
  1049.     }
  1050.     /**
  1051.      * Is the response a redirect of some form?
  1052.      *
  1053.      * @final
  1054.      */
  1055.     public function isRedirect(string $location null): bool
  1056.     {
  1057.         return \in_array($this->statusCode, [201301302303307308]) && (null === $location ?: $location == $this->headers->get('Location'));
  1058.     }
  1059.     /**
  1060.      * Is the response empty?
  1061.      *
  1062.      * @final
  1063.      */
  1064.     public function isEmpty(): bool
  1065.     {
  1066.         return \in_array($this->statusCode, [204304]);
  1067.     }
  1068.     /**
  1069.      * Cleans or flushes output buffers up to target level.
  1070.      *
  1071.      * Resulting level can be greater than target level if a non-removable buffer has been encountered.
  1072.      *
  1073.      * @final
  1074.      */
  1075.     public static function closeOutputBuffers(int $targetLevelbool $flush): void
  1076.     {
  1077.         $status ob_get_status(true);
  1078.         $level \count($status);
  1079.         $flags \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush \PHP_OUTPUT_HANDLER_FLUSHABLE \PHP_OUTPUT_HANDLER_CLEANABLE);
  1080.         while ($level-- > $targetLevel && ($s $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags $s['del'])) {
  1081.             if ($flush) {
  1082.                 ob_end_flush();
  1083.                 flush();
  1084.             } else {
  1085.                 ob_end_clean();
  1086.             }
  1087.         }
  1088.     }
  1089.     /**
  1090.      * Marks a response as safe according to RFC8674.
  1091.      *
  1092.      * @see https://tools.ietf.org/html/rfc8674
  1093.      */
  1094.     public function setContentSafe(bool $safe true): void
  1095.     {
  1096.         if ($safe) {
  1097.             $this->headers->set('Preference-Applied''safe');
  1098.         } elseif ('safe' === $this->headers->get('Preference-Applied')) {
  1099.             $this->headers->remove('Preference-Applied');
  1100.         }
  1101.         $this->setVary('Prefer'false);
  1102.     }
  1103.     /**
  1104.      * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
  1105.      *
  1106.      * @see http://support.microsoft.com/kb/323308
  1107.      *
  1108.      * @final
  1109.      */
  1110.     protected function ensureIEOverSSLCompatibility(Request $request): void
  1111.     {
  1112.         if (false !== stripos($this->headers->get('Content-Disposition') ?? '''attachment') && == preg_match('/MSIE (.*?);/i'$request->server->get('HTTP_USER_AGENT') ?? ''$match) && true === $request->isSecure()) {
  1113.             if ((int) preg_replace('/(MSIE )(.*?);/''$2'$match[0]) < 9) {
  1114.                 $this->headers->remove('Cache-Control');
  1115.             }
  1116.         }
  1117.     }
  1118. }