removing redundant setter/getter + adding PECL_HTTP like header parsing

This commit is contained in:
Ahmad Nassri
2014-12-17 23:03:20 -05:00
parent c7b73c8316
commit 07aa7ab19f

View File

@@ -5,10 +5,10 @@ namespace Unirest;
class Response class Response
{ {
private $code; public $code;
private $raw_body; public $raw_body;
private $body; public $body;
private $headers; public $headers;
/** /**
* @param int $code response code of the cURL request * @param int $code response code of the cURL request
@@ -18,7 +18,7 @@ class Response
public function __construct($code, $raw_body, $headers) public function __construct($code, $raw_body, $headers)
{ {
$this->code = $code; $this->code = $code;
$this->headers = $this->getHeadersFromCurlResponse($headers); $this->headers = http_parse_headers($headers);
$this->raw_body = $raw_body; $this->raw_body = $raw_body;
$this->body = $raw_body; $this->body = $raw_body;
$json = json_decode($raw_body); $json = json_decode($raw_body);
@@ -27,52 +27,35 @@ class Response
$this->body = $json; $this->body = $json;
} }
} }
}
/** if (!function_exists('http_parse_headers')) {
* Return a property of the response if it exists. function http_parse_headers($raw_headers) {
* Possibilities include: code, raw_body, headers, body (if the response is json-decodable) $headers = array();
* @return mixed $key = '';
*/
public function __get($property)
{
if (property_exists($this, $property)) {
return $this->$property;
}
}
/** foreach(explode("\n", $raw_headers) as $i => $h) {
* Set the properties of this object $h = explode(':', $h, 2);
* @param string $property the property name
* @param mixed $value the property value
*/
public function __set($property, $value)
{
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this; if (isset($h[1])) {
} if (!isset($headers[$h[0]])) {
$headers[$h[0]] = trim($h[1]);
} elseif (is_array($headers[$h[0]])) {
$headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1])));
} else {
$headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1])));
}
/** $key = $h[0];
* Retrieve the cURL response headers from the } else {
* header string and convert it into an array if (substr($h[0], 0, 1) == "\t") {
* @param string $headers header string from cURL response $headers[$key] .= "\r\n\t".trim($h[0]);
* @return array } elseif (!$key){
*/ $headers[0] = trim($h[0]);
private function getHeadersFromCurlResponse($headers) }
{
$result = array();
$headers = explode("\r\n", $headers);
array_shift($headers);
foreach ($headers as $line) {
if (strstr($line, ': ')) {
list($key, $value) = explode(': ', $line);
$result[$key] = $value;
} }
} }
return $result; return $headers;
} }
} }