Response.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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\Http\Client;
  15. // This alias is necessary to avoid class name conflicts
  16. // with the deprecated class in this namespace.
  17. use Cake\Http\Cookie\CookieCollection as CookiesCollection;
  18. use Psr\Http\Message\ResponseInterface;
  19. use RuntimeException;
  20. use Zend\Diactoros\MessageTrait;
  21. use Zend\Diactoros\Stream;
  22. /**
  23. * Implements methods for HTTP responses.
  24. *
  25. * All of the following examples assume that `$response` is an
  26. * instance of this class.
  27. *
  28. * ### Get header values
  29. *
  30. * Header names are case-insensitive, but normalized to Title-Case
  31. * when the response is parsed.
  32. *
  33. * ```
  34. * $val = $response->getHeaderLine('content-type');
  35. * ```
  36. *
  37. * Will read the Content-Type header. You can get all set
  38. * headers using:
  39. *
  40. * ```
  41. * $response->getHeaders();
  42. * ```
  43. *
  44. * You can also get at the headers using object access. When getting
  45. * headers with object access, you have to use case-sensitive header
  46. * names:
  47. *
  48. * ```
  49. * $val = $response->headers['Content-Type'];
  50. * ```
  51. *
  52. * ### Get the response body
  53. *
  54. * You can access the response body stream using:
  55. *
  56. * ```
  57. * $content = $response->getBody();
  58. * ```
  59. *
  60. * You can also use object access to get the string version
  61. * of the response body:
  62. *
  63. * ```
  64. * $content = $response->body;
  65. * ```
  66. *
  67. * If your response body is in XML or JSON you can use
  68. * special content type specific accessors to read the decoded data.
  69. * JSON data will be returned as arrays, while XML data will be returned
  70. * as SimpleXML nodes:
  71. *
  72. * ```
  73. * // Get as xml
  74. * $content = $response->xml
  75. * // Get as json
  76. * $content = $response->json
  77. * ```
  78. *
  79. * If the response cannot be decoded, null will be returned.
  80. *
  81. * ### Check the status code
  82. *
  83. * You can access the response status code using:
  84. *
  85. * ```
  86. * $content = $response->getStatusCode();
  87. * ```
  88. *
  89. * You can also use object access:
  90. *
  91. * ```
  92. * $content = $response->code;
  93. * ```
  94. */
  95. class Response extends Message implements ResponseInterface
  96. {
  97. use MessageTrait;
  98. /**
  99. * The status code of the response.
  100. *
  101. * @var int
  102. */
  103. protected $code;
  104. /**
  105. * Cookie Collection instance
  106. *
  107. * @var \Cake\Http\Cookie\CookieCollection
  108. */
  109. protected $cookies;
  110. /**
  111. * The reason phrase for the status code
  112. *
  113. * @var string
  114. */
  115. protected $reasonPhrase;
  116. /**
  117. * Cached decoded XML data.
  118. *
  119. * @var \SimpleXMLElement
  120. */
  121. protected $_xml;
  122. /**
  123. * Cached decoded JSON data.
  124. *
  125. * @var array
  126. */
  127. protected $_json;
  128. /**
  129. * Map of public => property names for __get()
  130. *
  131. * @var array
  132. */
  133. protected $_exposedProperties = [
  134. 'cookies' => '_getCookies',
  135. 'body' => '_getBody',
  136. 'code' => 'code',
  137. 'json' => '_getJson',
  138. 'xml' => '_getXml',
  139. 'headers' => '_getHeaders',
  140. ];
  141. /**
  142. * Constructor
  143. *
  144. * @param array $headers Unparsed headers.
  145. * @param string $body The response body.
  146. */
  147. public function __construct($headers = [], $body = '')
  148. {
  149. $this->_parseHeaders($headers);
  150. if ($this->getHeaderLine('Content-Encoding') === 'gzip') {
  151. $body = $this->_decodeGzipBody($body);
  152. }
  153. $stream = new Stream('php://memory', 'wb+');
  154. $stream->write($body);
  155. $this->stream = $stream;
  156. }
  157. /**
  158. * Uncompress a gzip response.
  159. *
  160. * Looks for gzip signatures, and if gzinflate() exists,
  161. * the body will be decompressed.
  162. *
  163. * @param string $body Gzip encoded body.
  164. * @return string
  165. * @throws \RuntimeException When attempting to decode gzip content without gzinflate.
  166. */
  167. protected function _decodeGzipBody($body)
  168. {
  169. if (!function_exists('gzinflate')) {
  170. throw new RuntimeException('Cannot decompress gzip response body without gzinflate()');
  171. }
  172. $offset = 0;
  173. // Look for gzip 'signature'
  174. if (substr($body, 0, 2) === "\x1f\x8b") {
  175. $offset = 2;
  176. }
  177. // Check the format byte
  178. if (substr($body, $offset, 1) === "\x08") {
  179. return gzinflate(substr($body, $offset + 8));
  180. }
  181. }
  182. /**
  183. * Parses headers if necessary.
  184. *
  185. * - Decodes the status code and reasonphrase.
  186. * - Parses and normalizes header names + values.
  187. *
  188. * @param array $headers Headers to parse.
  189. * @return void
  190. */
  191. protected function _parseHeaders($headers)
  192. {
  193. foreach ($headers as $key => $value) {
  194. if (substr($value, 0, 5) === 'HTTP/') {
  195. preg_match('/HTTP\/([\d.]+) ([0-9]+)(.*)/i', $value, $matches);
  196. $this->protocol = $matches[1];
  197. $this->code = (int)$matches[2];
  198. $this->reasonPhrase = trim($matches[3]);
  199. continue;
  200. }
  201. list($name, $value) = explode(':', $value, 2);
  202. $value = trim($value);
  203. $name = trim($name);
  204. $normalized = strtolower($name);
  205. if (isset($this->headers[$name])) {
  206. $this->headers[$name][] = $value;
  207. } else {
  208. $this->headers[$name] = (array)$value;
  209. $this->headerNames[$normalized] = $name;
  210. }
  211. }
  212. }
  213. /**
  214. * Check if the response was OK
  215. *
  216. * @return bool
  217. */
  218. public function isOk()
  219. {
  220. $codes = [
  221. static::STATUS_OK,
  222. static::STATUS_CREATED,
  223. static::STATUS_ACCEPTED
  224. ];
  225. return in_array($this->code, $codes);
  226. }
  227. /**
  228. * Check if the response had a redirect status code.
  229. *
  230. * @return bool
  231. */
  232. public function isRedirect()
  233. {
  234. $codes = [
  235. static::STATUS_MOVED_PERMANENTLY,
  236. static::STATUS_FOUND,
  237. static::STATUS_SEE_OTHER,
  238. static::STATUS_TEMPORARY_REDIRECT,
  239. ];
  240. return (
  241. in_array($this->code, $codes) &&
  242. $this->getHeaderLine('Location')
  243. );
  244. }
  245. /**
  246. * Get the status code from the response
  247. *
  248. * @return int
  249. * @deprecated 3.3.0 Use getStatusCode() instead.
  250. */
  251. public function statusCode()
  252. {
  253. return $this->code;
  254. }
  255. /**
  256. * {@inheritdoc}
  257. *
  258. * @return int The status code.
  259. */
  260. public function getStatusCode()
  261. {
  262. return $this->code;
  263. }
  264. /**
  265. * {@inheritdoc}
  266. *
  267. * @param int $code The status code to set.
  268. * @param string $reasonPhrase The status reason phrase.
  269. * @return $this A copy of the current object with an updated status code.
  270. */
  271. public function withStatus($code, $reasonPhrase = '')
  272. {
  273. $new = clone $this;
  274. $new->code = $code;
  275. $new->reasonPhrase = $reasonPhrase;
  276. return $new;
  277. }
  278. /**
  279. * {@inheritdoc}
  280. *
  281. * @return string The current reason phrase.
  282. */
  283. public function getReasonPhrase()
  284. {
  285. return $this->reasonPhrase;
  286. }
  287. /**
  288. * Get the encoding if it was set.
  289. *
  290. * @return string|null
  291. * @deprecated 3.3.0 Use getEncoding() instead.
  292. */
  293. public function encoding()
  294. {
  295. return $this->getEncoding();
  296. }
  297. /**
  298. * Get the encoding if it was set.
  299. *
  300. * @return string|null
  301. */
  302. public function getEncoding()
  303. {
  304. $content = $this->getHeaderLine('content-type');
  305. if (!$content) {
  306. return null;
  307. }
  308. preg_match('/charset\s?=\s?[\'"]?([a-z0-9-_]+)[\'"]?/i', $content, $matches);
  309. if (empty($matches[1])) {
  310. return null;
  311. }
  312. return $matches[1];
  313. }
  314. /**
  315. * Read single/multiple header value(s) out.
  316. *
  317. * @param string|null $name The name of the header you want. Leave
  318. * null to get all headers.
  319. * @return mixed Null when the header doesn't exist. An array
  320. * will be returned when getting all headers or when getting
  321. * a header that had multiple values set. Otherwise a string
  322. * will be returned.
  323. * @deprecated 3.3.0 Use getHeader() and getHeaderLine() instead.
  324. */
  325. public function header($name = null)
  326. {
  327. if ($name === null) {
  328. return $this->_getHeaders();
  329. }
  330. $header = $this->getHeader($name);
  331. if (count($header) === 1) {
  332. return $header[0];
  333. }
  334. return $header;
  335. }
  336. /**
  337. * Read single/multiple cookie values out.
  338. *
  339. * *Note* This method will only provide access to cookies that
  340. * were added as part of the constructor. If cookies are added post
  341. * construction they will not be accessible via this method.
  342. *
  343. * @param string|null $name The name of the cookie you want. Leave
  344. * null to get all cookies.
  345. * @param bool $all Get all parts of the cookie. When false only
  346. * the value will be returned.
  347. * @return mixed
  348. * @deprecated 3.3.0 Use getCookie(), getCookieData() or getCookies() instead.
  349. */
  350. public function cookie($name = null, $all = false)
  351. {
  352. if ($name === null) {
  353. return $this->getCookies();
  354. }
  355. if ($all) {
  356. return $this->getCookieData($name);
  357. }
  358. return $this->getCookie($name);
  359. }
  360. /**
  361. * Get the all cookie data.
  362. *
  363. * @return array The cookie data
  364. */
  365. public function getCookies()
  366. {
  367. return $this->_getCookies();
  368. }
  369. /**
  370. * Get the cookie collection from this response.
  371. *
  372. * This method exposes the response's CookieCollection
  373. * instance allowing you to interact with cookie objects directly.
  374. *
  375. * @return \Cake\Http\Cookie\CookieCollection
  376. */
  377. public function getCookieCollection()
  378. {
  379. $this->buildCookieCollection();
  380. return $this->cookies;
  381. }
  382. /**
  383. * Get the value of a single cookie.
  384. *
  385. * @param string $name The name of the cookie value.
  386. * @return string|null Either the cookie's value or null when the cookie is undefined.
  387. */
  388. public function getCookie($name)
  389. {
  390. $this->buildCookieCollection();
  391. if (!$this->cookies->has($name)) {
  392. return null;
  393. }
  394. return $this->cookies->get($name)->getValue();
  395. }
  396. /**
  397. * Get the full data for a single cookie.
  398. *
  399. * @param string $name The name of the cookie value.
  400. * @return array|null Either the cookie's data or null when the cookie is undefined.
  401. */
  402. public function getCookieData($name)
  403. {
  404. $this->buildCookieCollection();
  405. if (!$this->cookies->has($name)) {
  406. return null;
  407. }
  408. return $this->cookies->get($name)->toArrayCompat();
  409. }
  410. /**
  411. * Lazily build the CookieCollection and cookie objects from the response header
  412. *
  413. * @return void
  414. */
  415. protected function buildCookieCollection()
  416. {
  417. if ($this->cookies) {
  418. return;
  419. }
  420. $this->cookies = CookiesCollection::createFromHeader($this->getHeader('Set-Cookie'));
  421. }
  422. /**
  423. * Property accessor for `$this->cookies`
  424. *
  425. * @return array Array of Cookie data.
  426. */
  427. protected function _getCookies()
  428. {
  429. $this->buildCookieCollection();
  430. $cookies = [];
  431. foreach ($this->cookies as $cookie) {
  432. $cookies[$cookie->getName()] = $cookie->toArrayCompat();
  433. }
  434. return $cookies;
  435. }
  436. /**
  437. * Get the HTTP version used.
  438. *
  439. * @return string
  440. * @deprecated 3.3.0 Use getProtocolVersion()
  441. */
  442. public function version()
  443. {
  444. return $this->protocol;
  445. }
  446. /**
  447. * Get the response body.
  448. *
  449. * By passing in a $parser callable, you can get the decoded
  450. * response content back.
  451. *
  452. * For example to get the json data as an object:
  453. *
  454. * ```
  455. * $body = $response->body('json_decode');
  456. * ```
  457. *
  458. * @param callable|null $parser The callback to use to decode
  459. * the response body.
  460. * @return mixed The response body.
  461. */
  462. public function body($parser = null)
  463. {
  464. $stream = $this->stream;
  465. $stream->rewind();
  466. if ($parser) {
  467. return $parser($stream->getContents());
  468. }
  469. return $stream->getContents();
  470. }
  471. /**
  472. * Get the response body as JSON decoded data.
  473. *
  474. * @return array|null
  475. */
  476. protected function _getJson()
  477. {
  478. if ($this->_json) {
  479. return $this->_json;
  480. }
  481. return $this->_json = json_decode($this->_getBody(), true);
  482. }
  483. /**
  484. * Get the response body as XML decoded data.
  485. *
  486. * @return null|\SimpleXMLElement
  487. */
  488. protected function _getXml()
  489. {
  490. if ($this->_xml) {
  491. return $this->_xml;
  492. }
  493. libxml_use_internal_errors();
  494. $data = simplexml_load_string($this->_getBody());
  495. if ($data) {
  496. $this->_xml = $data;
  497. return $this->_xml;
  498. }
  499. return null;
  500. }
  501. /**
  502. * Provides magic __get() support.
  503. *
  504. * @return array
  505. */
  506. protected function _getHeaders()
  507. {
  508. $out = [];
  509. foreach ($this->headers as $key => $values) {
  510. $out[$key] = implode(',', $values);
  511. }
  512. return $out;
  513. }
  514. /**
  515. * Provides magic __get() support.
  516. *
  517. * @return array
  518. */
  519. protected function _getBody()
  520. {
  521. $this->stream->rewind();
  522. return $this->stream->getContents();
  523. }
  524. /**
  525. * Read values as properties.
  526. *
  527. * @param string $name Property name.
  528. * @return mixed
  529. */
  530. public function __get($name)
  531. {
  532. if (!isset($this->_exposedProperties[$name])) {
  533. return false;
  534. }
  535. $key = $this->_exposedProperties[$name];
  536. if (substr($key, 0, 4) === '_get') {
  537. return $this->{$key}();
  538. }
  539. return $this->{$key};
  540. }
  541. /**
  542. * isset/empty test with -> syntax.
  543. *
  544. * @param string $name Property name.
  545. * @return bool
  546. */
  547. public function __isset($name)
  548. {
  549. if (!isset($this->_exposedProperties[$name])) {
  550. return false;
  551. }
  552. $key = $this->_exposedProperties[$name];
  553. if (substr($key, 0, 4) === '_get') {
  554. $val = $this->{$key}();
  555. return $val !== null;
  556. }
  557. return isset($this->{$key});
  558. }
  559. }
  560. // @deprecated Add backwards compat alias.
  561. class_alias('Cake\Http\Client\Response', 'Cake\Network\Http\Response');