Response.php 30 KB

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