Response.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. /**
  3. * A parallel HTTP client written in pure PHP
  4. *
  5. * @author hightman <hightman@twomice.net>
  6. * @link http://hightman.cn
  7. * @copyright Copyright (c) 2015 Twomice Studio.
  8. */
  9. namespace hightman\http;
  10. /**
  11. * Http response
  12. *
  13. * @author hightman
  14. * @since 1.0
  15. */
  16. class Response
  17. {
  18. use HeaderTrait;
  19. /**
  20. * @var integer response status code
  21. */
  22. public $status;
  23. /**
  24. * @var string response status line, such as 'Not Found', 'Forbidden' ...
  25. */
  26. public $statusText;
  27. /**
  28. * @var string error message, null if has not error.
  29. */
  30. public $error;
  31. /**
  32. * @var string response body content.
  33. */
  34. public $body;
  35. /**
  36. * @var float time cost to complete this request.
  37. */
  38. public $timeCost;
  39. /**
  40. * @var string raw request url.
  41. */
  42. public $url;
  43. /**
  44. * @var integer number of redirects
  45. */
  46. public $numRedirected = 0;
  47. /**
  48. * Constructor
  49. * @param string $url
  50. */
  51. public function __construct($url)
  52. {
  53. $this->reset();
  54. $this->url = $url;
  55. }
  56. /**
  57. * Convert to string (body)
  58. * @return string
  59. */
  60. public function __toString()
  61. {
  62. return $this->body;
  63. }
  64. /**
  65. * Check has error or not
  66. * @return bool
  67. */
  68. public function hasError()
  69. {
  70. return $this->error !== null;
  71. }
  72. /**
  73. * Reset object
  74. */
  75. public function reset()
  76. {
  77. $this->status = 400;
  78. $this->statusText = 'Bad Request';
  79. $this->body = '';
  80. $this->error = null;
  81. $this->timeCost = 0;
  82. $this->clearHeader();
  83. $this->clearCookie();
  84. }
  85. /**
  86. * Redirect to another url
  87. * This method can be used in request callback.
  88. * @param string $url target url to be redirected to.
  89. */
  90. public function redirect($url)
  91. {
  92. // has redirect from upstream
  93. if (($this->status === 301 || $this->status === 302) && ($this->hasHeader('location'))) {
  94. return;
  95. }
  96. // @fixme need a better solution
  97. $this->numRedirected--;
  98. $this->status = 302;
  99. $this->setHeader('location', $url);
  100. }
  101. /**
  102. * Get json response data
  103. * @return mixed
  104. */
  105. public function getJson()
  106. {
  107. if (stripos($this->getHeader('content-type'), '/json') !== false) {
  108. return json_decode($this->body, true);
  109. } else {
  110. return false;
  111. }
  112. }
  113. }