Skip to content

Commit 8239b25

Browse files
author
Ben Ramsey
committed
Adding tie-breaker functionality
This allows you to specify a preferred mime-type in the event a tie occurs in the best fit and best fit quality values.
1 parent 70ec4d3 commit 8239b25

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

src/Bitworking/Mimeparse.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,10 @@ public static function quality($mimeType, $ranges)
201201
*
202202
* @param array $supported
203203
* @param string $header
204+
* @param string $tieBreaker In case of a tie, this mime-type is preferred
204205
* @return mixed $mimeType or NULL
205206
*/
206-
public static function bestMatch($supported, $header)
207+
public static function bestMatch($supported, $header, $tieBreaker = null)
207208
{
208209
$parsedHeader = explode(',', $header);
209210

@@ -235,6 +236,18 @@ public static function bestMatch($supported, $header)
235236
array_multisort($weightedMatches);
236237
$a = array_pop($weightedMatches);
237238

239+
// If there's a tie breaker specified, see if we have any ties
240+
// and then break them with the $tieBreaker
241+
if ($tieBreaker) {
242+
array_push($weightedMatches, $a);
243+
$ties = array_filter($weightedMatches, function ($val) use ($a) {
244+
return ($val[0] == $a[0]);
245+
});
246+
if (count($ties) > 1) {
247+
return $tieBreaker;
248+
}
249+
}
250+
238251
return (empty($a[0][0]) ? null : $a[1]);
239252
}
240253

tests/Bitworking/MimeparseTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,4 +191,27 @@ public function testStarSlashStarWithHigherQualityThanMoreSpecificType()
191191

192192
$this->assertEquals('image/jpeg', Mimeparse::bestMatch($supportedMimeTypes, $httpAcceptHeader));
193193
}
194+
195+
/**
196+
* @covers Bitworking\Mimeparse::bestMatch
197+
*/
198+
public function testBestMatchWithTieBreaker()
199+
{
200+
$supportedMimeTypes = array('text/html', 'application/json', 'application/hal+xml', 'application/hal+json');
201+
$httpAcceptHeader = 'application/*, text/*;q=0.8';
202+
203+
$this->assertEquals('application/json', Mimeparse::bestMatch($supportedMimeTypes, $httpAcceptHeader));
204+
$this->assertEquals('application/hal+json', Mimeparse::bestMatch($supportedMimeTypes, $httpAcceptHeader, 'application/hal+json'));
205+
}
206+
207+
/**
208+
* @covers Bitworking\Mimeparse::bestMatch
209+
*/
210+
public function testBestMatchWithTieBreakerAndNoTies()
211+
{
212+
$supportedMimeTypes = array('text/html', 'application/hal+json');
213+
$httpAcceptHeader = 'application/*, text/*;q=0.8';
214+
215+
$this->assertEquals('application/hal+json', Mimeparse::bestMatch($supportedMimeTypes, $httpAcceptHeader, 'application/hal+json'));
216+
}
194217
}

0 commit comments

Comments
 (0)