Skip to content

Commit

Permalink
Fix incorrect behavior related to priorities
Browse files Browse the repository at this point in the history
Fix #24
  • Loading branch information
willdurand committed Feb 26, 2014
1 parent 1fb776e commit cda64e2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
19 changes: 19 additions & 0 deletions src/Negotiation/FormatNegotiator.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,15 @@ public function getBest($header, array $priorities = array())
$acceptHeaders = $this->parseHeader($header);
$priorities = $this->sanitize($priorities);
$catchAllEnabled = $this->isCatchAllEnabled($priorities);
$catchAllHeader = null;

foreach ($acceptHeaders as $accept) {
$mimeType = $accept->getValue();

if (self::CATCH_ALL_VALUE === $mimeType) {
$catchAllHeader = $accept;
}

if ('/*' !== substr($mimeType, -2)) {
if (in_array($mimeType, $priorities)) {
return $accept;
Expand Down Expand Up @@ -68,6 +73,20 @@ public function getBest($header, array $priorities = array())
}
}

// if client sends `*/*` in Accept header, and nothing has been negotiated before
// then, return the first priority value if available
if (null !== $catchAllHeader) {
$value = array_shift($priorities);

if (null !== $value && self::CATCH_ALL_VALUE !== $value) {
return new AcceptHeader(
$value,
$catchAllHeader->getQuality(),
$this->parseParameters($catchAllHeader->getValue())
);
}
}

// if `$priorities` is empty or contains a catch-all mime type
if ($catchAllEnabled) {
return array_shift($acceptHeaders) ?: null;
Expand Down
4 changes: 2 additions & 2 deletions tests/Negotiation/Tests/FormatNegotiatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public static function dataProviderForGetBest()
'application/rss+xml',
'*/*',
),
'text/html'
'application/rss+xml'
),
// See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
array(
Expand Down Expand Up @@ -297,7 +297,7 @@ public static function dataProviderForGetBestFormat()
array('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', array(), 'html'),
array('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', array('html', 'json', '*/*'), 'html'),
array('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', array('html', 'json', '*/*'), 'html'),
array('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', array('rss', '*/*'), 'html'),
array('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', array('rss', '*/*'), 'rss'),
array('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', array('xml'), 'xml'),
// This shows clearly that the acceptheader is leading over server priorities
array('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', array('xml', 'html'), 'html'),
Expand Down

0 comments on commit cda64e2

Please sign in to comment.