Skip to content

Commit

Permalink
Extract common code into a helper method.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Sep 23, 2016
1 parent cea85d7 commit 95d9b06
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
36 changes: 23 additions & 13 deletions src/Network/Request.php
Expand Up @@ -943,6 +943,21 @@ public function here($base = true)
return $url;
}

/**
* Normalize a header name into the SERVER version.
*
* @param string $name The header name.
* @return string The normalized header name.
*/
protected function normalizeHeaderName($name)
{
$name = str_replace('-', '_', strtoupper($name));
if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
$name = 'HTTP_' . $name;
}
return $name;
}

/**
* Read an HTTP header from the Request information.
*
Expand All @@ -951,11 +966,7 @@ public function here($base = true)
*/
public function header($name)
{
$name = str_replace('-', '_', $name);
if (!in_array(strtoupper($name), ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
$name = 'HTTP_' . $name;
}

$name = $this->normalizeHeaderName($name);
return $this->env($name);
}

Expand Down Expand Up @@ -986,10 +997,7 @@ public function getHeaders()
*/
public function getHeader($name)
{
$name = str_replace('-', '_', strtoupper($name));
if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
$name = 'HTTP_' . $name;
}
$name = $this->normalizeHeaderName($name);
if (isset($this->_environment[$name])) {
return (array)$this->_environment[$name];
}
Expand Down Expand Up @@ -1020,10 +1028,7 @@ public function getHeaderLine($name)
public function withHeader($name, $value)
{
$new = clone $this;
$name = strtoupper(str_replace('-', '_', $name));
if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
$name = 'HTTP_' . $name;
}
$name = $this->normalizeHeaderName($name);
$new->_environment[$name] = $value;

return $new;
Expand Down Expand Up @@ -1051,6 +1056,11 @@ public function withAddedHeader($name, $value)
*/
public function withoutHeader($name)
{
$new = clone $this;
$name = $this->normalizeHeaderName($name);
$new->_environment[$name] = $value;

return $new;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions tests/TestCase/Network/RequestTest.php
Expand Up @@ -1347,9 +1347,11 @@ public function testWithHeader()

$this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged');
$this->assertEquals(999, $new->getHeaderLine('Content-length'), 'new request is correct');
$this->assertEquals(999, $new->header('Content-Length'));

$new = $request->withHeader('Double', ['a']);
$this->assertEquals(['a'], $new->getHeader('Double'), 'List values are overwritten');
$this->assertEquals(['a'], $new->header('Double'), 'headers written in bc way.');
}

/**
Expand Down

0 comments on commit 95d9b06

Please sign in to comment.