HttpResponse.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Qiniu\Pili;
  3. class HttpResponse
  4. {
  5. private $code;
  6. private $raw_body;
  7. private $body;
  8. private $headers;
  9. /**
  10. * @param int $code response code of the cURL request
  11. * @param string $raw_body the raw body of the cURL response
  12. * @param string $headers raw header string from cURL response
  13. */
  14. public function __construct($code, $raw_body, $headers)
  15. {
  16. $this->code = $code;
  17. $this->headers = $this->get_headers_from_curl_response($headers);
  18. $this->raw_body = $raw_body;
  19. $this->body = $raw_body;
  20. $json = json_decode($raw_body, true);
  21. if (json_last_error() == JSON_ERROR_NONE) {
  22. $this->body = $json;
  23. }
  24. }
  25. /**
  26. * Return a property of the response if it exists.
  27. * Possibilities include: code, raw_body, headers, body (if the response is json-decodable)
  28. * @return mixed
  29. */
  30. public function __get($property)
  31. {
  32. if (property_exists($this, $property)) {
  33. return $this->$property;
  34. }
  35. }
  36. /**
  37. * Set the properties of this object
  38. * @param string $property the property name
  39. * @param mixed $value the property value
  40. */
  41. public function __set($property, $value)
  42. {
  43. if (property_exists($this, $property)) {
  44. $this->$property = $value;
  45. }
  46. return $this;
  47. }
  48. /**
  49. * Retrieve the cURL response headers from the
  50. * header string and convert it into an array
  51. * @param string $headers header string from cURL response
  52. * @return array
  53. */
  54. private function get_headers_from_curl_response($headers)
  55. {
  56. $headers = explode("\r\n", $headers);
  57. array_shift($headers);
  58. foreach ($headers as $line) {
  59. if (strstr($line, ': ')) {
  60. list($key, $value) = explode(': ', $line);
  61. $result[$key] = $value;
  62. }
  63. }
  64. return $result;
  65. }
  66. }