Passed
Pull Request — master (#185)
by
unknown
02:24
created

HeaderHelper::getParameters()   B

Complexity

Conditions 8
Paths 4

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 19
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 26
rs 8.4444
ccs 10
cts 10
cp 1
crap 8
1
<?php
2
3
namespace Yiisoft\Yii\Web\Helper;
4
5
use Psr\Http\Message\RequestInterface;
6
7
final class HeaderHelper
8
{
9
    /**
10
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-2.2
11
     * token  = 1*<any CHAR except CTLs or separators>
12
     */
13
    private const PATTERN_TOKEN = '(?:(?:[^()<>@,;:\\"\/[\\]?={} \t\x7f]|[\x00-\x1f])+)';
14 29
15
    /**
16 29
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-3.6
17 29
     * attribute = token
18 1
     */
19
    private const PATTERN_ATTRIBUTE = self::PATTERN_TOKEN;
20 28
21 28
    /**
22 28
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-2.2
23 21
     * quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
24 21
     * qdtext         = <any TEXT except <">>
25 1
     * quoted-pair    = "\" CHAR
26
     */
27 21
    private const PATTERN_QUOTED_STRING = '(?:"(?:(?:\\\\.)+|[^\\"]+)*")';
28
29 28
    /**
30
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-3.6
31
     * value = token | quoted-string
32
     */
33
    private const PATTERN_VALUE = '(?:' . self::PATTERN_QUOTED_STRING . '|' . self::PATTERN_TOKEN . ')';
34
35
    /**
36
     * Explode header value to value and parameters (eg. text/html;q=2;version=6)
37
     *
38 32
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-3.6
39
     * transfer-extension      = token *( ";" parameter )
40 32
     * @param string $headerValue
41 21
     * @return array first element is the value, and key-value are the parameters
42
     */
43 32
    public static function getValueAndParameters(string $headerValue, bool $lowerCaseValue = true, bool $lowerCaseParameter = true, bool $lowerCaseParameterValue = true): array
44 3
    {
45
        $headerValue = trim($headerValue);
46 29
        if ($headerValue === '') {
47 4
            return [];
48
        }
49 25
        $parts = explode(';', $headerValue, 2);
50 25
        $output = [$lowerCaseValue ? strtolower($parts[0]) : $parts[0]];
51 25
        if (count($parts) === 1) {
52 25
            return $output;
53
        }
54
        return $output + self::getParameters($parts[1], $lowerCaseParameter, $lowerCaseParameterValue);
55 25
    }
56 4
57
    /**
58 21
     * Explode header value to parameters (eg. q=2;version=6)
59 21
     *
60
     * @link https://tools.ietf.org/html/rfc7230#section-3.2.6
61
     */
62 17
    public static function getParameters(string $headerValue, bool $lowerCaseParameter = true, $lowerCaseValue = true): array
63 17
    {
64 17
        $headerValue = trim($headerValue);
65 9
        if ($headerValue === '') {
66
            return [];
67 8
        }
68 21
        if (rtrim($headerValue, ';') !== $headerValue) {
69 21
            throw new \InvalidArgumentException('Cannot end with a semicolon.');
70
        }
71
        $output = [];
72
        do {
73
            $headerValue = preg_replace_callback(
74
                '/^(?<parameter>' . self::PATTERN_ATTRIBUTE . ')=(?<value>' . self::PATTERN_VALUE . ')(?:;|$)/',
75 6
                static function ($matches) use (&$output, $lowerCaseParameter, $lowerCaseValue) {
76
                    $value = $matches['value'];
77 6
                    if (substr($matches['value'], 0, 1) === '"') {
78
                        // unescape + remove first and last quote
79
                        $value = preg_replace('/\\\\(.)/', '$1', substr($value, 1, -1));
80
                    }
81
                    $output[$lowerCaseParameter ? strtolower($matches['parameter']) : $matches['parameter']] = $lowerCaseValue ? strtolower($value) : $value;
82
                }, $headerValue, 1, $count);
83
            if ($count !== 1) {
84
                throw new \InvalidArgumentException('Invalid input: ' . $headerValue);
85
            }
86 18
        } while ($headerValue !== '');
87
        return $output;
88 18
    }
89
90 12
    /**
91
     * Getting header value as q factor sorted list
92 4
     * @param string|string[] $values Header value as a comma-separated string or already exploded string array.
93
     * @see getValueAndParameters
94 8
     * @link https://developer.mozilla.org/en-US/docs/Glossary/Quality_values
95 8
     * @link https://www.ietf.org/rfc/rfc2045.html#section-2
96 8
     */
97 8
    public static function getSortedValueAndParameters($values, bool $lowerCaseValue = true, bool $lowerCaseParameter = true, bool $lowerCaseParameterValue = true): array
98 8
    {
99 8
        if (is_string($values)) {
100
            $values = preg_split('/\s*,\s*/', trim($values), -1, PREG_SPLIT_NO_EMPTY);
101 5
        }
102
        if (!is_array($values)) {
103
            throw new \InvalidArgumentException('Values ​​are neither array nor string');
104 3
        }
105
        if (count($values) === 0) {
106 1
            return [];
107 1
        }
108 1
        $output = [];
109
        foreach ($values as $value) {
110 1
            $parse = self::getValueAndParameters($value, $lowerCaseValue, $lowerCaseParameter, $lowerCaseParameterValue);
111
            // case-insensitive "q" parameter
112
            $q = $parse['q'] ?? $parse['Q'] ?? 1.0;
113 1
114 18
            // min 0.000 max 1.000, max 3 digits, without digits allowed
115 18
            if (is_string($q) && preg_match('/^(?:0(?:\.\d{1,3})?|1(?:\.0{1,3})?)$/', $q) === 0) {
116 16
                throw new \InvalidArgumentException('Invalid q factor');
117 16
            }
118 16
            $parse['q'] = (float)$q;
119 15
            unset($parse['Q']);
120 15
            $output[] = $parse;
121
        }
122 5
        usort($output, static function ($a, $b) {
123 5
            $a = $a['q'];
124
            $b = $b['q'];
125
            if ($a === $b) {
126 5
                return 0;
127 5
            }
128
            return $a > $b ? -1 : 1;
129 18
        });
130
        return $output;
131
    }
132
133
    /**
134
     * @see getSortedAcceptTypes
135
     */
136
    public static function getSortedAcceptTypesFromRequest(RequestInterface $request): array
137
    {
138
        return static::getSortedAcceptTypes($request->getHeader('accept'));
139
    }
140
141
    /**
142
     * @param $values string|string[] $values Header value as a comma-separated string or already exploded string array
143
     * @return string[] sorted accept types. Note: According to RFC 7231, special parameters (except the q factor) are
144
     *                  added to the type, which are always appended by a semicolon and sorted by string.
145
     * @link https://tools.ietf.org/html/rfc7231#section-5.3.2
146
     * @link https://www.ietf.org/rfc/rfc2045.html#section-2
147
     */
148
    public static function getSortedAcceptTypes($values): array
149
    {
150
        $output = self::getSortedValueAndParameters($values);
151
        usort($output, static function ($a, $b) {
152
            if ($a['q'] !== $b['q']) {
153
                // The higher q value wins
154
                return $a['q'] > $b['q'] ? -1 : 1;
155
            }
156
            $typeA = reset($a);
157
            $typeB = reset($b);
158
            if (strpos($typeA, '*') === false && strpos($typeB, '*') === false) {
159
                $countA = count($a);
160
                $countB = count($b);
161
                if ($countA === $countB) {
162
                    // They are equivalent for the same parameter number
163
                    return 0;
164
                }
165
                // No wildcard character, higher parameter number wins
166
                return $countA > $countB ? -1 : 1;
167
            }
168
            $endWildcardA = substr($typeA, -1, 1) === '*';
169
            $endWildcardB = substr($typeB, -1, 1) === '*';
170
            if (($endWildcardA && !$endWildcardB) || (!$endWildcardA && $endWildcardB)) {
171
                // The wildcard ends is the loser.
172
                return $endWildcardA ? 1 : -1;
173
            }
174
            // The wildcard starts is the loser.
175
            return strpos($typeA, '*') === 0 ? 1 : -1;
176
        });
177
        foreach ($output as $key => $value) {
178
            $type = array_shift($value);
179
            unset($value['q']);
180
            if (count($value) === 0) {
181
                $output[$key] = $type;
182
                continue;
183
            }
184
            foreach ($value as $k => $v) {
185
                $value[$k] = $k . '=' . $v;
186
            }
187
            // Parameters are sorted for easier use of parameter variations.
188
            asort($value, SORT_STRING);
189
            $output[$key] = $type . ';' . join(';', $value);
190
        }
191
        return $output;
192
    }
193
}
194