Response.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace EasyWeChat\Kernel\Http;
  11. use EasyWeChat\Kernel\Support\Collection;
  12. use EasyWeChat\Kernel\Support\XML;
  13. use GuzzleHttp\Psr7\Response as GuzzleResponse;
  14. use Psr\Http\Message\ResponseInterface;
  15. /**
  16. * Class Response.
  17. *
  18. * @author overtrue <i@overtrue.me>
  19. */
  20. class Response extends GuzzleResponse
  21. {
  22. /**
  23. * @return string
  24. */
  25. public function getBodyContents()
  26. {
  27. $this->getBody()->rewind();
  28. $contents = $this->getBody()->getContents();
  29. $this->getBody()->rewind();
  30. return $contents;
  31. }
  32. /**
  33. * @param \Psr\Http\Message\ResponseInterface $response
  34. *
  35. * @return \EasyWeChat\Kernel\Http\Response
  36. */
  37. public static function buildFromPsrResponse(ResponseInterface $response)
  38. {
  39. return new static(
  40. $response->getStatusCode(),
  41. $response->getHeaders(),
  42. $response->getBody(),
  43. $response->getProtocolVersion(),
  44. $response->getReasonPhrase()
  45. );
  46. }
  47. /**
  48. * Build to json.
  49. *
  50. * @return string
  51. */
  52. public function toJson()
  53. {
  54. return json_encode($this->toArray());
  55. }
  56. /**
  57. * Build to array.
  58. *
  59. * @return array
  60. */
  61. public function toArray()
  62. {
  63. $content = $this->removeControlCharacters($this->getBodyContents());
  64. if (false !== stripos($this->getHeaderLine('Content-Type'), 'xml') || 0 === stripos($content, '<xml')) {
  65. return XML::parse($content);
  66. }
  67. $array = json_decode($content, true, 512, JSON_BIGINT_AS_STRING);
  68. if (JSON_ERROR_NONE === json_last_error()) {
  69. return (array) $array;
  70. }
  71. return [];
  72. }
  73. /**
  74. * Get collection data.
  75. *
  76. * @return \EasyWeChat\Kernel\Support\Collection
  77. */
  78. public function toCollection()
  79. {
  80. return new Collection($this->toArray());
  81. }
  82. /**
  83. * @return object
  84. */
  85. public function toObject()
  86. {
  87. return json_decode($this->toJson());
  88. }
  89. /**
  90. * @return bool|string
  91. */
  92. public function __toString()
  93. {
  94. return $this->getBodyContents();
  95. }
  96. /**
  97. * @param string $content
  98. *
  99. * @return string
  100. */
  101. protected function removeControlCharacters(string $content)
  102. {
  103. return \preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', $content);
  104. }
  105. }