-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathURL.php
More file actions
513 lines (469 loc) · 15.2 KB
/
URL.php
File metadata and controls
513 lines (469 loc) · 15.2 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
507
508
509
510
511
512
513
<?php
namespace MaxieSystems;
use MaxieSystems\URL\Exception\InvalidURLException;
use MaxieSystems\URL\PathType;
/**
* Parse URLs
*
* @property string $scheme
* @property string|\Stringable $host
* @property int|string $port
* @property string $user
* @property string $pass
* @property string|\Stringable $path
* @property string|\Stringable $query
* @property string $fragment
*/
class URL implements URLInterface
{
final public static function parse(string $url, bool &$invalid = null): \stdClass
{
$u = parse_url($url);
$r = new \stdClass();
if ($invalid = false === $u) {
foreach (self::$components as $k => $v) {
$r->$k = '';
}
} else {
foreach (self::$components as $k => $v) {
$r->$k = $u[$k] ?? '';
}
}
return $r;
}
final public static function build(object $url): string
{
# My implementation slightly differs from this: https://datatracker.ietf.org/doc/html/rfc3986#section-5.3
$s = '';
if ('' !== $url->scheme) {
$s .= "$url->scheme:";
}
$host = (string)$url->host;
$path = (string)$url->path;
if ('' !== $host) {
$s .= '//';
if ('' !== $url->user) {
$s .= $url->user;
if ($url->pass) {
$s .= ":$url->pass";
}
$s .= '@';
}
$s .= $host;
if ($url->port) {
$s .= ":$url->port";
}
if (self::isPathRootless($path)) {
$s .= '/';
}
}
$s .= $path;
$q = (string)$url->query;
if ('' !== $q) {
$s .= "?$q";
}
if ('' !== $url->fragment) {
$s .= "#$url->fragment";
}
return $s;
}
final public static function encode(string $string): string
{
static $s = [
'%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D',
'%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'
];
static $r = [
'!', '*', "'", "(", ")", ";", ":", "@", "&", "=",
"+", "$", ",", "/", "?", "%", "#", "[", "]"
];
return str_replace($s, $r, rawurlencode($string));
}
final public static function addQueryParameters(string $url, string|array $params): string
{
if (is_array($params)) {
$params = http_build_query($params);
}
$pos = strpos($url, '?');
if (false === $pos) {
$c = '?';
} elseif ($pos === strlen($url) - 1) {
$c = '';
} else {
$c = '&';
}
return $url . $c . $params;
}
/**
* @param string $q
* @param array $params
* @param ?int &$count
* @return string
*/
final public static function deleteQueryParameters(string $q, array $params, int &$count = null): string
{
$count = 0;
if (!$params) {
return $q;
}
$params = array_fill_keys($params, 1);
$s = '';
foreach (explode('&', $q) as $sp) {
$p = explode('=', $sp, 2);
$n = urldecode($p[0]);// \PHP_QUERY_RFC1738
$pos0 = strpos($n, '[');
if (false !== $pos0) {
$pos1 = strpos($n, ']', $pos0 + 1);
if (false !== $pos1) {
$n = substr($n, 0, $pos0);
}
}
if (isset($params[$n])) {
++$count;
} else {
if ('' !== $s) {
$s .= '&';
}
$s .= $sp;
}
}
return $count ? $s : $q;
}
final public static function mergePaths(string $base_path, string $path, PathType &$path_type = null): string
{
# Merge Paths - https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.3
if ('' === $path) {
$path_type = PathType::Empty;
return $base_path;
} elseif ('/' !== $path[0]) {
$path_type = PathType::Rootless;
$pos = strrpos($base_path, '/');
if (false === $pos) {
return $path;
} elseif (0 === $pos) {
# if strrpos returns 0 then $base_path has only 1 slash - the first slash.
return "/$path";
} else {
++$pos;
$p = $base_path;
if ($pos < strlen($base_path)) {
if ('..' === substr($p, $pos)) {
$p .= '/';
} else {
$p = substr($p, 0, $pos);
}
}
return $p . $path;
}
}
$path_type = PathType::Absolute;
return $path;
}
final public static function pathToAbsolute(string $base_path, string $path, PathType &$path_type = null): string
{
# We assume that the $base_url is absolute even if it's not preceded by a slash "/".
if ('' === $base_path) {
$base_path = '/';
} elseif ('/' !== $base_path[0]) {
$base_path = "/$base_path";
}
$path = self::mergePaths($base_path, $path, $path_type);
return self::removeDotSegments($path);
}
final public static function removeDotSegments(string|iterable $raw_path): string
{
if (is_string($raw_path)) {
$raw_path = explode('/', $raw_path);
}
# explode('/', '') : [0 => ''], explode('/', '.') : [0 => '.'], explode('/', '$') : [0 => '$']
# explode('/', '/') : [0 => '', 1 => '']
$is_abs = false;
$i = 0;
$path = [];
foreach ($raw_path as $v) {
if ('..' === $v) {
if (count($path)) {
if (end($path) === '..') {
$path[] = $v;
} else {
array_pop($path);
}
} else {
#$path[] = $v;
}
} elseif ('.' === $v) {
# skip it...
} elseif ('' === $v) {
if (0 === $i) {
$is_abs = true;
}
# skip it...
} else {
$path[] = $v;
}
++$i;
}
$s = $is_abs && $i > 1 ? '/' : '';
if (count($path)) {
$s .= implode('/', $path);
if ('' === $v || '.' === $v || '..' === $v) {
$s .= '/';
}
}
return $s;
}
final public static function isComponentName(string $name): bool
{
return isset(self::$components[$name]);
}
final public static function getComponentNames(): array
{
return array_keys(self::$components);
}
final public static function isPathAbsolute(string $url_path): bool
{
return '' !== $url_path && '/' === $url_path[0];
}
final public static function isPathRelative(string $url_path, bool &$is_empty = null): bool
{
$is_empty = '' === $url_path;
return $is_empty || '/' !== $url_path[0];
}
final public static function isPathRootless(string $url_path): bool
{
# path-rootless: https://datatracker.ietf.org/doc/html/rfc3986#section-3.3
return '' !== $url_path && '/' !== $url_path[0];
}
public function __construct(string|array|object $source)
{
if (is_string($source)) {
if ('' === $source || '#' === $source) {
$source = [];
} else {
$u = parse_url($source);
if (!$u) {
throw new InvalidURLException();
}
/** @var array $source */
$source = $u;
}
} elseif (is_array($source) || ($source instanceof \ArrayAccess)) {
} else {
$source = new ArrayAccessProxy($source);
}
foreach ($this->data as $k => $v) {
if (null !== ($v = $this->filterComponent($k, $source[$k] ?? $v))) {
$this->data[$k] = $v;
}
}
}
final public function isAbsolute(URLType &$type = null): bool
{
$type = $this->getType();
return URLType::Absolute === $type;
}
final public function isEmpty(string $group = null): bool
{
if (null === $group) {
foreach ($this as $v) {
if ('' !== (string)$v) {
return false;
}
}
} elseif (isset(self::$componentGroup[$group])) {
foreach ($this as $k => $v) {
if (!isset(self::$componentGroup[$group][$k])) {
continue;
} elseif ('' !== (string)$v) {
return false;
}
}
} else {
throw new \UnexpectedValueException('Invalid group name');
}
return true;
}
final public function copy(URLInterface|array|\ArrayAccess $source_url, string ...$components): self
{
if ($source_url instanceof URLInterface) {
$copy = [$this, 'copyFromURLInterface'];
# } elseif (is_array($source_url) || ($source_url instanceof \ArrayAccess)) {
} else {
$copy = [$this, 'copyFromArray'];
}
if ($components) {
foreach ($components as $name) {
if (self::isComponentName($name)) {
$copy($source_url, $name);
} elseif (isset(self::$componentGroup[$name])) {
foreach (self::$componentGroup[$name] as $n) {
$copy($source_url, $n);
}
} else {
throw new \UnexpectedValueException('Invalid component name');
}
}
} else {
foreach (self::$components as $name => $c) {
$copy($source_url, $name);
}
}
return $this;
}
final public function getType(): URLType
{
if ('' === (string)$this->scheme) {
if ($this->isEmpty('authority')) {
if (self::isPathRelative($this->path, $is_empty)) {
return $is_empty
&& '' === (string)$this->__get('query')
&& '' === (string)$this->__get('fragment') ? URLType::Empty : URLType::Relative;
} else {
return URLType::RootRelative;
}
} else {
return URLType::ProtocolRelative;
}
} else {
return URLType::Absolute;
}
}
public function __isset($name): bool
{
return self::isComponentName($name);
}
public function __get($name): mixed
{
if (self::isComponentName($name)) {
return $this->data[$name];
}
throw new \Error(EMessages::undefinedProperty($this, $name));
}
final public function __unset($name): void
{
$this->__set($name, null);
}
public function __set($name, $value): void
{
if (self::isComponentName($name)) {
$this->data[$name] = $this->filterComponent($name, $value) ?? '';
} else {
throw new \Error(EMessages::undefinedProperty($this, $name));
}
}
final public function offsetExists(mixed $offset): bool
{
return $this->__isset($offset);
}
final public function offsetGet(mixed $offset): mixed
{
return $this->__get($offset);
}
final public function offsetSet(mixed $offset, mixed $value): void
{
$this->__set($offset, $value);
}
final public function offsetUnset(mixed $offset): void
{
$this->__unset($offset);
}
public function current(): mixed
{
$k = key($this->data);
if (null !== $k) {
$v = $this->data[$k];
return 'mixed' === self::$components[$k]['type'] ? (string)$v : $v;
}
}
final public function next(): void
{
next($this->data);
}
#[\ReturnTypeWillChange]
final public function key(): string
{
return key($this->data);
}
final public function valid(): bool
{
return null !== key($this->data);
}
final public function rewind(): void
{
reset($this->data);
}
public function __clone()
{
foreach ($this->data as $k => $v) {
if (is_object($v)) {
$this->data[$k] = clone $v;
}
}
}
public function __debugInfo(): array
{
$r = $this->toArray();
$r['type'] = $this->getType();
return $r;
}
final public function __toString()
{
return self::Build($this);
}
# function(string $name, string|int|object $value, self $this_url, ...$args): mixed
final public function toStdClass(callable $callback = null, ...$args): \stdClass
{
$r = new \stdClass();
$this->traverse(function (string $k, string|int|object $v) use ($r): void {
$r->$k = $v;
}, $callback, ...$args);
return $r;
}
# function(string $name, string|int|object $value, self $this_url, ...$args): mixed
final public function toArray(callable $callback = null, ...$args): array
{
$r = [];
$this->traverse(function (string $k, string|int|object $v) use (&$r): void {
$r[$k] = $v;
}, $callback, ...$args);
return $r;
}
protected function filterComponent(string $name, mixed $value): mixed
{
return $value;
}
final protected function traverse(callable $action, ?callable $callback, ...$args): void
{
if (null === $callback) {
foreach ($this as $k => $v) {
$action($k, $v);
}
} else {
foreach ($this->data as $k => $v) {
$action($k, $callback($k, $v, $this, ...$args));
}
}
}
private function copyFromURLInterface(URLInterface $source_url, string $name): void
{
$this->data[$name] = $this->filterComponent($name, $source_url->$name) ?? '';
}
private function copyFromArray(array|\ArrayAccess $source_url, string $name): void
{
$this->data[$name] = $this->filterComponent($name, $source_url[$name] ?? '') ?? '';
}
private array $data = [
'scheme' => '', 'host' => '', 'port' => '', 'user' => '', 'pass' => '',
'path' => '', 'query' => '', 'fragment' => ''
];
private static array $components = [
'scheme' => ['type' => 'string'], 'host' => ['type' => 'mixed'], 'port' => ['type' => 'int'],
'user' => ['type' => 'string'], 'pass' => ['type' => 'string'],
'path' => ['type' => 'mixed'], 'query' => ['type' => 'mixed'], 'fragment' => ['type' => 'string']
];
# <authority> - https://datatracker.ietf.org/doc/html/rfc3986#section-3.2
private static array $componentGroup = [
'authority' => ['host' => 'host', 'port' => 'port', 'user' => 'user', 'pass' => 'pass'],
'origin' => ['scheme' => 'scheme', 'host' => 'host', 'port' => 'port'],
];
}