-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUtils.php
244 lines (231 loc) · 8.87 KB
/
Utils.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<?php
declare(strict_types=1);
namespace Fossar\GuzzleTranscoder;
class Utils {
/**
* HTTP Headers Util 0.1.
*
* @author: Keyvan Minoukadeh - [email protected] - http://www.keyvan.net
*
* @license GNU General Public License, version 2
*
* @see (source) http://www.phpkode.com/source/s/http-headers-utility/http-headers-utility/HTTP_Headers_Util.php
*
* This method is based on:
* <http://search.cpan.org/author/GAAS/libwww-perl-5.65/lib/HTTP/Headers/Util.pm>
* by Gisle Aas.
* The text here is copied from the documentation of the above, obviously
* slightly modified as this is PHP not Perl.
*
* split_header_words
*
* This function will parse the header values given as argument into a
* array containing key/value pairs. The function
* knows how to deal with ",", ";" and "=" as well as quoted values after
* "=". A list of space separated tokens are parsed as if they were
* separated by ";".
*
* If the $headerValues passed as argument contains multiple values,
* then they are treated as if they were a single value separated by
* comma ",".
*
* This means that this function is useful for parsing header fields that
* follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
* the requirement for tokens).
*
* headers = #header
* header = (token | parameter) *( [";"] (token | parameter))
*
* token = 1*<any CHAR except CTLs or separators>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
*
* quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
* qdtext = <any TEXT except <">>
* quoted-pair = "\" CHAR
*
* parameter = attribute "=" value
* attribute = token
* value = token | quoted-string
*
* Each header is represented by an anonymous array of key/value
* pairs. The value for a simple token (not part of a parameter) is null.
* Syntactically incorrect headers will not necessary be parsed as you
* would want.
*
* This is easier to describe with some examples:
*
* split_header_words('foo="bar"; port="80,81"; discard, bar=baz');
* split_header_words('text/html; charset="iso-8859-1");
* split_header_words('Basic realm="\"foo\\bar\""');
* split_header_words("</TheBook/chapter,2>; rel=\"pre,vious\"; title*=UTF-8'de'letztes%20Kapitel, </TheBook/chapter4>;rel=\"next\"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel");
*
* will return
*
* [foo=>'bar', port=>'80,81', discard=>null], [bar=>'baz']
* ['text/html'=>null, charset=>'iso-8859-1']
* [Basic=>null, realm=>'"foo\bar"']
* ["</TheBook/chapter,2>" => null, "rel" => "pre,vious", "title*" => "UTF-8'de'letztes%20Kapitel" ], ["</TheBook/chapter4>" => null, "rel" => "next", "title*" => "UTF-8'de'n%c3%a4chstes%20Kapitel" ]
*
* @param list<string>|string $headerValues
*
* @throws \Exception
*
* @return array<non-empty-array<string, ?string>>
*/
public static function splitHttpHeaderWords($headerValues): array {
if (!\is_array($headerValues)) {
$headerValues = [$headerValues];
}
$result = [];
foreach ($headerValues as $header) {
$cur = [];
while ($header) {
$key = '';
$val = null;
// Parse <link> header correctly http://tools.ietf.org/html/rfc5988#section-5
if (preg_match('/^\s*(<[^>]*>)(.*)/', $header, $match)) {
$key = $match[1];
$header = $match[2];
$cur[$key] = null;
} elseif (preg_match('/^\s*(=*[^\s=;,]+)(.*)/', $header, $match)) {
// 'token' or parameter 'attribute'
$key = $match[1];
$header = $match[2];
// a quoted value
if (preg_match('/^\s*=\s*"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"(.*)/', $header, $match)) {
$val = $match[1];
$header = $match[2];
// remove backslash character escape
$val = preg_replace('/\\\\(.)/', '$1', $val);
// some unquoted value
} elseif (preg_match('/^\s*=\s*([^;,\s]*)(.*)/', $header, $match)) {
$val = trim($match[1]);
$header = $match[2];
}
// add details
$cur[$key] = $val;
// reached the end, a new 'token' or 'attribute' about to start
} elseif (preg_match('/^\s*,(.*)/', $header, $match)) {
$header = $match[1];
if (\count($cur)) {
$result[] = $cur;
}
$cur = [];
// continue
} elseif (preg_match('/^\s*;(.*)/', $header, $match)) {
$header = $match[1];
} elseif (preg_match('/^\s+(.*)/', $header, $match)) {
$header = $match[1];
} else {
throw new \Exception('This should not happen: "' . $header . '"');
}
}
if (\count($cur)) {
$result[] = $cur;
}
}
return $result;
}
/**
* HTTP Headers Util 0.1.
*
* @author: Keyvan Minoukadeh – [email protected] – http://www.keyvan.net
*
* @license GNU General Public License, version 2
*
* @see (source)http://www.phpkode.com/source/s/http-headers-utility/http-headers-utility/HTTP_Headers_Util.php
*
* join_header_words
*
* This will do the opposite of the conversion done by split_header_words().
* It takes a list of anonymous arrays as arguments (or a list of
* key/value pairs) and produces a single header value. Attribute values
* are quoted if needed.
*
* Example:
*
* join_header_words(array(array("text/plain" => null, "charset" => "iso-8859/1")));
* join_header_words(array("text/plain" => null, "charset" => "iso-8859/1"));
*
* will both return the string:
*
* text/plain; charset="iso-8859/1"
* @see http://tools.ietf.org/html/rfc5988#section-5
*
* @param array<array<string, ?string>>|array<string, ?string> $headerValues
*/
public static function joinHttpHeaderWords(array $headerValues): string {
if (\count($headerValues) === 0) {
return '';
}
// evaluate if its a multidimensional array
$first = reset($headerValues);
if (!\is_array($first)) {
$headerValues = [$headerValues];
}
/** @var array<array<string, ?string>> $headerValues */
$spaces = '\\s';
$ctls = '\\x00-\\x1F\\x7F'; // @see http://stackoverflow.com/a/1497928/413531
$tspecials = '()<>@,;:<>/[\\]?.="\\\\';
$tokenPattern = "#^[^{$spaces}{$ctls}{$tspecials}]+$#";
$result = [];
foreach ($headerValues as $header) {
$attr = [];
foreach ($header as $key => $val) {
if (isset($val)) {
if (preg_match($tokenPattern, $val)) {
$key .= "=$val";
} else {
$val = preg_replace('/(["\\\\])/', '\\\\$1', $val);
$key .= "=\"$val\"";
}
}
$attr[] = $key;
}
if (\count($attr)) {
$result[] = implode('; ', $attr);
}
}
return implode(', ', $result);
}
/**
* Gets array item by case-insensitive key.
*
* @template T
*
* @param array<string, T> $words
*
* @return ?T
*/
public static function getByCaseInsensitiveKey(array $words, string $key) {
foreach ($words as $headerWord => $value) {
if (strcasecmp($headerWord, $key) === 0) {
return $value;
}
}
return null;
}
/**
* Sets array item by case-insensitive key.
*
* @template T
*
* @param array<string, T> $words
* @param T $newValue
*
* @return array<string, T>
*/
public static function setByCaseInsensitiveKey(array $words, string $key, $newValue): array {
foreach ($words as $headerWord => $value) {
if (strcasecmp($headerWord, $key) === 0) {
$key = $headerWord;
break;
}
}
$words[$key] = $newValue;
return $words;
}
}