Completed
Pull Request — master (#188)
by Alexander
04:45
created

HeaderHelper::getParameters()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
nc 3
nop 1
dl 0
loc 18
ccs 12
cts 13
cp 0.9231
crap 4.0072
rs 9.7998
c 1
b 0
f 0
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 29
    public static function getValueAndParameters(string $headerValue): array
15
    {
16 29
        $headerValue = trim($headerValue);
17 29
        if ($headerValue === '') {
18 1
            return [];
19
        }
20 28
        $parts = preg_split('/\s*;\s*/', $headerValue, 2, PREG_SPLIT_NO_EMPTY);
21 28
        $output = [$parts[0]];
22 28
        if (count($parts) === 1) {
23 16
            return $output;
24
        }
25 21
        return array_merge($output, self::getParameters($parts[1]));
26
    }
27
28
    /**
29
     * Explode header value to parameters (eg. q=2;version=6)
30
     *
31
     * @link https://tools.ietf.org/html/rfc7230#section-3.2.6
32
     */
33 41
    public static function getParameters(string $headerValue): array
34
    {
35 41
        $headerValue = trim($headerValue);
36 41
        if ($headerValue === '') {
37
            return [];
38
        }
39 41
        $output = [];
40
        do {
41 41
            $headerValue = preg_replace_callback(
42 41
                '/^\s*(?<parameter>\w+)\s*=\s*(?:"(?<valueQuoted>[^"]+)"|(?<value>[!#$%&\'*+.^`|~\w-]+))\s*(?:;|$)/',
43
                static function ($matches) use (&$output) {
44 38
                    $output[$matches['parameter']] = $matches['value'] ?? $matches['valueQuoted'];
45 41
                }, $headerValue, 1, $count);
46 41
            if ($count !== 1) {
47 4
                throw new \InvalidArgumentException('Invalid input: ' . $headerValue);
48
            }
49 38
        } while ($headerValue !== '');
50 37
        return $output;
51
    }
52
53
    /**
54
     * Getting header value as q factor sorted list
55
     * @param string|string[] $values Header value as a comma-separated string or already exploded string array.
56
     * @see getValueAndParameters
57
     * @link https://developer.mozilla.org/en-US/docs/Glossary/Quality_values
58
     */
59 32
    public static function getSortedValueAndParameters($values): array
60
    {
61 32
        if (is_string($values)) {
62 21
            $values = preg_split('/\s*,\s*/', trim($values), -1, PREG_SPLIT_NO_EMPTY);
63
        }
64 32
        if (!is_array($values)) {
65 3
            throw new \InvalidArgumentException('Values ​​are neither array nor string');
66
        }
67 29
        if (count($values) === 0) {
68 4
            return [];
69
        }
70 25
        $output = [];
71 25
        foreach ($values as $value) {
72 25
            $parse = self::getValueAndParameters($value);
73 25
            $q = $parse['q'] ?? 1.0;
74
75
            // min 0.000 max 1.000, max 3 digits, without digits allowed
76 25
            if (is_string($q) && preg_match('/^(?:0(?:\.\d{1,3})?|1(?:\.0{1,3})?)$/', $q) === 0) {
77 4
                throw new \InvalidArgumentException('Invalid q factor');
78
            }
79 21
            $parse['q'] = (float)$q;
80 21
            $output[] = $parse;
81
        }
82
        usort($output, static function ($a, $b) {
83 17
            $a = $a['q'];
84 17
            $b = $b['q'];
85 17
            if ($a === $b) {
86 9
                return 0;
87
            }
88 8
            return $a > $b ? -1 : 1;
89 21
        });
90 21
        return $output;
91
    }
92
93
    /**
94
     * @see getSortedAcceptTypes
95
     */
96 6
    public static function getSortedAcceptTypesFromRequest(RequestInterface $request): array
97
    {
98 6
        return static::getSortedAcceptTypes($request->getHeader('accept'));
99
    }
100
101
    /**
102
     * @param $values string|string[] $values Header value as a comma-separated string or already exploded string array
103
     * @return string[] sorted accept types. Note: According to RFC 7231, special parameters (except the q factor) are
104
     *                  added to the type, which are always appended by a semicolon and sorted by string.
105
     * @link https://tools.ietf.org/html/rfc7231#section-5.3.2
106
     */
107 18
    public static function getSortedAcceptTypes($values): array
108
    {
109 18
        $output = self::getSortedValueAndParameters($values);
110
        usort($output, static function ($a, $b) {
111 12
            if ($a['q'] !== $b['q']) {
112
                // The higher q value wins
113 4
                return $a['q'] > $b['q'] ? -1 : 1;
114
            }
115 8
            $typeA = reset($a);
116 8
            $typeB = reset($b);
117 8
            if (strpos($typeA, '*') === false && strpos($typeB, '*') === false) {
118 8
                $countA = count($a);
119 8
                $countB = count($b);
120 8
                if ($countA === $countB) {
121
                    // They are equivalent for the same parameter number
122 5
                    return 0;
123
                }
124
                // No wildcard character, higher parameter number wins
125 3
                return $countA > $countB ? -1 : 1;
126
            }
127 1
            $endWildcardA = substr($typeA, -1, 1) === '*';
128 1
            $endWildcardB = substr($typeB, -1, 1) === '*';
129 1
            if (($endWildcardA && !$endWildcardB) || (!$endWildcardA && $endWildcardB)) {
130
                // The wildcard ends is the loser.
131 1
                return $endWildcardA ? 1 : -1;
132
            }
133
            // The wildcard starts is the loser.
134 1
            return strpos($typeA, '*') === 0 ? 1 : -1;
135 18
        });
136 18
        foreach ($output as $key => $value) {
137 16
            $type = array_shift($value);
138 16
            unset($value['q']);
139 16
            if (count($value) === 0) {
140 15
                $output[$key] = $type;
141 15
                continue;
142
            }
143 5
            foreach ($value as $k => $v) {
144 5
                $value[$k] = $k . '=' . $v;
145
            }
146
            // Parameters are sorted for easier use of parameter variations.
147 5
            asort($value, SORT_STRING);
148 5
            $output[$key] = $type . ';' . join(';', $value);
149
        }
150 18
        return $output;
151
    }
152
}
153