Completed
Pull Request — master (#151)
by Alexander
03:41 queued 01:25
created

HeaderHelper::getSortedValueAndParameters()   B

Complexity

Conditions 9
Paths 10

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 21
c 0
b 0
f 0
nc 10
nop 1
dl 0
loc 32
rs 8.0555
ccs 22
cts 22
cp 1
crap 9
1
<?php
2
3
namespace Yiisoft\Yii\Web\Helper;
4
5
use Psr\Http\Message\RequestInterface;
6
7
final class HeaderHelper
8
{
9
    /**
10
     * Explode header value to value and parameters (eg. text/html;q=2;version=6)
11
     * @param string $headerValue
12
     * @return array first element is the value, and key-value are the parameters
13
     */
14 27
    public static function getValueAndParameters(string $headerValue): array
15
    {
16 27
        $headerValue = trim($headerValue);
17 27
        if ($headerValue === '') {
18 1
            return [];
19
        }
20 26
        $parts = preg_split('/\s*;\s*/', $headerValue, -1, PREG_SPLIT_NO_EMPTY);
21 26
        $output = [array_shift($parts)];
0 ignored issues
show
Bug introduced by
It seems like $parts can also be of type false; however, parameter $array of array_shift() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

21
        $output = [array_shift(/** @scrutinizer ignore-type */ $parts)];
Loading history...
22 26
        foreach ($parts as $part) {
23 20
            [$key, $headerValue] = explode('=', $part, 2);
24 20
            $output[$key] = $headerValue;
25
        }
26 26
        return $output;
27
    }
28
29
    /**
30
     * Getting header value as q factor sorted list
31
     * @param string|string[] $values Header value as a comma-separated string or already exploded string array.
32
     * @see getValueAndParameters
33
     * @link https://developer.mozilla.org/en-US/docs/Glossary/Quality_values
34
     */
35 31
    public static function getSortedValueAndParameters($values): array
36
    {
37 31
        if (is_string($values)) {
38 21
            $values = preg_split('/\s*,\s*/', trim($values), -1, PREG_SPLIT_NO_EMPTY);
39
        }
40 31
        if (!is_array($values)) {
41 3
            throw new \InvalidArgumentException('Values ​​are neither array nor string');
42
        }
43 28
        if (count($values) === 0) {
44 4
            return [];
45
        }
46 24
        $output = [];
47 24
        foreach ($values as $value) {
48 24
            $parse = self::getValueAndParameters($value);
49 24
            $q = $parse['q'] ?? 1.0;
50
51
            // min 0.000 max 1.000, max 3 digits, without digits allowed
52 24
            if (is_string($q) && preg_match('/^(?:0(?:\.\d{1,3})?|1(?:\.0{1,3})?)$/', $q) === 0) {
53 4
                throw new \InvalidArgumentException('Invalid q factor');
54
            }
55 20
            $parse['q'] = floatval($q);
56 20
            $output[] = $parse;
57
        }
58
        usort($output, static function ($a, $b) {
59 17
            $a = $a['q'];
60 17
            $b = $b['q'];
61 17
            if ($a === $b) {
62 9
                return 0;
63
            }
64 8
            return $a > $b ? -1 : 1;
65 20
        });
66 20
        return $output;
67
    }
68
69
    /**
70
     * @see getSortedAcceptTypes
71
     */
72 5
    public static function getSortedAcceptTypesFromRequest(RequestInterface $request): array
73
    {
74 5
        return static::getSortedAcceptTypes($request->getHeader('accept'));
75
    }
76
77
    /**
78
     * @param $values string|string[] $values Header value as a comma-separated string or already exploded string array
79
     * @return string[] sorted accept types. Note: According to RFC 7231, special parameters (except the q factor) are
80
     *                  added to the type, which are always appended by a semicolon and sorted by string.
81
     * @link https://tools.ietf.org/html/rfc7231#section-5.3.2
82
     */
83 17
    public static function getSortedAcceptTypes($values): array
84
    {
85 17
        $output = self::getSortedValueAndParameters($values);
86
        usort($output, static function ($a, $b) {
87 12
            if ($a['q'] !== $b['q']) {
88
                // The higher q value wins
89 4
                return $a['q'] > $b['q'] ? -1 : 1;
90
            }
91 8
            $typeA = reset($a);
92 8
            $typeB = reset($b);
93 8
            if (strpos($typeA, '*') === false && strpos($typeB, '*') === false) {
94 8
                $countA = count($a);
95 8
                $countB = count($b);
96 8
                if ($countA === $countB) {
97
                    // They are equivalent for the same parameter number
98 5
                    return 0;
99
                }
100
                // No wildcard character, higher parameter number wins
101 3
                return $countA > $countB ? -1 : 1;
102
            }
103 1
            $endWildcardA = substr($typeA, -1, 1) === '*';
104 1
            $endWildcardB = substr($typeB, -1, 1) === '*';
105 1
            if (($endWildcardA && !$endWildcardB) || (!$endWildcardA && $endWildcardB)) {
106
                // The wildcard ends is the loser.
107 1
                return $endWildcardA ? 1 : -1;
108
            }
109
            // The wildcard starts is the loser.
110 1
            return strpos($typeA, '*') === 0 ? 1 : -1;
111 17
        });
112 17
        foreach ($output as $key => $value) {
113 15
            $type = array_shift($value);
114 15
            unset($value['q']);
115 15
            if (count($value) === 0) {
116 14
                $output[$key] = $type;
117 14
                continue;
118
            }
119 5
            foreach ($value as $k => $v) {
120 5
                $value[$k] = $k . '=' . $v;
121
            }
122
            // Parameters are sorted for easier use of parameter variations.
123 5
            asort($value, SORT_STRING);
124 5
            $output[$key] = $type . ';' . join(';', $value);
125
        }
126 17
        return $output;
127
    }
128
}
129