-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathEncoder.php
More file actions
506 lines (427 loc) · 16.8 KB
/
Encoder.php
File metadata and controls
506 lines (427 loc) · 16.8 KB
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
<?php
/**
* League.Uri (https://uri.thephpleague.com)
*
* (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace League\Uri;
use BackedEnum;
use Closure;
use Deprecated;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\IPv6\Converter as IPv6Converter;
use SensitiveParameter;
use Stringable;
use Throwable;
use function explode;
use function filter_var;
use function gettype;
use function in_array;
use function preg_match;
use function preg_replace_callback;
use function rawurldecode;
use function rawurlencode;
use function sprintf;
use function str_starts_with;
use function strtolower;
use function strtoupper;
use const FILTER_FLAG_IPV4;
use const FILTER_VALIDATE_IP;
final class Encoder
{
private const REGEXP_CHARS_INVALID = '/[\x00-\x1f\x7f]/';
private const REGEXP_CHARS_ENCODED = ',%[A-Fa-f0-9]{2},';
private const REGEXP_CHARS_PREVENTS_DECODING = ',%
2[A-F|1-2|4-9]|
3[0-9|B|D]|
4[1-9|A-F]|
5[0-9|A|F]|
6[1-9|A-F]|
7[0-9|E]
,ix';
private const REGEXP_PART_SUBDELIM = "\!\$&'\(\)\*\+,;\=%";
private const REGEXP_PART_UNRESERVED = 'A-Za-z\d_\-.~';
private const REGEXP_PART_ENCODED = '%(?![A-Fa-f\d]{2})';
/**
* Unreserved characters.
*
* @see https://www.rfc-editor.org/rfc/rfc3986.html#section-2.3
*/
private const REGEXP_UNRESERVED_CHARACTERS = ',%(2[DdEe]|3[0-9]|4[1-9A-Fa-f]|5[AaFf]|6[1-9A-Fa-f]|7[0-9A-Ea-e]),';
/**
* Tell whether the user component is correctly encoded.
*/
public static function isUserEncoded(BackedEnum|Stringable|string|null $encoded): bool
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.']+|'.self::REGEXP_PART_ENCODED.'/';
if ($encoded instanceof BackedEnum) {
$encoded = $encoded->value;
}
return null === $encoded || 1 !== preg_match($pattern, (string) $encoded);
}
/**
* Encode User.
*
* All generic delimiters MUST be encoded
*/
public static function encodeUser(BackedEnum|Stringable|string|null $user): ?string
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.']+|'.self::REGEXP_PART_ENCODED.'/';
return self::encode($user, $pattern);
}
/**
* Normalize user component.
*
* The value returned MUST be percent-encoded, but MUST NOT double-encode
* any characters. To determine what characters to encode, please refer to
* RFC 3986.
*/
public static function normalizeUser(BackedEnum|Stringable|string|null $user): ?string
{
return self::normalize(self::encodeUser(self::decodeUnreservedCharacters($user)));
}
private static function normalize(?string $component): ?string
{
if (null === $component) {
return null;
}
return (string) preg_replace_callback(
'/%[0-9a-f]{2}/i',
static fn (array $found) => strtoupper($found[0]),
$component
);
}
/**
* Tell whether the password component is correctly encoded.
*/
public static function isPasswordEncoded(#[SensitiveParameter] BackedEnum|Stringable|string|null $encoded): bool
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.':]+|'.self::REGEXP_PART_ENCODED.'/';
if ($encoded instanceof BackedEnum) {
$encoded = $encoded->value;
}
return null === $encoded || 1 !== preg_match($pattern, (string) $encoded);
}
/**
* Encode Password.
*
* Generic delimiters ":" MUST NOT be encoded
*/
public static function encodePassword(#[SensitiveParameter] BackedEnum|Stringable|string|null $component): ?string
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.':]+|'.self::REGEXP_PART_ENCODED.'/';
return self::encode($component, $pattern);
}
/**
* Normalize password component.
*
* The value returned MUST be percent-encoded, but MUST NOT double-encode
* any characters. To determine what characters to encode, please refer to
* RFC 3986.
*/
public static function normalizePassword(#[SensitiveParameter] BackedEnum|Stringable|string|null $password): ?string
{
return self::normalize(self::encodePassword(self::decodeUnreservedCharacters($password)));
}
/**
* Tell whether the userInfo component is correctly encoded.
*/
public static function isUserInfoEncoded(#[SensitiveParameter] BackedEnum|Stringable|string|null $userInfo): bool
{
if (null === $userInfo) {
return true;
}
if ($userInfo instanceof BackedEnum) {
$userInfo = $userInfo->value;
}
[$user, $password] = explode(':', (string) $userInfo, 2) + [1 => null];
return self::isUserEncoded($user)
&& self::isPasswordEncoded($password);
}
public static function encodeUserInfo(#[SensitiveParameter] BackedEnum|Stringable|string|null $userInfo): ?string
{
if (null === $userInfo) {
return null;
}
if ($userInfo instanceof BackedEnum) {
$userInfo = $userInfo->value;
}
[$user, $password] = explode(':', (string) $userInfo, 2) + [1 => null];
$userInfo = self::encodeUser($user);
if (null === $password) {
return $userInfo;
}
return $userInfo.':'.self::encodePassword($password);
}
public static function normalizeUserInfo(#[SensitiveParameter] BackedEnum|Stringable|string|null $userInfo): ?string
{
if (null === $userInfo) {
return null;
}
if ($userInfo instanceof BackedEnum) {
$userInfo = $userInfo->value;
}
[$user, $password] = explode(':', (string) $userInfo, 2) + [1 => null];
$userInfo = self::normalizeUser($user);
if (null === $password) {
return $userInfo;
}
return $userInfo.':'.self::normalizePassword($password);
}
/**
* Decodes all the URI component characters.
*/
public static function decodeAll(BackedEnum|Stringable|string|null $component): ?string
{
return self::decode($component, static fn (array $matches): string => rawurldecode($matches[0]));
}
/**
* Decodes the URI component without decoding the unreserved characters which are already encoded.
*/
public static function decodeNecessary(BackedEnum|Stringable|string|int|null $component): ?string
{
$decoder = static function (array $matches): string {
if (1 === preg_match(self::REGEXP_CHARS_PREVENTS_DECODING, $matches[0])) {
return strtoupper($matches[0]);
}
return rawurldecode($matches[0]);
};
return self::decode($component, $decoder);
}
/**
* Decodes the component unreserved characters.
*/
public static function decodeUnreservedCharacters(BackedEnum|Stringable|string|null $str): ?string
{
if ($str instanceof BackedEnum) {
$str = $str->value;
}
if (null === $str) {
return null;
}
return preg_replace_callback(
self::REGEXP_UNRESERVED_CHARACTERS,
static fn (array $matches): string => rawurldecode($matches[0]),
(string) $str
);
}
/**
* Tell whether the path component is correctly encoded.
*/
public static function isPathEncoded(BackedEnum|Stringable|string|null $encoded): bool
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.':@\/]+|'.self::REGEXP_PART_ENCODED.'/';
if ($encoded instanceof BackedEnum) {
$encoded = $encoded->value;
}
return null === $encoded || 1 !== preg_match($pattern, (string) $encoded);
}
/**
* Encode Path.
*
* Generic delimiters ":", "@", and "/" MUST NOT be encoded
*/
public static function encodePath(BackedEnum|Stringable|string|null $component): string
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.':@\/]+|'.self::REGEXP_PART_ENCODED.'/';
return (string) self::encode($component, $pattern);
}
/**
* Decodes the path component while preserving characters that should not be decoded in the context of a full valid URI.
*/
public static function decodePath(BackedEnum|Stringable|string|null $path): ?string
{
$decoder = static function (array $matches): string {
$encodedChar = strtoupper($matches[0]);
return in_array($encodedChar, ['%2F', '%20', '%3F', '%23'], true) ? $encodedChar : rawurldecode($encodedChar);
};
return self::decode($path, $decoder);
}
/**
* Normalize path component.
*
* The value returned MUST be percent-encoded, but MUST NOT double-encode
* any characters. To determine what characters to encode, please refer to
* RFC 3986.
*/
public static function normalizePath(BackedEnum|Stringable|string|null $component): ?string
{
return self::normalize(self::encodePath(self::decodePath($component)));
}
/**
* Tell whether the query component is correctly encoded.
*/
public static function isQueryEncoded(BackedEnum|Stringable|string|null $encoded): bool
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.'\/?%]+|'.self::REGEXP_PART_ENCODED.'/';
if ($encoded instanceof BackedEnum) {
$encoded = $encoded->value;
}
return null === $encoded || 1 !== preg_match($pattern, (string) $encoded);
}
/**
* Decodes the query component while preserving characters that should not be decoded in the context of a full valid URI.
*/
public static function decodeQuery(BackedEnum|Stringable|string|null $path): ?string
{
$decoder = static function (array $matches): string {
$encodedChar = strtoupper($matches[0]);
return in_array($encodedChar, ['%26', '%3D', '%20', '%23', '%3F'], true) ? $encodedChar : rawurldecode($encodedChar);
};
return self::decode($path, $decoder);
}
/**
* Normalize the query component.
*
* The value returned MUST be percent-encoded, but MUST NOT double-encode
* any characters. To determine what characters to encode, please refer to
* RFC 3986.
*/
public static function normalizeQuery(BackedEnum|Stringable|string|null $query): ?string
{
return self::normalize(self::encodeQueryOrFragment(self::decodeQuery($query)));
}
/**
* Tell whether the query component is correctly encoded.
*/
public static function isFragmentEncoded(BackedEnum|Stringable|string|null $encoded): bool
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.':@\/?%]|'.self::REGEXP_PART_ENCODED.'/';
if ($encoded instanceof BackedEnum) {
$encoded = $encoded->value;
}
return null === $encoded || 1 !== preg_match($pattern, (string) $encoded);
}
/**
* Decodes the fragment component while preserving characters that should not be decoded in the context of a full valid URI.
*/
public static function decodeFragment(BackedEnum|Stringable|string|null $path): ?string
{
return self::decode($path, static fn (array $matches): string => '%20' === $matches[0] ? $matches[0] : rawurldecode($matches[0]));
}
/**
* Normalize the fragment component.
*
* The value returned MUST be percent-encoded, but MUST NOT double-encode
* any characters. To determine what characters to encode, please refer to
* RFC 3986.
*/
public static function normalizeFragment(BackedEnum|Stringable|string|null $fragment): ?string
{
return self::normalize(self::encodeQueryOrFragment(self::decodeFragment($fragment)));
}
/**
* Normalize the host component.
*
* @see https://www.rfc-editor.org/rfc/rfc3986.html#section-3.2.2
*
* The value returned MUST be percent-encoded, but MUST NOT double-encode
* any characters. To determine what characters to encode, please refer to
* RFC 3986.
*/
public static function normalizeHost(BackedEnum|Stringable|string|null $host): ?string
{
if ($host instanceof BackedEnum) {
$host = (string) $host->value;
}
if ($host instanceof Stringable) {
$host = (string) $host;
}
if (null === $host || '' === $host || false !== filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return $host;
}
if (str_starts_with($host, '[')) {
return IPv6Converter::normalize($host);
}
$host = strtolower($host);
return (!str_contains($host, '%')) ? $host : preg_replace_callback(
'/%[a-f0-9]{2}/',
fn (array $matches) => 1 === preg_match('/%([0-7][0-9a-f])/', $matches[0]) ? rawurldecode($matches[0]) : strtoupper($matches[0]),
$host
);
}
/**
* Encode Query or Fragment.
*
* Generic delimiters ":", "@", "?", and "/" MUST NOT be encoded
*/
public static function encodeQueryOrFragment(BackedEnum|Stringable|string|null $component): ?string
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.self::REGEXP_PART_SUBDELIM.':@\/?]+|'.self::REGEXP_PART_ENCODED.'/';
return self::encode($component, $pattern);
}
public static function encodeQueryKeyValue(mixed $component): ?string
{
static $pattern = '/[^'.self::REGEXP_PART_UNRESERVED.']+|'.self::REGEXP_PART_ENCODED.'/';
$encoder = static fn (array $found): string => 1 === preg_match('/[^'.self::REGEXP_PART_UNRESERVED.']/', rawurldecode($found[0])) ? rawurlencode($found[0]) : $found[0];
$filteredComponent = self::filterComponent($component);
return match (true) {
null === $filteredComponent => throw new SyntaxError(sprintf('A pair key/value must be a scalar value `%s` given.', gettype($component))),
1 === preg_match(self::REGEXP_CHARS_INVALID, $filteredComponent) => rawurlencode($filteredComponent),
default => (string) preg_replace_callback($pattern, $encoder, $filteredComponent),
};
}
private static function filterComponent(mixed $component): ?string
{
try {
return StringCoercionMode::Native->coerce($component);
} catch (Throwable $exception) {
throw new SyntaxError(
sprintf('The component must be a scalar value `%s` given.', gettype($component)),
previous: $exception
);
}
}
/**
* Encodes the URI component characters using a regular expression to find which characters need encoding.
*/
private static function encode(BackedEnum|Stringable|string|int|bool|null $component, string $pattern): ?string
{
$component = self::filterComponent($component);
if (null === $component || '' === $component) {
return $component;
}
return (string) preg_replace_callback(
$pattern,
static fn (array $found): string => 1 === preg_match('/[^'.self::REGEXP_PART_UNRESERVED.']/', rawurldecode($found[0])) ? rawurlencode($found[0]) : $found[0],
$component
);
}
/**
* Decodes the URI component characters using a closure.
*/
private static function decode(BackedEnum|Stringable|string|int|null $component, Closure $decoder): ?string
{
$component = self::filterComponent($component);
if (null === $component || '' === $component) {
return $component;
}
if (1 === preg_match(self::REGEXP_CHARS_INVALID, $component)) {
throw new SyntaxError('Invalid component string: '.$component.'.');
}
if (1 === preg_match(self::REGEXP_CHARS_ENCODED, $component)) {
return (string) preg_replace_callback(self::REGEXP_CHARS_ENCODED, $decoder, $component);
}
return $component;
}
/**
* Decodes the URI component without decoding the unreserved characters which are already encoded.
*
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated Since version 7.6.0
* @codeCoverageIgnore
* @see Encoder::decodeNecessary()
*
* Create a new instance from the environment.
*/
#[Deprecated(message:'use League\Uri\Encoder::decodeNecessary() instead', since:'league/uri:7.6.0')]
public static function decodePartial(BackedEnum|Stringable|string|int|null $component): ?string
{
return self::decodeNecessary($component);
}
}