diff --git a/lib/Client.php b/lib/Client.php index cb9b24f..0f82163 100644 --- a/lib/Client.php +++ b/lib/Client.php @@ -166,6 +166,7 @@ public function makeRequest($method, $url, $body = null, $headers = null) $responseHeaders = substr($response, 0, $headerSize); $responseHeaders = explode("\n", $responseHeaders); + $responseHeaders = array_map('trim', $responseHeaders); curl_close($curl); diff --git a/lib/Response.php b/lib/Response.php index bc04e1f..29720f0 100644 --- a/lib/Response.php +++ b/lib/Response.php @@ -64,10 +64,53 @@ public function body() /** * The response headers * + * @param bool $assoc + * * @return array */ - public function headers() + public function headers($assoc = false) { - return $this->headers; + if (!$assoc) { + return $this->headers; + } + + return $this->prettifyHeaders($this->headers); + } + + /** + * Returns response headers as associative array + * + * @param array $headers + * + * @return array + * + * @throws \InvalidArgumentException + */ + private function prettifyHeaders($headers) + { + if (!is_array($headers)) { + throw new \InvalidArgumentException('$headers should be array'); + } + + return array_reduce( + array_filter($headers), + function ($result, $header) { + if (empty($header)) { + return $result; + } + + if (false === strpos($header, ':')) { + $result['Status'] = trim($header); + + return $result; + } + + list ($key, $value) = explode(':', $header, 2); + $result[trim($key)] = trim($value); + + return $result; + }, + [] + ); } -} \ No newline at end of file +} diff --git a/test/unit/ResponseTest.php b/test/unit/ResponseTest.php index 04bd27b..45660e2 100644 --- a/test/unit/ResponseTest.php +++ b/test/unit/ResponseTest.php @@ -41,4 +41,11 @@ public function testHeaders() $this->assertEquals(['Content-Type: text/html'], $response->headers()); } -} \ No newline at end of file + + public function testAssociativeHeaders() + { + $response = new Response(null, null, ['Content-Type: text/html', 'HTTP/1.1 200 OK']); + + $this->assertEquals(['Content-Type' => 'text/html', 'Status' => 'HTTP/1.1 200 OK'], $response->headers(true)); + } +}