Skip to content

Commit 2bbe63a

Browse files
committed
Add Accept enum
1 parent a7741e6 commit 2bbe63a

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed

src/Header/Accept.php

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44

55
namespace FastForward\Http\Message\Header;
66

7-
use function explode;
8-
use function str_contains;
7+
use function preg_match_all;
98
use function str_ends_with;
109
use function str_starts_with;
1110
use function strtok;
@@ -57,32 +56,28 @@ public static function getBestMatch(string $acceptHeader, array $supportedTypes)
5756
private static function parseHeader(string $header): array
5857
{
5958
$preferences = [];
60-
$parts = explode(',', $header);
61-
62-
foreach ($parts as $part) {
63-
$params = explode(';', $part);
64-
$type = trim($params[0]);
65-
$q = 1.0;
66-
67-
if (isset($params[1]) && str_contains($params[1], 'q=')) {
68-
$q = (float) trim(explode('=', $params[1])[1]);
59+
// Regex to capture type and an optional q-factor, ignoring other parameters.
60+
$pattern = '/(?<type>[^,;]+)(?:;[^,]*q=(?<q>[0-9.]+))?/';
61+
62+
if (preg_match_all($pattern, $header, $matches, PREG_SET_ORDER)) {
63+
foreach ($matches as $match) {
64+
$type = trim($match['type']);
65+
$q = isset($match['q']) && $match['q'] !== '' ? (float) $match['q'] : 1.0;
66+
67+
$preferences[] = [
68+
'type' => $type,
69+
'q' => $q,
70+
'specificity' => self::calculateSpecificity($type),
71+
];
6972
}
70-
71-
$preferences[] = [
72-
'type' => $type,
73-
'q' => $q,
74-
'specificity' => self::calculateSpecificity($type),
75-
];
7673
}
7774

78-
usort($preferences, function ($a, $b) {
75+
usort($preferences, static function ($a, $b) {
7976
if ($a['q'] !== $b['q']) {
8077
return $b['q'] <=> $a['q']; // Sort by quality factor descending
8178
}
82-
if ($a['specificity'] !== $b['specificity']) {
83-
return $b['specificity'] <=> $a['specificity']; // Then by specificity descending
84-
}
85-
return 0;
79+
80+
return $b['specificity'] <=> $a['specificity']; // Then by specificity descending
8681
});
8782

8883
return $preferences;

0 commit comments

Comments
 (0)