Skip to content

Commit 7929ea2

Browse files
Merge pull request #19 from mazanax/master
Added ability to get headers as associative array
2 parents 59fa31c + 257fede commit 7929ea2

File tree

3 files changed

+55
-4
lines changed

3 files changed

+55
-4
lines changed

lib/Client.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ public function makeRequest($method, $url, $body = null, $headers = null)
166166
$responseHeaders = substr($response, 0, $headerSize);
167167

168168
$responseHeaders = explode("\n", $responseHeaders);
169+
$responseHeaders = array_map('trim', $responseHeaders);
169170

170171
curl_close($curl);
171172

lib/Response.php

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,53 @@ public function body()
6464
/**
6565
* The response headers
6666
*
67+
* @param bool $assoc
68+
*
6769
* @return array
6870
*/
69-
public function headers()
71+
public function headers($assoc = false)
7072
{
71-
return $this->headers;
73+
if (!$assoc) {
74+
return $this->headers;
75+
}
76+
77+
return $this->prettifyHeaders($this->headers);
78+
}
79+
80+
/**
81+
* Returns response headers as associative array
82+
*
83+
* @param array $headers
84+
*
85+
* @return array
86+
*
87+
* @throws \InvalidArgumentException
88+
*/
89+
private function prettifyHeaders($headers)
90+
{
91+
if (!is_array($headers)) {
92+
throw new \InvalidArgumentException('$headers should be array');
93+
}
94+
95+
return array_reduce(
96+
array_filter($headers),
97+
function ($result, $header) {
98+
if (empty($header)) {
99+
return $result;
100+
}
101+
102+
if (false === strpos($header, ':')) {
103+
$result['Status'] = trim($header);
104+
105+
return $result;
106+
}
107+
108+
list ($key, $value) = explode(':', $header, 2);
109+
$result[trim($key)] = trim($value);
110+
111+
return $result;
112+
},
113+
[]
114+
);
72115
}
73-
}
116+
}

test/unit/ResponseTest.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,11 @@ public function testHeaders()
4141

4242
$this->assertEquals(['Content-Type: text/html'], $response->headers());
4343
}
44-
}
44+
45+
public function testAssociativeHeaders()
46+
{
47+
$response = new Response(null, null, ['Content-Type: text/html', 'HTTP/1.1 200 OK']);
48+
49+
$this->assertEquals(['Content-Type' => 'text/html', 'Status' => 'HTTP/1.1 200 OK'], $response->headers(true));
50+
}
51+
}

0 commit comments

Comments
 (0)