Skip to content

Commit

Permalink
Start to implement header parsing/normalization.
Browse files Browse the repository at this point in the history
There is some intentional copy/paste here until I figure out what can/should be pushed down into a base class.
  • Loading branch information
markstory committed Dec 26, 2012
1 parent c9eba76 commit d70934d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
23 changes: 22 additions & 1 deletion lib/Cake/Network/Http/Response.php
Expand Up @@ -62,6 +62,9 @@ public function __construct($headers, $content) {
/**
* Parses headers if necessary.
*
* - Decodes the status code.
* - Parses and normalizes header names + values.
*
* @param array $headers
*/
protected function _parseHeaders($headers) {
Expand All @@ -73,12 +76,26 @@ protected function _parseHeaders($headers) {
}
if (is_int($key)) {
list($name, $value) = explode(':', $value, 2);
$this->_headers[$name] = $value;
$name = $this->_normalizeHeader($name);
$this->_headers[trim($name)] = trim($value);
continue;
}
}
}

/**
* Normalize header names to Camel-Case form.
*
* @param string $name The header name to normalize.
* @return string Normalized header name.
*/
protected function _normalizeHeader($name) {
$parts = explode('-', $name);
$parts = array_map('strtolower', $parts);
$parts = array_map('ucfirst', $parts);
return implode('-', $parts);
}

/**
* Check if the response was OK
*
Expand Down Expand Up @@ -128,6 +145,10 @@ public function header($name = null) {
if ($name === null) {
return $this->_headers;
}
$name = $this->_normalizeHeader($name);
if (!isset($this->_headers[$name])) {
return null;
}
return $this->_headers[$name];
}

Expand Down
17 changes: 16 additions & 1 deletion lib/Cake/Test/TestCase/Network/Http/ResponseTest.php
Expand Up @@ -22,7 +22,22 @@
class ResponseTest extends TestCase {

public function testHeaderParsing() {
$this->markTestIncomplete();
$headers = [
'HTTP/1.1 200 OK',
'Content-Type : text/html;charset="UTF-8"',
'date: Tue, 25 Dec 2012 04:43:47 GMT',
];
$response = new Response($headers, 'ok');

$this->assertEquals(200, $response->statusCode());
$this->assertEquals(
'text/html;charset="UTF-8"',
$response->header('content-type')
);
$this->assertEquals(
'Tue, 25 Dec 2012 04:43:47 GMT',
$response->header('Date')
);
}

public function testContent() {
Expand Down

0 comments on commit d70934d

Please sign in to comment.