Skip to content

Commit

Permalink
Better parsing with RFC respect
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevinrob committed Jul 29, 2015
1 parent eff86f6 commit 374da39
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
27 changes: 17 additions & 10 deletions src/KeyValueHttpHeader.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

class KeyValueHttpHeader
{
const REGEX_SPLIT = '/^([^=]*)=(.*)$/';

/**
* Take from https://github.com/hapijs/wreck
* and modified for accepting space before and after the "=".
*/
const REGEX_SPLIT = '/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\\\"\/\[\]\?\=\{\}\x7F]+)(?:\s*\=\s*(?:([^\x00-\x20\(\)<>@\,;\:\\\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\\\]|\\\\.)*)\")))?/';

/**
* @var string[]
Expand All @@ -19,15 +24,17 @@ class KeyValueHttpHeader
public function __construct(array $values)
{
foreach ($values as $value) {
// FIXME make it better with the RFC ABNF rule
$exploded = explode(',', $value);

foreach ($exploded as $fragment) {
$matches = [];
if (preg_match(self::REGEX_SPLIT, $fragment, $matches)) {
$this->values[trim($matches[1])] = trim($matches[2]);
} else {
$this->values[trim($fragment)] = true;
$matches = [];
if (preg_match_all(self::REGEX_SPLIT, $value, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$val = '';
if (count($match) == 3) {
$val = $match[2];
} else if (count($match) > 3) {
$val = $match[3];
}

$this->values[$match[1]] = $val;
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/KeyValueHttpHeaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function testBase()
'zero=0',
'nothing = ',
'false = false',
'with-comma=1,yeah=2'
'with-comma=1,yeah="2"'
]
]);

Expand Down

0 comments on commit 374da39

Please sign in to comment.