Response.php 34 KB

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