Skip to content

Commit

Permalink
Add Headers::qvalues() to implement content negotiation
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed May 25, 2024
1 parent 943ae36 commit 419224f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 6 deletions.
34 changes: 34 additions & 0 deletions src/main/php/web/Headers.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,40 @@ protected function next($input, &$offset) {
};
}

/**
* Returns a new parser for qvalues headers, e.g.:
*
* `Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5`
*
* @return self
*/
public static function qvalues() {
return new class() extends Headers {
protected function next($input, &$offset) {
$weighted= [];
$q= 1.0;
do {
$s= strcspn($input, ',;', $offset);
$value= ltrim(substr($input, $offset, $s), ' ');
$offset+= $s + 1;

$c= $input[$offset - 1] ?? null;
if (';' === $c) {
$weighted[$value]= (float)(Headers::pairs()->next($input, $offset)['q'] ?? $q);
$c= $input[$offset - 1] ?? null;
} else {
$weighted[$value]= $q;
}

$q-= 0.0001;
} while ($c);

arsort($weighted);
return $weighted;
}
};
}

/**
* Returns a new parser for headers with key/value pairs
*
Expand Down
16 changes: 10 additions & 6 deletions src/test/php/web/unittest/HeadersTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,16 @@ public function refresh($header) {
#[Test]
public function accept() {
Assert::equals(
[
new Parameterized('text/html', []),
new Parameterized('application/json', ['q' => '0.9']),
new Parameterized('*/*', ['q' => '0.8']),
],
Headers::values(Headers::parameterized())->parse('text/html, application/json;q=0.9, */*;q=0.8')
['text/html' => 1.0, 'application/json' => 0.9, '*/*' => 0.8],
Headers::qvalues()->parse('text/html, application/json;q=0.9, */*;q=0.8')
);
}

#[Test]
public function accept_encoding() {
Assert::equals(
['deflate' => 1.0, 'gzip' => 1.0, '*' => 0.5],
Headers::qvalues()->parse('deflate, gzip;q=1.0, *;q=0.5')
);
}

Expand Down

0 comments on commit 419224f

Please sign in to comment.