1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\ApiHttp\Negotiation; |
6
|
|
|
|
7
|
|
|
final class ContentNegotiator implements ContentNegotiatorInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @param string $header |
11
|
|
|
* @param array $supportedContentTypes |
12
|
|
|
* |
13
|
|
|
* @return Content|null |
14
|
|
|
*/ |
15
|
5 |
|
public function negotiate(string $header, array $supportedContentTypes) |
16
|
|
|
{ |
17
|
5 |
|
$values = []; |
18
|
5 |
|
foreach (explode(',', $header) as $headerValue) { |
19
|
5 |
|
$headerValueParts = explode(';', $headerValue); |
20
|
5 |
|
$contentType = trim(array_shift($headerValueParts)); |
21
|
5 |
|
$attributes = []; |
22
|
5 |
|
foreach ($headerValueParts as $attribute) { |
23
|
4 |
|
list($attributeKey, $attributeValue) = explode('=', $attribute); |
24
|
4 |
|
$attributes[trim($attributeKey)] = trim($attributeValue); |
25
|
|
|
} |
26
|
|
|
|
27
|
5 |
|
if (!isset($attributes['q'])) { |
28
|
5 |
|
$attributes['q'] = '1.0'; |
29
|
|
|
} |
30
|
|
|
|
31
|
5 |
|
$values[$contentType] = $attributes; |
32
|
|
|
} |
33
|
|
|
|
34
|
5 |
|
uasort($values, function (array $a, array $b) { |
35
|
5 |
|
return $b['q'] <=> $a['q']; |
36
|
5 |
|
}); |
37
|
|
|
|
38
|
|
|
foreach ($values as $contentType => $attributes) { |
39
|
|
|
list($type, $subType) = explode('/', $contentType); |
40
|
|
|
$typePattern = '*' !== $type ? preg_quote($type) : '[^\/]+'; |
41
|
|
|
$subTypePattern = '*' !== $subType ? preg_quote($subType) : '[^\/]+'; |
42
|
|
|
|
43
|
|
|
foreach ($supportedContentTypes as $supportedContentType) { |
44
|
|
|
if (1 === preg_match('/^'.$typePattern.'\/'.$subTypePattern.'$/', $supportedContentType)) { |
45
|
|
|
return new Content($supportedContentType, $attributes); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return null; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|