Fixed MediaType::getQuality always returning 1.0.

This commit is contained in:
Pachira 2024-08-18 16:56:17 +00:00
parent 57f8c69ca0
commit 25063f6b1f
3 changed files with 39 additions and 5 deletions

View file

@ -1 +1 @@
0.2408.181640 0.2408.181655

View file

@ -1,7 +1,7 @@
<?php <?php
// MediaType.php // MediaType.php
// Created: 2022-02-10 // Created: 2022-02-10
// Updated: 2024-08-03 // Updated: 2024-08-18
namespace Index; namespace Index;
@ -105,10 +105,12 @@ class MediaType implements Stringable, IComparable, IEquatable {
*/ */
public function getQuality(): float { public function getQuality(): float {
$quality = $this->getParam('q', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); $quality = $this->getParam('q', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
if(!is_float($quality) && !is_int($quality)) if(is_string($quality) || is_int($quality))
return 1; $quality = (float)$quality;
if(!is_float($quality))
return 1.0;
return max(min(round($quality, 2), 1), 0); return max(min(round($quality, 2), 1.0), 0.0);
} }
/** /**

32
tests/MediaTypeTest.php Normal file
View file

@ -0,0 +1,32 @@
<?php
// MediaTypeTest.php
// Created: 2024-08-18
// Updated: 2024-08-18
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\{CoversClass,UsesClass};
use Index\{MediaType,XArray};
// This test needs to be made more comprehensive someday, this is currently only checking for an issue that I actually ran into.
#[CoversClass(MediaType::class)]
#[UsesClass(UsesClass::class)]
final class MediaTypeTest extends TestCase {
public function testQualityParsing(): void {
$types = [
'text/html' => 1.0,
'application/xhtml+xml' => 1.0,
'application/xml;q=0.9' => 0.9,
'image/webp' => 1.0,
'*/*;q=0.8' => 0.8,
];
foreach($types as $typeStr => $expectQuality) {
$type = MediaType::parse($typeStr);
$this->assertEquals($typeStr, (string)$type);
$this->assertEquals($expectQuality, $type->getQuality());
}
}
}