Passed
Push — master ( 1d59e9...66e80e )
by Alexander
09:22 queued 07:43
created

HeaderHelper   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 187
Duplicated Lines 0 %

Test Coverage

Coverage 79.07%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 86
c 1
b 1
f 0
dl 0
loc 187
ccs 68
cts 86
cp 0.7907
rs 9.36
wmc 38

4 Methods

Rating   Name   Duplication   Size   Complexity  
C getSortedAcceptTypes() 0 44 16
B getParameters() 0 36 9
B getSortedValueAndParameters() 0 34 9
A getValueAndParameters() 0 12 4
1
<?php
2
3
namespace Yiisoft\ErrorHandler;
4
5
final class HeaderHelper
6
{
7
    /**
8
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-2.2
9
     * token  = 1*<any CHAR except CTLs or separators>
10
     */
11
    private const PATTERN_TOKEN = '(?:(?:[^()<>@,;:\\"\/[\\]?={} \t\x7f]|[\x00-\x1f])+)';
12
13
    /**
14
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-3.6
15
     * attribute = token
16
     */
17
    private const PATTERN_ATTRIBUTE = self::PATTERN_TOKEN;
18
19
    /**
20
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-2.2
21
     * quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
22
     * qdtext         = <any TEXT except <">>
23
     * quoted-pair    = "\" CHAR
24
     */
25
    private const PATTERN_QUOTED_STRING = '(?:"(?:(?:\\\\.)+|[^\\"]+)*")';
26
27
    /**
28
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-3.6
29
     * value = token | quoted-string
30
     */
31
    private const PATTERN_VALUE = '(?:' . self::PATTERN_QUOTED_STRING . '|' . self::PATTERN_TOKEN . ')';
32
33
    /**
34
     * Explode header value to value and parameters (eg. text/html;q=2;version=6)
35
     *
36
     * @link https://www.rfc-editor.org/rfc/rfc2616.html#section-3.6
37
     * transfer-extension      = token *( ";" parameter )
38
     * @param string $headerValue
39
     * @return array first element is the value, and key-value are the parameters
40
     */
41 5
    public static function getValueAndParameters(string $headerValue, bool $lowerCaseValue = true, bool $lowerCaseParameter = true, bool $lowerCaseParameterValue = true): array
42
    {
43 5
        $headerValue = trim($headerValue);
44 5
        if ($headerValue === '') {
45
            return [];
46
        }
47 5
        $parts = explode(';', $headerValue, 2);
48 5
        $output = [$lowerCaseValue ? strtolower($parts[0]) : $parts[0]];
49 5
        if (count($parts) === 1) {
50 5
            return $output;
51
        }
52 1
        return $output + self::getParameters($parts[1], $lowerCaseParameter, $lowerCaseParameterValue);
53
    }
54
55
    /**
56
     * Explode header value to parameters (eg. q=2;version=6)
57
     *
58
     * @link https://tools.ietf.org/html/rfc7230#section-3.2.6
59
     */
60 1
    public static function getParameters(string $headerValue, bool $lowerCaseParameter = true, bool $lowerCaseValue = true): array
61
    {
62 1
        $headerValue = trim($headerValue);
63 1
        if ($headerValue === '') {
64
            return [];
65
        }
66 1
        if (rtrim($headerValue, ';') !== $headerValue) {
67
            throw new \InvalidArgumentException('Cannot end with a semicolon.');
68
        }
69 1
        $output = [];
70
        do {
71
            /** @psalm-suppress InvalidArgument */
72 1
            $headerValue = preg_replace_callback(
73 1
                '/^[ \t]*(?<parameter>' . self::PATTERN_ATTRIBUTE . ')[ \t]*=[ \t]*(?<value>' . self::PATTERN_VALUE . ')[ \t]*(?:;|$)/u',
74 1
                static function ($matches) use (&$output, $lowerCaseParameter, $lowerCaseValue) {
75 1
                    $value = $matches['value'];
76 1
                    if (mb_strpos($matches['value'], '"') === 0) {
77
                        // unescape + remove first and last quote
78
                        $value = preg_replace('/\\\\(.)/u', '$1', mb_substr($value, 1, -1));
79
                    }
80 1
                    $key = $lowerCaseParameter ? mb_strtolower($matches['parameter']) : $matches['parameter'];
81 1
                    if (isset($output[$key])) {
82
                        // The first is the winner.
83
                        return;
84
                    }
85 1
                    $output[$key] = $lowerCaseValue ? mb_strtolower($value) : $value;
86 1
                },
87
                $headerValue,
88 1
                1,
89
                $count
90
            );
91 1
            if ($count !== 1) {
92
                throw new \InvalidArgumentException('Invalid input: ' . $headerValue);
93
            }
94 1
        } while ($headerValue !== '');
95 1
        return $output;
96
    }
97
98
    /**
99
     * Getting header value as q factor sorted list
100
     * @param string|string[] $values Header value as a comma-separated string or already exploded string array.
101
     * @see getValueAndParameters
102
     * @link https://developer.mozilla.org/en-US/docs/Glossary/Quality_values
103
     * @link https://www.ietf.org/rfc/rfc2045.html#section-2
104
     */
105 5
    public static function getSortedValueAndParameters($values, bool $lowerCaseValue = true, bool $lowerCaseParameter = true, bool $lowerCaseParameterValue = true): array
106
    {
107 5
        if (is_string($values)) {
108
            $values = preg_split('/\s*,\s*/', trim($values), -1, PREG_SPLIT_NO_EMPTY);
109
        }
110 5
        if (!is_array($values)) {
111
            throw new \InvalidArgumentException('Values ​​are neither array nor string');
112
        }
113 5
        if (count($values) === 0) {
114
            return [];
115
        }
116 5
        $output = [];
117 5
        foreach ($values as $value) {
118 5
            $parse = self::getValueAndParameters($value, $lowerCaseValue, $lowerCaseParameter, $lowerCaseParameterValue);
119
            // case-insensitive "q" parameter
120 5
            $q = $parse['q'] ?? $parse['Q'] ?? 1.0;
121
122
            // min 0.000 max 1.000, max 3 digits, without digits allowed
123 5
            if (is_string($q) && preg_match('/^(?:0(?:\.\d{1,3})?|1(?:\.0{1,3})?)$/', $q) === 0) {
124
                throw new \InvalidArgumentException('Invalid q factor');
125
            }
126 5
            $parse['q'] = (float)$q;
127 5
            unset($parse['Q']);
128 5
            $output[] = $parse;
129
        }
130 5
        usort($output, static function ($a, $b) {
131 1
            $a = $a['q'];
132 1
            $b = $b['q'];
133 1
            if ($a === $b) {
134 1
                return 0;
135
            }
136
            return $a > $b ? -1 : 1;
137 5
        });
138 5
        return $output;
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 5
    public static function getSortedAcceptTypes($values): array
149
    {
150 5
        $output = self::getSortedValueAndParameters($values);
151 5
        usort($output, static function ($a, $b) {
152 1
            if ($a['q'] !== $b['q']) {
153
                // The higher q value wins
154
                return $a['q'] > $b['q'] ? -1 : 1;
155
            }
156 1
            $typeA = reset($a);
157 1
            $typeB = reset($b);
158 1
            if (strpos($typeA, '*') === false && strpos($typeB, '*') === false) {
159 1
                $countA = count($a);
160 1
                $countB = count($b);
161 1
                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 1
                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 5
        });
177 5
        foreach ($output as $key => $value) {
178 5
            $type = array_shift($value);
179 5
            unset($value['q']);
180 5
            if (count($value) === 0) {
181 5
                $output[$key] = $type;
182 5
                continue;
183
            }
184 1
            foreach ($value as $k => $v) {
185 1
                $value[$k] = $k . '=' . $v;
186
            }
187
            // Parameters are sorted for easier use of parameter variations.
188 1
            asort($value, SORT_STRING);
189 1
            $output[$key] = $type . ';' . join(';', $value);
190
        }
191 5
        return $output;
192
    }
193
}
194