Response.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. /**
  3. * Slim - a micro PHP 5 framework
  4. *
  5. * @author Josh Lockhart <[email protected]>
  6. * @copyright 2011 Josh Lockhart
  7. * @link http://www.slimframework.com
  8. * @license http://www.slimframework.com/license
  9. * @version 2.2.0
  10. * @package Slim
  11. *
  12. * MIT LICENSE
  13. *
  14. * Permission is hereby granted, free of charge, to any person obtaining
  15. * a copy of this software and associated documentation files (the
  16. * "Software"), to deal in the Software without restriction, including
  17. * without limitation the rights to use, copy, modify, merge, publish,
  18. * distribute, sublicense, and/or sell copies of the Software, and to
  19. * permit persons to whom the Software is furnished to do so, subject to
  20. * the following conditions:
  21. *
  22. * The above copyright notice and this permission notice shall be
  23. * included in all copies or substantial portions of the Software.
  24. *
  25. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. namespace Slim\Http;
  34. /**
  35. * Response
  36. *
  37. * This is a simple abstraction over top an HTTP response. This
  38. * provides methods to set the HTTP status, the HTTP headers,
  39. * and the HTTP body.
  40. *
  41. * @package Slim
  42. * @author Josh Lockhart
  43. * @since 1.0.0
  44. */
  45. class Response implements \ArrayAccess, \Countable, \IteratorAggregate
  46. {
  47. /**
  48. * @var int HTTP status code
  49. */
  50. protected $status;
  51. /**
  52. * @var \Slim\Http\Headers List of HTTP response headers
  53. */
  54. protected $header;
  55. /**
  56. * @var string HTTP response body
  57. */
  58. protected $body;
  59. /**
  60. * @var int Length of HTTP response body
  61. */
  62. protected $length;
  63. /**
  64. * @var array HTTP response codes and messages
  65. */
  66. protected static $messages = array(
  67. //Informational 1xx
  68. 100 => '100 Continue',
  69. 101 => '101 Switching Protocols',
  70. //Successful 2xx
  71. 200 => '200 OK',
  72. 201 => '201 Created',
  73. 202 => '202 Accepted',
  74. 203 => '203 Non-Authoritative Information',
  75. 204 => '204 No Content',
  76. 205 => '205 Reset Content',
  77. 206 => '206 Partial Content',
  78. //Redirection 3xx
  79. 300 => '300 Multiple Choices',
  80. 301 => '301 Moved Permanently',
  81. 302 => '302 Found',
  82. 303 => '303 See Other',
  83. 304 => '304 Not Modified',
  84. 305 => '305 Use Proxy',
  85. 306 => '306 (Unused)',
  86. 307 => '307 Temporary Redirect',
  87. //Client Error 4xx
  88. 400 => '400 Bad Request',
  89. 401 => '401 Unauthorized',
  90. 402 => '402 Payment Required',
  91. 403 => '403 Forbidden',
  92. 404 => '404 Not Found',
  93. 405 => '405 Method Not Allowed',
  94. 406 => '406 Not Acceptable',
  95. 407 => '407 Proxy Authentication Required',
  96. 408 => '408 Request Timeout',
  97. 409 => '409 Conflict',
  98. 410 => '410 Gone',
  99. 411 => '411 Length Required',
  100. 412 => '412 Precondition Failed',
  101. 413 => '413 Request Entity Too Large',
  102. 414 => '414 Request-URI Too Long',
  103. 415 => '415 Unsupported Media Type',
  104. 416 => '416 Requested Range Not Satisfiable',
  105. 417 => '417 Expectation Failed',
  106. 422 => '422 Unprocessable Entity',
  107. 423 => '423 Locked',
  108. //Server Error 5xx
  109. 500 => '500 Internal Server Error',
  110. 501 => '501 Not Implemented',
  111. 502 => '502 Bad Gateway',
  112. 503 => '503 Service Unavailable',
  113. 504 => '504 Gateway Timeout',
  114. 505 => '505 HTTP Version Not Supported'
  115. );
  116. /**
  117. * Constructor
  118. * @param string $body The HTTP response body
  119. * @param int $status The HTTP response status
  120. * @param \Slim\Http\Headers|array $header The HTTP response headers
  121. */
  122. public function __construct($body = '', $status = 200, $header = array())
  123. {
  124. $this->status = (int) $status;
  125. $headers = array();
  126. foreach ($header as $key => $value) {
  127. $headers[$key] = $value;
  128. }
  129. $this->header = new Headers(array_merge(array('Content-Type' => 'text/html'), $headers));
  130. $this->body = '';
  131. $this->write($body);
  132. }
  133. /**
  134. * Get and set status
  135. * @param int|null $status
  136. * @return int
  137. */
  138. public function status($status = null)
  139. {
  140. if (!is_null($status)) {
  141. $this->status = (int) $status;
  142. }
  143. return $this->status;
  144. }
  145. /**
  146. * Get and set header
  147. * @param string $name Header name
  148. * @param string|null $value Header value
  149. * @return string Header value
  150. */
  151. public function header($name, $value = null)
  152. {
  153. if (!is_null($value)) {
  154. $this[$name] = $value;
  155. }
  156. return $this[$name];
  157. }
  158. /**
  159. * Get headers
  160. * @return \Slim\Http\Headers
  161. */
  162. public function headers()
  163. {
  164. return $this->header;
  165. }
  166. /**
  167. * Get and set body
  168. * @param string|null $body Content of HTTP response body
  169. * @return string
  170. */
  171. public function body($body = null)
  172. {
  173. if (!is_null($body)) {
  174. $this->write($body, true);
  175. }
  176. return $this->body;
  177. }
  178. /**
  179. * Get and set length
  180. * @param int|null $length
  181. * @return int
  182. */
  183. public function length($length = null)
  184. {
  185. if (!is_null($length)) {
  186. $this->length = (int) $length;
  187. }
  188. return $this->length;
  189. }
  190. /**
  191. * Append HTTP response body
  192. * @param string $body Content to append to the current HTTP response body
  193. * @param bool $replace Overwrite existing response body?
  194. * @return string The updated HTTP response body
  195. */
  196. public function write($body, $replace = false)
  197. {
  198. if ($replace) {
  199. $this->body = $body;
  200. } else {
  201. $this->body .= (string) $body;
  202. }
  203. $this->length = strlen($this->body);
  204. return $this->body;
  205. }
  206. /**
  207. * Finalize
  208. *
  209. * This prepares this response and returns an array
  210. * of [status, headers, body]. This array is passed to outer middleware
  211. * if available or directly to the Slim run method.
  212. *
  213. * @return array[int status, array headers, string body]
  214. */
  215. public function finalize()
  216. {
  217. if (in_array($this->status, array(204, 304))) {
  218. unset($this['Content-Type'], $this['Content-Length']);
  219. return array($this->status, $this->header, '');
  220. } else {
  221. return array($this->status, $this->header, $this->body);
  222. }
  223. }
  224. /**
  225. * Set cookie
  226. *
  227. * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie`
  228. * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This
  229. * response's header is passed by reference to the utility class and is directly modified. By not
  230. * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or
  231. * analyze the raw header before the response is ultimately delivered to the HTTP client.
  232. *
  233. * @param string $name The name of the cookie
  234. * @param string|array $value If string, the value of cookie; if array, properties for
  235. * cookie including: value, expire, path, domain, secure, httponly
  236. */
  237. public function setCookie($name, $value)
  238. {
  239. Util::setCookieHeader($this->header, $name, $value);
  240. }
  241. /**
  242. * Delete cookie
  243. *
  244. * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie`
  245. * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This
  246. * response's header is passed by reference to the utility class and is directly modified. By not
  247. * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or
  248. * analyze the raw header before the response is ultimately delivered to the HTTP client.
  249. *
  250. * This method will set a cookie with the given name that has an expiration time in the past; this will
  251. * prompt the HTTP client to invalidate and remove the client-side cookie. Optionally, you may
  252. * also pass a key/value array as the second argument. If the "domain" key is present in this
  253. * array, only the Cookie with the given name AND domain will be removed. The invalidating cookie
  254. * sent with this response will adopt all properties of the second argument.
  255. *
  256. * @param string $name The name of the cookie
  257. * @param array $value Properties for cookie including: value, expire, path, domain, secure, httponly
  258. */
  259. public function deleteCookie($name, $value = array())
  260. {
  261. Util::deleteCookieHeader($this->header, $name, $value);
  262. }
  263. /**
  264. * Redirect
  265. *
  266. * This method prepares this response to return an HTTP Redirect response
  267. * to the HTTP client.
  268. *
  269. * @param string $url The redirect destination
  270. * @param int $status The redirect HTTP status code
  271. */
  272. public function redirect ($url, $status = 302)
  273. {
  274. $this->status = $status;
  275. $this['Location'] = $url;
  276. }
  277. /**
  278. * Helpers: Empty?
  279. * @return bool
  280. */
  281. public function isEmpty()
  282. {
  283. return in_array($this->status, array(201, 204, 304));
  284. }
  285. /**
  286. * Helpers: Informational?
  287. * @return bool
  288. */
  289. public function isInformational()
  290. {
  291. return $this->status >= 100 && $this->status < 200;
  292. }
  293. /**
  294. * Helpers: OK?
  295. * @return bool
  296. */
  297. public function isOk()
  298. {
  299. return $this->status === 200;
  300. }
  301. /**
  302. * Helpers: Successful?
  303. * @return bool
  304. */
  305. public function isSuccessful()
  306. {
  307. return $this->status >= 200 && $this->status < 300;
  308. }
  309. /**
  310. * Helpers: Redirect?
  311. * @return bool
  312. */
  313. public function isRedirect()
  314. {
  315. return in_array($this->status, array(301, 302, 303, 307));
  316. }
  317. /**
  318. * Helpers: Redirection?
  319. * @return bool
  320. */
  321. public function isRedirection()
  322. {
  323. return $this->status >= 300 && $this->status < 400;
  324. }
  325. /**
  326. * Helpers: Forbidden?
  327. * @return bool
  328. */
  329. public function isForbidden()
  330. {
  331. return $this->status === 403;
  332. }
  333. /**
  334. * Helpers: Not Found?
  335. * @return bool
  336. */
  337. public function isNotFound()
  338. {
  339. return $this->status === 404;
  340. }
  341. /**
  342. * Helpers: Client error?
  343. * @return bool
  344. */
  345. public function isClientError()
  346. {
  347. return $this->status >= 400 && $this->status < 500;
  348. }
  349. /**
  350. * Helpers: Server Error?
  351. * @return bool
  352. */
  353. public function isServerError()
  354. {
  355. return $this->status >= 500 && $this->status < 600;
  356. }
  357. /**
  358. * Array Access: Offset Exists
  359. */
  360. public function offsetExists( $offset )
  361. {
  362. return isset($this->header[$offset]);
  363. }
  364. /**
  365. * Array Access: Offset Get
  366. */
  367. public function offsetGet( $offset )
  368. {
  369. if (isset($this->header[$offset])) {
  370. return $this->header[$offset];
  371. } else {
  372. return null;
  373. }
  374. }
  375. /**
  376. * Array Access: Offset Set
  377. */
  378. public function offsetSet($offset, $value)
  379. {
  380. $this->header[$offset] = $value;
  381. }
  382. /**
  383. * Array Access: Offset Unset
  384. */
  385. public function offsetUnset($offset)
  386. {
  387. unset($this->header[$offset]);
  388. }
  389. /**
  390. * Countable: Count
  391. */
  392. public function count()
  393. {
  394. return count($this->header);
  395. }
  396. /**
  397. * Get Iterator
  398. *
  399. * This returns the contained `\Slim\Http\Headers` instance which
  400. * is itself iterable.
  401. *
  402. * @return \Slim\Http\Headers
  403. */
  404. public function getIterator()
  405. {
  406. return $this->header;
  407. }
  408. /**
  409. * Get message for HTTP status code
  410. * @return string|null
  411. */
  412. public static function getMessageForCode($status)
  413. {
  414. if (isset(self::$messages[$status])) {
  415. return self::$messages[$status];
  416. } else {
  417. return null;
  418. }
  419. }
  420. }