Response.php 11 KB

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