4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
15 * Response represents an HTTP response.
17 * @author Fabien Potencier <fabien@symfony.com>
21 const HTTP_CONTINUE = 100;
22 const HTTP_SWITCHING_PROTOCOLS = 101;
23 const HTTP_PROCESSING = 102; // RFC2518
24 const HTTP_EARLY_HINTS = 103; // RFC8297
26 const HTTP_CREATED = 201;
27 const HTTP_ACCEPTED = 202;
28 const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
29 const HTTP_NO_CONTENT = 204;
30 const HTTP_RESET_CONTENT = 205;
31 const HTTP_PARTIAL_CONTENT = 206;
32 const HTTP_MULTI_STATUS = 207; // RFC4918
33 const HTTP_ALREADY_REPORTED = 208; // RFC5842
34 const HTTP_IM_USED = 226; // RFC3229
35 const HTTP_MULTIPLE_CHOICES = 300;
36 const HTTP_MOVED_PERMANENTLY = 301;
37 const HTTP_FOUND = 302;
38 const HTTP_SEE_OTHER = 303;
39 const HTTP_NOT_MODIFIED = 304;
40 const HTTP_USE_PROXY = 305;
41 const HTTP_RESERVED = 306;
42 const HTTP_TEMPORARY_REDIRECT = 307;
43 const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238
44 const HTTP_BAD_REQUEST = 400;
45 const HTTP_UNAUTHORIZED = 401;
46 const HTTP_PAYMENT_REQUIRED = 402;
47 const HTTP_FORBIDDEN = 403;
48 const HTTP_NOT_FOUND = 404;
49 const HTTP_METHOD_NOT_ALLOWED = 405;
50 const HTTP_NOT_ACCEPTABLE = 406;
51 const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
52 const HTTP_REQUEST_TIMEOUT = 408;
53 const HTTP_CONFLICT = 409;
54 const HTTP_GONE = 410;
55 const HTTP_LENGTH_REQUIRED = 411;
56 const HTTP_PRECONDITION_FAILED = 412;
57 const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
58 const HTTP_REQUEST_URI_TOO_LONG = 414;
59 const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
60 const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
61 const HTTP_EXPECTATION_FAILED = 417;
62 const HTTP_I_AM_A_TEAPOT = 418; // RFC2324
63 const HTTP_MISDIRECTED_REQUEST = 421; // RFC7540
64 const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
65 const HTTP_LOCKED = 423; // RFC4918
66 const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
71 const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817
72 const HTTP_TOO_EARLY = 425; // RFC-ietf-httpbis-replay-04
73 const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
74 const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
75 const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
76 const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
77 const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
78 const HTTP_INTERNAL_SERVER_ERROR = 500;
79 const HTTP_NOT_IMPLEMENTED = 501;
80 const HTTP_BAD_GATEWAY = 502;
81 const HTTP_SERVICE_UNAVAILABLE = 503;
82 const HTTP_GATEWAY_TIMEOUT = 504;
83 const HTTP_VERSION_NOT_SUPPORTED = 505;
84 const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
85 const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918
86 const HTTP_LOOP_DETECTED = 508; // RFC5842
87 const HTTP_NOT_EXTENDED = 510; // RFC2774
88 const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
91 * @var \Symfony\Component\HttpFoundation\ResponseHeaderBag
108 protected $statusCode;
113 protected $statusText;
121 * Status codes translation table.
123 * The list of codes is complete according to the
124 * {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol (HTTP) Status Code Registry}
125 * (last updated 2016-03-01).
127 * Unless otherwise noted, the status code is defined in RFC2616.
131 public static $statusTexts = array(
133 101 => 'Switching Protocols',
134 102 => 'Processing', // RFC2518
135 103 => 'Early Hints',
139 203 => 'Non-Authoritative Information',
141 205 => 'Reset Content',
142 206 => 'Partial Content',
143 207 => 'Multi-Status', // RFC4918
144 208 => 'Already Reported', // RFC5842
145 226 => 'IM Used', // RFC3229
146 300 => 'Multiple Choices',
147 301 => 'Moved Permanently',
150 304 => 'Not Modified',
152 307 => 'Temporary Redirect',
153 308 => 'Permanent Redirect', // RFC7238
154 400 => 'Bad Request',
155 401 => 'Unauthorized',
156 402 => 'Payment Required',
159 405 => 'Method Not Allowed',
160 406 => 'Not Acceptable',
161 407 => 'Proxy Authentication Required',
162 408 => 'Request Timeout',
165 411 => 'Length Required',
166 412 => 'Precondition Failed',
167 413 => 'Payload Too Large',
168 414 => 'URI Too Long',
169 415 => 'Unsupported Media Type',
170 416 => 'Range Not Satisfiable',
171 417 => 'Expectation Failed',
172 418 => 'I\'m a teapot', // RFC2324
173 421 => 'Misdirected Request', // RFC7540
174 422 => 'Unprocessable Entity', // RFC4918
175 423 => 'Locked', // RFC4918
176 424 => 'Failed Dependency', // RFC4918
177 425 => 'Too Early', // RFC-ietf-httpbis-replay-04
178 426 => 'Upgrade Required', // RFC2817
179 428 => 'Precondition Required', // RFC6585
180 429 => 'Too Many Requests', // RFC6585
181 431 => 'Request Header Fields Too Large', // RFC6585
182 451 => 'Unavailable For Legal Reasons', // RFC7725
183 500 => 'Internal Server Error',
184 501 => 'Not Implemented',
185 502 => 'Bad Gateway',
186 503 => 'Service Unavailable',
187 504 => 'Gateway Timeout',
188 505 => 'HTTP Version Not Supported',
189 506 => 'Variant Also Negotiates', // RFC2295
190 507 => 'Insufficient Storage', // RFC4918
191 508 => 'Loop Detected', // RFC5842
192 510 => 'Not Extended', // RFC2774
193 511 => 'Network Authentication Required', // RFC6585
197 * @param mixed $content The response content, see setContent()
198 * @param int $status The response status code
199 * @param array $headers An array of response headers
201 * @throws \InvalidArgumentException When the HTTP status code is not valid
203 public function __construct($content = '', $status = 200, $headers = array())
205 $this->headers = new ResponseHeaderBag($headers);
206 $this->setContent($content);
207 $this->setStatusCode($status);
208 $this->setProtocolVersion('1.0');
212 * Factory method for chainability.
216 * return Response::create($body, 200)
217 * ->setSharedMaxAge(300);
219 * @param mixed $content The response content, see setContent()
220 * @param int $status The response status code
221 * @param array $headers An array of response headers
225 public static function create($content = '', $status = 200, $headers = array())
227 return new static($content, $status, $headers);
231 * Returns the Response as an HTTP string.
233 * The string representation of the Response is the same as the
234 * one that will be sent to the client only if the prepare() method
235 * has been called before.
237 * @return string The Response as an HTTP string
241 public function __toString()
244 sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
245 $this->headers."\r\n".
250 * Clones the current Response instance.
252 public function __clone()
254 $this->headers = clone $this->headers;
258 * Prepares the Response before it is sent to the client.
260 * This method tweaks the Response to ensure that it is
261 * compliant with RFC 2616. Most of the changes are based on
262 * the Request that is "associated" with this Response.
266 public function prepare(Request $request)
268 $headers = $this->headers;
270 if ($this->isInformational() || $this->isEmpty()) {
271 $this->setContent(null);
272 $headers->remove('Content-Type');
273 $headers->remove('Content-Length');
275 // Content-type based on the Request
276 if (!$headers->has('Content-Type')) {
277 $format = $request->getRequestFormat();
278 if (null !== $format && $mimeType = $request->getMimeType($format)) {
279 $headers->set('Content-Type', $mimeType);
284 $charset = $this->charset ?: 'UTF-8';
285 if (!$headers->has('Content-Type')) {
286 $headers->set('Content-Type', 'text/html; charset='.$charset);
287 } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
289 $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
292 // Fix Content-Length
293 if ($headers->has('Transfer-Encoding')) {
294 $headers->remove('Content-Length');
297 if ($request->isMethod('HEAD')) {
299 $length = $headers->get('Content-Length');
300 $this->setContent(null);
302 $headers->set('Content-Length', $length);
308 if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
309 $this->setProtocolVersion('1.1');
312 // Check if we need to send extra expire info headers
313 if ('1.0' == $this->getProtocolVersion() && false !== strpos($this->headers->get('Cache-Control'), 'no-cache')) {
314 $this->headers->set('pragma', 'no-cache');
315 $this->headers->set('expires', -1);
318 $this->ensureIEOverSSLCompatibility($request);
324 * Sends HTTP headers.
328 public function sendHeaders()
330 // headers have already been sent by the developer
331 if (headers_sent()) {
336 foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
337 foreach ($values as $value) {
338 header($name.': '.$value, false, $this->statusCode);
343 foreach ($this->headers->getCookies() as $cookie) {
344 header('Set-Cookie: '.$cookie->getName().strstr($cookie, '='), false, $this->statusCode);
348 header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
354 * Sends content for the current web response.
358 public function sendContent()
366 * Sends HTTP headers and content.
370 public function send()
372 $this->sendHeaders();
373 $this->sendContent();
375 if (\function_exists('fastcgi_finish_request')) {
376 fastcgi_finish_request();
377 } elseif (!\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true)) {
378 static::closeOutputBuffers(0, true);
385 * Sets the response content.
387 * Valid types are strings, numbers, null, and objects that implement a __toString() method.
389 * @param mixed $content Content that can be cast to string
393 * @throws \UnexpectedValueException
395 public function setContent($content)
397 if (null !== $content && !\is_string($content) && !is_numeric($content) && !\is_callable(array($content, '__toString'))) {
398 throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', \gettype($content)));
401 $this->content = (string) $content;
407 * Gets the current response content.
409 * @return string Content
411 public function getContent()
413 return $this->content;
417 * Sets the HTTP protocol version (1.0 or 1.1).
419 * @param string $version The HTTP protocol version
423 * @final since version 3.2
425 public function setProtocolVersion($version)
427 $this->version = $version;
433 * Gets the HTTP protocol version.
435 * @return string The HTTP protocol version
437 * @final since version 3.2
439 public function getProtocolVersion()
441 return $this->version;
445 * Sets the response status code.
447 * If the status text is null it will be automatically populated for the known
448 * status codes and left empty otherwise.
450 * @param int $code HTTP status code
451 * @param mixed $text HTTP status text
455 * @throws \InvalidArgumentException When the HTTP status code is not valid
457 * @final since version 3.2
459 public function setStatusCode($code, $text = null)
461 $this->statusCode = $code = (int) $code;
462 if ($this->isInvalid()) {
463 throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
466 if (null === $text) {
467 $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknown status';
472 if (false === $text) {
473 $this->statusText = '';
478 $this->statusText = $text;
484 * Retrieves the status code for the current web response.
486 * @return int Status code
488 * @final since version 3.2
490 public function getStatusCode()
492 return $this->statusCode;
496 * Sets the response charset.
498 * @param string $charset Character set
502 * @final since version 3.2
504 public function setCharset($charset)
506 $this->charset = $charset;
512 * Retrieves the response charset.
514 * @return string Character set
516 * @final since version 3.2
518 public function getCharset()
520 return $this->charset;
524 * Returns true if the response may safely be kept in a shared (surrogate) cache.
526 * Responses marked "private" with an explicit Cache-Control directive are
527 * considered uncacheable.
529 * Responses with neither a freshness lifetime (Expires, max-age) nor cache
530 * validator (Last-Modified, ETag) are considered uncacheable because there is
531 * no way to tell when or how to remove them from the cache.
533 * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
534 * for example "status codes that are defined as cacheable by default [...]
535 * can be reused by a cache with heuristic expiration unless otherwise indicated"
536 * (https://tools.ietf.org/html/rfc7231#section-6.1)
538 * @return bool true if the response is worth caching, false otherwise
540 * @final since version 3.3
542 public function isCacheable()
544 if (!\in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
548 if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
552 return $this->isValidateable() || $this->isFresh();
556 * Returns true if the response is "fresh".
558 * Fresh responses may be served from cache without any interaction with the
559 * origin. A response is considered fresh when it includes a Cache-Control/max-age
560 * indicator or Expires header and the calculated age is less than the freshness lifetime.
562 * @return bool true if the response is fresh, false otherwise
564 * @final since version 3.3
566 public function isFresh()
568 return $this->getTtl() > 0;
572 * Returns true if the response includes headers that can be used to validate
573 * the response with the origin server using a conditional GET request.
575 * @return bool true if the response is validateable, false otherwise
577 * @final since version 3.3
579 public function isValidateable()
581 return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
585 * Marks the response as "private".
587 * It makes the response ineligible for serving other clients.
591 * @final since version 3.2
593 public function setPrivate()
595 $this->headers->removeCacheControlDirective('public');
596 $this->headers->addCacheControlDirective('private');
602 * Marks the response as "public".
604 * It makes the response eligible for serving other clients.
608 * @final since version 3.2
610 public function setPublic()
612 $this->headers->addCacheControlDirective('public');
613 $this->headers->removeCacheControlDirective('private');
619 * Marks the response as "immutable".
621 * @param bool $immutable enables or disables the immutable directive
627 public function setImmutable($immutable = true)
630 $this->headers->addCacheControlDirective('immutable');
632 $this->headers->removeCacheControlDirective('immutable');
639 * Returns true if the response is marked as "immutable".
641 * @return bool returns true if the response is marked as "immutable"; otherwise false
645 public function isImmutable()
647 return $this->headers->hasCacheControlDirective('immutable');
651 * Returns true if the response must be revalidated by caches.
653 * This method indicates that the response must not be served stale by a
654 * cache in any circumstance without first revalidating with the origin.
655 * When present, the TTL of the response should not be overridden to be
656 * greater than the value provided by the origin.
658 * @return bool true if the response must be revalidated by a cache, false otherwise
660 * @final since version 3.3
662 public function mustRevalidate()
664 return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
668 * Returns the Date header as a DateTime instance.
670 * @return \DateTime A \DateTime instance
672 * @throws \RuntimeException When the header is not parseable
674 * @final since version 3.2
676 public function getDate()
678 return $this->headers->getDate('Date');
682 * Sets the Date header.
686 * @final since version 3.2
688 public function setDate(\DateTime $date)
690 $date->setTimezone(new \DateTimeZone('UTC'));
691 $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
697 * Returns the age of the response.
699 * @return int The age of the response in seconds
701 * @final since version 3.2
703 public function getAge()
705 if (null !== $age = $this->headers->get('Age')) {
709 return max(time() - $this->getDate()->format('U'), 0);
713 * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
717 public function expire()
719 if ($this->isFresh()) {
720 $this->headers->set('Age', $this->getMaxAge());
721 $this->headers->remove('Expires');
728 * Returns the value of the Expires header as a DateTime instance.
730 * @return \DateTime|null A DateTime instance or null if the header does not exist
732 * @final since version 3.2
734 public function getExpires()
737 return $this->headers->getDate('Expires');
738 } catch (\RuntimeException $e) {
739 // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
740 return \DateTime::createFromFormat(DATE_RFC2822, 'Sat, 01 Jan 00 00:00:00 +0000');
745 * Sets the Expires HTTP header with a DateTime instance.
747 * Passing null as value will remove the header.
749 * @param \DateTime|null $date A \DateTime instance or null to remove the header
753 * @final since version 3.2
755 public function setExpires(\DateTime $date = null)
757 if (null === $date) {
758 $this->headers->remove('Expires');
761 $date->setTimezone(new \DateTimeZone('UTC'));
762 $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
769 * Returns the number of seconds after the time specified in the response's Date
770 * header when the response should no longer be considered fresh.
772 * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
773 * back on an expires header. It returns null when no maximum age can be established.
775 * @return int|null Number of seconds
777 * @final since version 3.2
779 public function getMaxAge()
781 if ($this->headers->hasCacheControlDirective('s-maxage')) {
782 return (int) $this->headers->getCacheControlDirective('s-maxage');
785 if ($this->headers->hasCacheControlDirective('max-age')) {
786 return (int) $this->headers->getCacheControlDirective('max-age');
789 if (null !== $this->getExpires()) {
790 return $this->getExpires()->format('U') - $this->getDate()->format('U');
795 * Sets the number of seconds after which the response should no longer be considered fresh.
797 * This methods sets the Cache-Control max-age directive.
799 * @param int $value Number of seconds
803 * @final since version 3.2
805 public function setMaxAge($value)
807 $this->headers->addCacheControlDirective('max-age', $value);
813 * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
815 * This methods sets the Cache-Control s-maxage directive.
817 * @param int $value Number of seconds
821 * @final since version 3.2
823 public function setSharedMaxAge($value)
826 $this->headers->addCacheControlDirective('s-maxage', $value);
832 * Returns the response's time-to-live in seconds.
834 * It returns null when no freshness information is present in the response.
836 * When the responses TTL is <= 0, the response may not be served from cache without first
837 * revalidating with the origin.
839 * @return int|null The TTL in seconds
841 * @final since version 3.2
843 public function getTtl()
845 if (null !== $maxAge = $this->getMaxAge()) {
846 return $maxAge - $this->getAge();
851 * Sets the response's time-to-live for shared caches.
853 * This method adjusts the Cache-Control/s-maxage directive.
855 * @param int $seconds Number of seconds
859 * @final since version 3.2
861 public function setTtl($seconds)
863 $this->setSharedMaxAge($this->getAge() + $seconds);
869 * Sets the response's time-to-live for private/client caches.
871 * This method adjusts the Cache-Control/max-age directive.
873 * @param int $seconds Number of seconds
877 * @final since version 3.2
879 public function setClientTtl($seconds)
881 $this->setMaxAge($this->getAge() + $seconds);
887 * Returns the Last-Modified HTTP header as a DateTime instance.
889 * @return \DateTime|null A DateTime instance or null if the header does not exist
891 * @throws \RuntimeException When the HTTP header is not parseable
893 * @final since version 3.2
895 public function getLastModified()
897 return $this->headers->getDate('Last-Modified');
901 * Sets the Last-Modified HTTP header with a DateTime instance.
903 * Passing null as value will remove the header.
905 * @param \DateTime|null $date A \DateTime instance or null to remove the header
909 * @final since version 3.2
911 public function setLastModified(\DateTime $date = null)
913 if (null === $date) {
914 $this->headers->remove('Last-Modified');
917 $date->setTimezone(new \DateTimeZone('UTC'));
918 $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
925 * Returns the literal value of the ETag HTTP header.
927 * @return string|null The ETag HTTP header or null if it does not exist
929 * @final since version 3.2
931 public function getEtag()
933 return $this->headers->get('ETag');
937 * Sets the ETag value.
939 * @param string|null $etag The ETag unique identifier or null to remove the header
940 * @param bool $weak Whether you want a weak ETag or not
944 * @final since version 3.2
946 public function setEtag($etag = null, $weak = false)
948 if (null === $etag) {
949 $this->headers->remove('Etag');
951 if (0 !== strpos($etag, '"')) {
952 $etag = '"'.$etag.'"';
955 $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
962 * Sets the response's cache headers (validation and/or expiration).
964 * Available options are: etag, last_modified, max_age, s_maxage, private, public and immutable.
966 * @param array $options An array of cache options
970 * @throws \InvalidArgumentException
972 * @final since version 3.3
974 public function setCache(array $options)
976 if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'))) {
977 throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff)));
980 if (isset($options['etag'])) {
981 $this->setEtag($options['etag']);
984 if (isset($options['last_modified'])) {
985 $this->setLastModified($options['last_modified']);
988 if (isset($options['max_age'])) {
989 $this->setMaxAge($options['max_age']);
992 if (isset($options['s_maxage'])) {
993 $this->setSharedMaxAge($options['s_maxage']);
996 if (isset($options['public'])) {
997 if ($options['public']) {
1000 $this->setPrivate();
1004 if (isset($options['private'])) {
1005 if ($options['private']) {
1006 $this->setPrivate();
1012 if (isset($options['immutable'])) {
1013 $this->setImmutable((bool) $options['immutable']);
1020 * Modifies the response so that it conforms to the rules defined for a 304 status code.
1022 * This sets the status, removes the body, and discards any headers
1023 * that MUST NOT be included in 304 responses.
1027 * @see http://tools.ietf.org/html/rfc2616#section-10.3.5
1029 * @final since version 3.3
1031 public function setNotModified()
1033 $this->setStatusCode(304);
1034 $this->setContent(null);
1036 // remove headers that MUST NOT be included with 304 Not Modified responses
1037 foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
1038 $this->headers->remove($header);
1045 * Returns true if the response includes a Vary header.
1047 * @return bool true if the response includes a Vary header, false otherwise
1049 * @final since version 3.2
1051 public function hasVary()
1053 return null !== $this->headers->get('Vary');
1057 * Returns an array of header names given in the Vary header.
1059 * @return array An array of Vary names
1061 * @final since version 3.2
1063 public function getVary()
1065 if (!$vary = $this->headers->get('Vary', null, false)) {
1070 foreach ($vary as $item) {
1071 $ret = array_merge($ret, preg_split('/[\s,]+/', $item));
1078 * Sets the Vary header.
1080 * @param string|array $headers
1081 * @param bool $replace Whether to replace the actual value or not (true by default)
1085 * @final since version 3.2
1087 public function setVary($headers, $replace = true)
1089 $this->headers->set('Vary', $headers, $replace);
1095 * Determines if the Response validators (ETag, Last-Modified) match
1096 * a conditional value specified in the Request.
1098 * If the Response is not modified, it sets the status code to 304 and
1099 * removes the actual content by calling the setNotModified() method.
1101 * @return bool true if the Response validators match the Request, false otherwise
1103 * @final since version 3.3
1105 public function isNotModified(Request $request)
1107 if (!$request->isMethodCacheable()) {
1111 $notModified = false;
1112 $lastModified = $this->headers->get('Last-Modified');
1113 $modifiedSince = $request->headers->get('If-Modified-Since');
1115 if ($etags = $request->getETags()) {
1116 $notModified = \in_array($this->getEtag(), $etags) || \in_array('*', $etags);
1119 if ($modifiedSince && $lastModified) {
1120 $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified);
1124 $this->setNotModified();
1127 return $notModified;
1131 * Is response invalid?
1135 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
1137 * @final since version 3.2
1139 public function isInvalid()
1141 return $this->statusCode < 100 || $this->statusCode >= 600;
1145 * Is response informative?
1149 * @final since version 3.3
1151 public function isInformational()
1153 return $this->statusCode >= 100 && $this->statusCode < 200;
1157 * Is response successful?
1161 * @final since version 3.2
1163 public function isSuccessful()
1165 return $this->statusCode >= 200 && $this->statusCode < 300;
1169 * Is the response a redirect?
1173 * @final since version 3.2
1175 public function isRedirection()
1177 return $this->statusCode >= 300 && $this->statusCode < 400;
1181 * Is there a client error?
1185 * @final since version 3.2
1187 public function isClientError()
1189 return $this->statusCode >= 400 && $this->statusCode < 500;
1193 * Was there a server side error?
1197 * @final since version 3.3
1199 public function isServerError()
1201 return $this->statusCode >= 500 && $this->statusCode < 600;
1205 * Is the response OK?
1209 * @final since version 3.2
1211 public function isOk()
1213 return 200 === $this->statusCode;
1217 * Is the response forbidden?
1221 * @final since version 3.2
1223 public function isForbidden()
1225 return 403 === $this->statusCode;
1229 * Is the response a not found error?
1233 * @final since version 3.2
1235 public function isNotFound()
1237 return 404 === $this->statusCode;
1241 * Is the response a redirect of some form?
1243 * @param string $location
1247 * @final since version 3.2
1249 public function isRedirect($location = null)
1251 return \in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
1255 * Is the response empty?
1259 * @final since version 3.2
1261 public function isEmpty()
1263 return \in_array($this->statusCode, array(204, 304));
1267 * Cleans or flushes output buffers up to target level.
1269 * Resulting level can be greater than target level if a non-removable buffer has been encountered.
1271 * @param int $targetLevel The target output buffering level
1272 * @param bool $flush Whether to flush or clean the buffers
1274 * @final since version 3.3
1276 public static function closeOutputBuffers($targetLevel, $flush)
1278 $status = ob_get_status(true);
1279 $level = \count($status);
1280 // PHP_OUTPUT_HANDLER_* are not defined on HHVM 3.3
1281 $flags = \defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1;
1283 while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
1293 * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
1295 * @see http://support.microsoft.com/kb/323308
1297 * @final since version 3.3
1299 protected function ensureIEOverSSLCompatibility(Request $request)
1301 if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) {
1302 if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
1303 $this->headers->remove('Cache-Control');