Response.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Easemob\Http;
  3. /**
  4. * @ignore 响应体类
  5. * @final
  6. */
  7. final class Response
  8. {
  9. /**
  10. * @var int $httpCode http 状态码
  11. */
  12. public $httpCode;
  13. /**
  14. * @var number $duration 响应时长
  15. */
  16. public $duration;
  17. /**
  18. * @var mixed $headers 响应头
  19. */
  20. public $headers;
  21. /**
  22. * @var mixed $body 响应体
  23. */
  24. public $body;
  25. /**
  26. * @var mixed $error 错误信息
  27. */
  28. public $error;
  29. /**
  30. * @var mixed $data 响应数据
  31. */
  32. private $data;
  33. /**
  34. * @var array $statusText 状态码对应信息
  35. */
  36. private static $statusText = array(
  37. 400 => 'Bad Request',
  38. 401 => 'Unauthorized',
  39. 403 => 'Forbidden',
  40. 404 => 'Not Found',
  41. 405 => 'Method Not Allowed',
  42. 408 => 'Request Timeout',
  43. 413 => 'Request Entity Too Large',
  44. 415 => 'Unsupported Media Type',
  45. 429 => 'Too Many Requests',
  46. 500 => 'Internal Server Error',
  47. 501 => 'Not Implemented',
  48. 502 => 'Bad Gateway',
  49. 503 => 'Service Unavailable',
  50. 504 => 'Gateway Timeout',
  51. );
  52. /**
  53. * 构造方法
  54. * @param int $httpCode 状态码
  55. * @param double $duration 执行时间
  56. * @param mixed $headers 响应头
  57. * @param mixed $body 响应体
  58. * @param mixed $error 错误信息
  59. */
  60. public function __construct($httpCode, $duration, $headers = null, $body = null, $error = null)
  61. {
  62. $this->httpCode = $httpCode;
  63. $this->duration = $duration;
  64. $this->headers = $headers;
  65. $this->body = $body;
  66. if ($error !== null) {
  67. return;
  68. }
  69. if ($body !== null) {
  70. $this->data = json_decode($body, true);
  71. $error = isset($this->data['error']) && $this->data['error'] ? $this->data['error'] : $error;
  72. }
  73. if ($error === null) {
  74. $error = isset(self::$statusText[$httpCode]) ? self::$statusText[$httpCode] : $error;
  75. }
  76. $this->error = $error;
  77. }
  78. /**
  79. * 查看请求是否成功
  80. * @return boolean 请求是否成功
  81. */
  82. public function ok()
  83. {
  84. return $this->httpCode >= 200 && $this->httpCode < 300 && $this->error == null;
  85. }
  86. /**
  87. * 获取响应数据
  88. * @return array 响应数据
  89. */
  90. public function data()
  91. {
  92. return $this->data;
  93. }
  94. }