Skip to content

Commit

Permalink
Fix normalization header values by trimming in MessageTrait (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
devanych committed May 6, 2023
1 parent 7f0ee00 commit 25e8ef2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/MessageTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use function preg_match;
use function sprintf;
use function strtolower;
use function trim;

/**
* Trait implementing the methods defined in `Psr\Http\Message\MessageInterface`.
Expand Down Expand Up @@ -371,6 +372,8 @@ private function registerProtocolVersion(string $protocol): void
}

/**
* @see https://tools.ietf.org/html/rfc7230#section-3.2
*
* @param mixed $name
* @return string
* @throws InvalidArgumentException for invalid header name.
Expand All @@ -388,6 +391,8 @@ private function normalizeHeaderName($name): string
}

/**
* @see https://tools.ietf.org/html/rfc7230#section-3.2
*
* @param mixed $value
* @return array
* @throws InvalidArgumentException for invalid header name.
Expand All @@ -402,16 +407,20 @@ private function normalizeHeaderValue($value): array
);
}

$normalizedValues = [];

foreach ($value as $v) {
if ((!is_string($v) && !is_numeric($v)) || !preg_match('/^[ \t\x21-\x7E\x80-\xFF]*$/D', (string) $v)) {
throw new InvalidArgumentException(sprintf(
'"%s" is not valid header value.',
(is_object($v) ? get_class($v) : (is_string($v) ? $v : gettype($v)))
));
}

$normalizedValues[] = trim((string) $v, " \t");
}

return $value;
return $normalizedValues;
}

/**
Expand Down
22 changes: 22 additions & 0 deletions tests/MessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,28 @@ public function testGetHeaderLineNotFound(): void
$this->assertSame('', $this->message->getHeaderLine('Name'));
}

/**
* @return array
*/
public function trimmedHeaderValuesProvider(): array
{
return [
[(new Message())->withHeader('Name', [" \t \tValue\t \t "])],
[(new Message())->withHeader('Name', " \t \tValue\t \t ")],
[(new Message())->withAddedHeader('Name', " \t \tValue\t \t ")],
];
}

/**
* @dataProvider trimmedHeaderValuesProvider
*/
public function testHeaderValuesAreTrimmed(Message $message): void
{
$this->assertSame(['Name' => ['Value']], $message->getHeaders());
$this->assertSame('Value', $message->getHeaderLine('name'));
$this->assertSame(['Value'], $message->getHeader('name'));
}

/**
* @return array
*/
Expand Down

0 comments on commit 25e8ef2

Please sign in to comment.