Response.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @since 3.0.0
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Network\Http;
  15. use RuntimeException;
  16. /**
  17. * Implements methods for HTTP responses.
  18. *
  19. * All of the following examples assume that `$response` is an
  20. * instance of this class.
  21. *
  22. * ### Get header values
  23. *
  24. * Header names are case-insensitive, but normalized to Title-Case
  25. * when the response is parsed.
  26. *
  27. * ```
  28. * $val = $response->header('content-type');
  29. * ```
  30. *
  31. * Will read the Content-Type header. You can get all set
  32. * headers using:
  33. *
  34. * ```
  35. * $response->header();
  36. * ```
  37. *
  38. * You can also get at the headers using object access. When getting
  39. * headers with object access, you have to use case-sensitive header
  40. * names:
  41. *
  42. * ```
  43. * $val = $response->headers['Content-Type'];
  44. * ```
  45. *
  46. * ### Get the response body
  47. *
  48. * You can access the response body using:
  49. *
  50. * ```
  51. * $content = $response->body();
  52. * ```
  53. *
  54. * You can also use object access:
  55. *
  56. * ```
  57. * $content = $response->body;
  58. * ```
  59. *
  60. * If your response body is in XML or JSON you can use
  61. * special content type specific accessors to read the decoded data.
  62. * JSON data will be returned as arrays, while XML data will be returned
  63. * as SimpleXML nodes:
  64. *
  65. * ```
  66. * // Get as xml
  67. * $content = $response->xml
  68. * // Get as json
  69. * $content = $response->json
  70. * ```
  71. *
  72. * If the response cannot be decoded, null will be returned.
  73. *
  74. * ### Check the status code
  75. *
  76. * You can access the response status code using:
  77. *
  78. * ```
  79. * $content = $response->statusCode();
  80. * ```
  81. *
  82. * You can also use object access:
  83. *
  84. * ```
  85. * $content = $response->code;
  86. * ```
  87. */
  88. class Response extends Message
  89. {
  90. /**
  91. * The status code of the response.
  92. *
  93. * @var int
  94. */
  95. protected $_code;
  96. /**
  97. * The response body
  98. *
  99. * @var string
  100. */
  101. protected $_body;
  102. /**
  103. * Cached decoded XML data.
  104. *
  105. * @var \SimpleXMLElement
  106. */
  107. protected $_xml;
  108. /**
  109. * Cached decoded JSON data.
  110. *
  111. * @var array
  112. */
  113. protected $_json;
  114. /**
  115. * Map of public => property names for __get()
  116. *
  117. * @var array
  118. */
  119. protected $_exposedProperties = [
  120. 'cookies' => '_cookies',
  121. 'headers' => '_headers',
  122. 'body' => '_body',
  123. 'code' => '_code',
  124. 'json' => '_getJson',
  125. 'xml' => '_getXml'
  126. ];
  127. /**
  128. * Constructor
  129. *
  130. * @param array $headers Unparsed headers.
  131. * @param string $body The response body.
  132. */
  133. public function __construct($headers = [], $body = '')
  134. {
  135. $this->_parseHeaders($headers);
  136. if ($this->header('Content-Encoding') === 'gzip') {
  137. $body = $this->_decodeGzipBody($body);
  138. }
  139. $this->_body = $body;
  140. }
  141. /**
  142. * Uncompress a gzip response.
  143. *
  144. * Looks for gzip signatures, and if gzinflate() exists,
  145. * the body will be decompressed.
  146. *
  147. * @param string $body Gzip encoded body.
  148. * @return string
  149. * @throws \RuntimeException When attempting to decode gzip content without gzinflate.
  150. */
  151. protected function _decodeGzipBody($body)
  152. {
  153. if (!function_exists('gzinflate')) {
  154. throw new RuntimeException('Cannot decompress gzip response body without gzinflate()');
  155. }
  156. $offset = 0;
  157. // Look for gzip 'signature'
  158. if (substr($body, 0, 2) === "\x1f\x8b") {
  159. $offset = 2;
  160. }
  161. // Check the format byte
  162. if (substr($body, $offset, 1) === "\x08") {
  163. return gzinflate(substr($body, $offset + 8));
  164. }
  165. }
  166. /**
  167. * Parses headers if necessary.
  168. *
  169. * - Decodes the status code.
  170. * - Parses and normalizes header names + values.
  171. *
  172. * @param array $headers Headers to parse.
  173. * @return void
  174. */
  175. protected function _parseHeaders($headers)
  176. {
  177. foreach ($headers as $key => $value) {
  178. if (substr($value, 0, 5) === 'HTTP/') {
  179. preg_match('/HTTP\/([\d.]+) ([0-9]+)/i', $value, $matches);
  180. $this->_version = $matches[1];
  181. $this->_code = $matches[2];
  182. continue;
  183. }
  184. list($name, $value) = explode(':', $value, 2);
  185. $value = trim($value);
  186. $name = $this->_normalizeHeader($name);
  187. if ($name === 'Set-Cookie') {
  188. $this->_parseCookie($value);
  189. }
  190. if (isset($this->_headers[$name])) {
  191. $this->_headers[$name] = (array)$this->_headers[$name];
  192. $this->_headers[$name][] = $value;
  193. } else {
  194. $this->_headers[$name] = $value;
  195. }
  196. }
  197. }
  198. /**
  199. * Parse a cookie header into data.
  200. *
  201. * @param string $value The cookie value to parse.
  202. * @return void
  203. */
  204. protected function _parseCookie($value)
  205. {
  206. $value = rtrim($value, ';');
  207. $nestedSemi = '";"';
  208. if (strpos($value, $nestedSemi) !== false) {
  209. $value = str_replace($nestedSemi, "{__cookie_replace__}", $value);
  210. $parts = explode(';', $value);
  211. $parts = str_replace("{__cookie_replace__}", $nestedSemi, $parts);
  212. } else {
  213. $parts = preg_split('/\;[ \t]*/', $value);
  214. }
  215. $name = false;
  216. foreach ($parts as $i => $part) {
  217. if (strpos($part, '=') !== false) {
  218. list($key, $value) = explode('=', $part, 2);
  219. } else {
  220. $key = $part;
  221. $value = true;
  222. }
  223. if ($i === 0) {
  224. $name = $key;
  225. $cookie['value'] = $value;
  226. continue;
  227. }
  228. $key = strtolower($key);
  229. if (!isset($cookie[$key])) {
  230. $cookie[$key] = $value;
  231. }
  232. }
  233. $cookie['name'] = $name;
  234. $this->_cookies[$name] = $cookie;
  235. }
  236. /**
  237. * Check if the response was OK
  238. *
  239. * @return bool
  240. */
  241. public function isOk()
  242. {
  243. $codes = [
  244. static::STATUS_OK,
  245. static::STATUS_CREATED,
  246. static::STATUS_ACCEPTED
  247. ];
  248. return in_array($this->_code, $codes);
  249. }
  250. /**
  251. * Check if the response had a redirect status code.
  252. *
  253. * @return bool
  254. */
  255. public function isRedirect()
  256. {
  257. $codes = [
  258. static::STATUS_MOVED_PERMANENTLY,
  259. static::STATUS_FOUND,
  260. static::STATUS_SEE_OTHER,
  261. static::STATUS_TEMPORARY_REDIRECT,
  262. ];
  263. return (
  264. in_array($this->_code, $codes) &&
  265. $this->header('Location')
  266. );
  267. }
  268. /**
  269. * Get the status code from the response
  270. *
  271. * @return int
  272. */
  273. public function statusCode()
  274. {
  275. return $this->_code;
  276. }
  277. /**
  278. * Get the encoding if it was set.
  279. *
  280. * @return string|null
  281. */
  282. public function encoding()
  283. {
  284. $content = $this->header('content-type');
  285. if (!$content) {
  286. return null;
  287. }
  288. preg_match('/charset\s?=\s?[\'"]?([a-z0-9-_]+)[\'"]?/i', $content, $matches);
  289. if (empty($matches[1])) {
  290. return null;
  291. }
  292. return $matches[1];
  293. }
  294. /**
  295. * Read single/multiple header value(s) out.
  296. *
  297. * @param string|null $name The name of the header you want. Leave
  298. * null to get all headers.
  299. * @return mixed Null when the header doesn't exist. An array
  300. * will be returned when getting all headers or when getting
  301. * a header that had multiple values set. Otherwise a string
  302. * will be returned.
  303. */
  304. public function header($name = null)
  305. {
  306. if ($name === null) {
  307. return $this->_headers;
  308. }
  309. $name = $this->_normalizeHeader($name);
  310. if (!isset($this->_headers[$name])) {
  311. return null;
  312. }
  313. return $this->_headers[$name];
  314. }
  315. /**
  316. * Read single/multiple cookie values out.
  317. *
  318. * @param string|null $name The name of the cookie you want. Leave
  319. * null to get all cookies.
  320. * @param bool $all Get all parts of the cookie. When false only
  321. * the value will be returned.
  322. * @return mixed
  323. */
  324. public function cookie($name = null, $all = false)
  325. {
  326. if ($name === null) {
  327. return $this->_cookies;
  328. }
  329. if (!isset($this->_cookies[$name])) {
  330. return null;
  331. }
  332. if ($all) {
  333. return $this->_cookies[$name];
  334. }
  335. return $this->_cookies[$name]['value'];
  336. }
  337. /**
  338. * Get the response body.
  339. *
  340. * By passing in a $parser callable, you can get the decoded
  341. * response content back.
  342. *
  343. * For example to get the json data as an object:
  344. *
  345. * ```
  346. * $body = $response->body('json_decode');
  347. * ```
  348. *
  349. * @param callable|null $parser The callback to use to decode
  350. * the response body.
  351. * @return mixed The response body.
  352. */
  353. public function body($parser = null)
  354. {
  355. if ($parser) {
  356. return $parser($this->_body);
  357. }
  358. return $this->_body;
  359. }
  360. /**
  361. * Get the response body as JSON decoded data.
  362. *
  363. * @return mixed
  364. */
  365. protected function _getJson()
  366. {
  367. if (!empty($this->_json)) {
  368. return $this->_json;
  369. }
  370. return $this->_json = json_decode($this->_body, true);
  371. }
  372. /**
  373. * Get the response body as XML decoded data.
  374. *
  375. * @return null|\SimpleXMLElement
  376. */
  377. protected function _getXml()
  378. {
  379. if (!empty($this->_xml)) {
  380. return $this->_xml;
  381. }
  382. libxml_use_internal_errors();
  383. $data = simplexml_load_string($this->_body);
  384. if ($data) {
  385. $this->_xml = $data;
  386. return $this->_xml;
  387. }
  388. return null;
  389. }
  390. /**
  391. * Read values as properties.
  392. *
  393. * @param string $name Property name.
  394. * @return mixed
  395. */
  396. public function __get($name)
  397. {
  398. if (!isset($this->_exposedProperties[$name])) {
  399. return false;
  400. }
  401. $key = $this->_exposedProperties[$name];
  402. if (substr($key, 0, 4) === '_get') {
  403. return $this->{$key}();
  404. }
  405. return $this->{$key};
  406. }
  407. /**
  408. * isset/empty test with -> syntax.
  409. *
  410. * @param string $name Property name.
  411. * @return bool
  412. */
  413. public function __isset($name)
  414. {
  415. if (!isset($this->_exposedProperties[$name])) {
  416. return false;
  417. }
  418. $key = $this->_exposedProperties[$name];
  419. if (substr($key, 0, 4) === '_get') {
  420. $val = $this->{$key}();
  421. return $val !== null;
  422. }
  423. return isset($this->$key);
  424. }
  425. }