Passed
Push — master ( 854b7d...2bd34a )
by Dominik
01:59
created

ContentNegotiator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 1
dl 0
loc 46
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
D negotiate() 0 37 9
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