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

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