Skip to content

Commit

Permalink
Add missed fallback to generic language (in LanguageNegotiator) (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
rtm-ctrlz authored Jan 30, 2022
1 parent 450beae commit 9785ce2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Negotiation/LanguageNegotiator.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ protected function match(AcceptHeader $acceptLanguage, AcceptHeader $priority, $
$baseEqual = !strcasecmp($ab, $pb);
$subEqual = !strcasecmp($as, $ps);

if (($ab == '*' || $baseEqual) && ($as === null || $subEqual)) {
if (($ab == '*' || $baseEqual) && ($as === null || $subEqual || null === $ps)) {
$score = 10 * $baseEqual + $subEqual;

return new AcceptMatch($acceptLanguage->getQuality() * $priority->getQuality(), $score, $index);
Expand Down
20 changes: 20 additions & 0 deletions tests/Negotiation/Tests/LanguageNegotiatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ public static function dataProviderForTestGetBest()
array('fr, zh-Hans-CN;q=0.3', array('fr'), 'fr'),
# Quality of source factors
array('en;q=0.5,de', array('de;q=0.3', 'en;q=0.9'), 'en;q=0.9'),
# Generic fallback
array('fr-FR, en-US;q=0.8', array('fr'), 'fr'),
array('fr-FR, en-US;q=0.8', array('fr', 'en-US'), 'fr'),
array('fr-FR, en-US;q=0.8', array('fr-CA', 'en'), 'en'),
);
}

Expand Down Expand Up @@ -78,4 +82,20 @@ public static function dataProviderForTestParseHeader()
array('en; q=0.1, fr; q=0.4, fu; q=0.9, de; q=0.2', array('en; q=0.1', 'fr; q=0.4', 'fu; q=0.9', 'de; q=0.2')),
);
}

/**
* Given a accept header containing specific languages (here 'en-US', 'fr-FR')
* And priorities containing a generic version of that language
* Then the best language is mapped to the generic one here 'fr'
*/
public function testSpecificLanguageAreMappedToGeneric()
{
$acceptLanguageHeader = 'fr-FR, en-US;q=0.8';
$priorities = array('fr');

$acceptHeader = $this->negotiator->getBest($acceptLanguageHeader, $priorities);

$this->assertInstanceOf('Negotiation\AcceptHeader', $acceptHeader);
$this->assertEquals('fr', $acceptHeader->getValue());
}
}

0 comments on commit 9785ce2

Please sign in to comment.