-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathModifier.php
More file actions
1561 lines (1337 loc) · 52.2 KB
/
Modifier.php
File metadata and controls
1561 lines (1337 loc) · 52.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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 Deprecated;
use Dom\HTMLDocument;
use DOMDocument;
use DOMException;
use JsonSerializable;
use League\Uri\Components\DataPath;
use League\Uri\Components\Domain;
use League\Uri\Components\Fragment;
use League\Uri\Components\FragmentDirectives;
use League\Uri\Components\HierarchicalPath;
use League\Uri\Components\Host;
use League\Uri\Components\Path;
use League\Uri\Components\Query;
use League\Uri\Components\URLSearchParams;
use League\Uri\Contracts\Conditionable;
use League\Uri\Contracts\FragmentDirective;
use League\Uri\Contracts\FragmentInterface;
use League\Uri\Contracts\PathInterface;
use League\Uri\Contracts\Transformable;
use League\Uri\Contracts\UriAccess;
use League\Uri\Contracts\UriInterface;
use League\Uri\Exceptions\MissingFeature;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\Idna\Converter as IdnaConverter;
use League\Uri\IPv4\Converter as IPv4Converter;
use League\Uri\IPv6\Converter as IPv6Converter;
use League\Uri\KeyValuePair\Converter as KeyValuePairConverter;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface as Psr7UriInterface;
use SensitiveParameter;
use Stringable;
use Uri\Rfc3986\Uri as Rfc3986Uri;
use Uri\WhatWg\Url as WhatWgUrl;
use ValueError;
use function array_keys;
use function class_exists;
use function count;
use function filter_var;
use function implode;
use function in_array;
use function is_array;
use function is_bool;
use function is_string;
use function ltrim;
use function rtrim;
use function str_ends_with;
use function str_starts_with;
use function strpos;
use function strtolower;
use function substr;
use function trim;
use const FILTER_FLAG_IPV4;
use const FILTER_VALIDATE_IP;
class Modifier implements Stringable, JsonSerializable, UriAccess, Conditionable, Transformable
{
private const MASK = '*****';
final public function __construct(protected readonly Rfc3986Uri|WhatWgUrl|Psr7UriInterface|UriInterface $uri)
{
}
public static function wrap(Rfc3986Uri|WhatWgUrl|BackedEnum|Stringable|string $uri): static
{
return new static(match (true) {
$uri instanceof self => $uri->uri,
$uri instanceof Psr7UriInterface,
$uri instanceof UriInterface,
$uri instanceof Rfc3986Uri,
$uri instanceof WhatWgUrl => $uri,
default => Uri::new($uri),
});
}
public function unwrap(): Rfc3986Uri|WhatWgUrl|Psr7UriInterface|UriInterface
{
return $this->uri;
}
public function jsonSerialize(): string
{
return $this->toString();
}
public function __toString(): string
{
return $this->toString();
}
public function toString(): string
{
return match (true) {
$this->uri instanceof Rfc3986Uri,
$this->uri instanceof UriInterface => $this->uri->toString(),
$this->uri instanceof WhatWgUrl => $this->uri->toAsciiString(),
$this->uri instanceof Psr7UriInterface => $this->uri->__toString(),
};
}
public function toDisplayString(): string
{
return ($this->uri instanceof Uri ? $this->uri : Uri::new($this->toString()))->toDisplayString();
}
/**
* Returns the Markdown string representation of the anchor tag with the current instance as its href attribute.
*/
public function toMarkdownAnchor(?string $textContent = null): string
{
return '['.strtr($textContent ?? '{uri}', ['{uri}' => $this->toDisplayString()]).']('.$this->toString().')';
}
/**
* Returns the HTML string representation of the anchor tag with the current instance as its href attribute.
*
* @param iterable<string, string|null|array<string>> $attributes an ordered map of key value. you must quote the value if needed
*
* @throws DOMException
*/
public function toHtmlAnchor(Stringable|string|null $textContent = null, iterable $attributes = []): string
{
FeatureDetection::supportsDom();
$uriString = $this->toString();
$rfc3987String = UriString::toIriString($uriString);
$doc = class_exists(HTMLDocument::class) ? HTMLDocument::createEmpty() : new DOMDocument(encoding:'utf-8'); /* @phpstan-ignore-line */
$element = $doc->createElement('a');
$element->setAttribute('href', $uriString);
$element->appendChild(match (true) {
null === $textContent => $doc->createTextNode($rfc3987String),
default => $doc->createTextNode(strtr((string) $textContent, ['{uri}' => $rfc3987String])),
});
foreach ($attributes as $name => $value) {
if ('href' === strtolower($name) || null === $value) {
continue;
}
if (is_array($value)) {
$value = implode(' ', $value);
}
is_string($value) || throw new ValueError('The attribute `'.$name.'` contains an invalid value.');
$value = trim($value);
if ('' === $value) {
continue;
}
$element->setAttribute($name, $value);
}
false !== ($html = $doc->saveHTML($element)) || throw new DOMException('The HTML generation failed.');
return $html;
}
public function resolve(Rfc3986Uri|WhatWgUrl|Psr7UriInterface|UriInterface|BackedEnum|Stringable|string $uri): static
{
$uriString = match (true) {
$uri instanceof Rfc3986Uri,
$uri instanceof UriInterface => $uri->toString(),
$uri instanceof WhatWgUrl => $uri->toAsciiString(),
$uri instanceof BackedEnum => (string) $uri->value,
default => (string) $uri,
};
if (!$this->uri instanceof Psr7UriInterface) {
return new static($this->uri->resolve($uriString));
}
$components = UriString::parse(UriString::resolve($uriString, $this->toString()));
return new static(
$this->uri
->withFragment($components['fragment'] ?? '')
->withQuery($components['query'] ?? '')
->withPath($components['path'] ?? '')
->withHost($components['host'] ?? '')
->withPort($components['port'] ?? null)
->withUserInfo($components['user'] ?? '', $components['pass'] ?? null)
->withScheme($components['scheme'] ?? '')
);
}
public function normalize(): static
{
if ($this->uri instanceof WhatWgUrl) {
return $this;
}
if ($this->uri instanceof Rfc3986Uri) {
return new static(new Rfc3986Uri($this->uri->toString()));
}
if ($this->uri instanceof UriInterface) {
return new static($this->uri->normalize());
}
$uri = Uri::new($this->uri->__toString())->normalize();
if ($uri->toString() === $this->uri->__toString()) {
return $this;
}
return new static(
$this->uri
->withPath($uri->getPath())
->withHost($uri->getHost() ?? '')
->withUserInfo($uri->getUsername() ?? '', $uri->getPassword())
);
}
public function withScheme(BackedEnum|Stringable|string|null $scheme): static
{
return new static($this->uri->withScheme(self::normalizeComponent($scheme, $this->uri)));
}
public function withUserInfo(
Stringable|string|null $username,
#[SensitiveParameter] Stringable|string|null $password
): static {
if ($this->uri instanceof Rfc3986Uri) {
$userInfo = Encoder::encodeUser($username);
if (null !== $password) {
$userInfo .= ':'.Encoder::encodePassword($password);
}
return new static($this->uri->withUserInfo($userInfo));
}
if ($this->uri instanceof WhatWgUrl) {
if (null !== $username) {
if ($username instanceof BackedEnum) {
$username = $username->value;
}
$username = (string) $username;
}
if (null !== $password) {
if ($password instanceof BackedEnum) {
$password = $password->value;
}
$password = (string) $password;
}
return new static($this->uri->withUsername($username)->withPassword($password));
}
if (null == $username && $this->uri instanceof Psr7UriInterface) {
$username = '';
}
if ($username instanceof BackedEnum) {
$username = (string) $username->value;
}
if ($password instanceof BackedEnum) {
$password = (string) $password->value;
}
return new static($this->uri->withUserInfo(
$username instanceof Stringable ? (string) $username : $username,
$password instanceof Stringable ? (string) $password : $password,
));
}
/**
* Returns a new instance with the entire UserInfo component redacted.
*
* Examples:
* http://user:pass@host → http://[REDACTED]@host
* http://user@host → http://[REDACTED]@host
*/
public function redactUserInfo(): static
{
if ($this->uri instanceof WhatWgUrl) {
if (null !== $this->uri->getUsername() || null !== $this->uri->getPassword()) {
return new static($this->uri->withUsername(self::MASK)->withPassword(null));
}
return $this;
}
if (null === $this->uri->getUserInfo()) {
return $this;
}
return new static($this->uri->withUserInfo(self::MASK));
}
public function withHost(BackedEnum|Stringable|string|null $host): static
{
$host = self::normalizeComponent($host, $this->uri);
if ($this->uri instanceof Rfc3986Uri) {
if (null !== $host) {
$host = IdnaConverter::toAscii($host)->domain();
}
}
return new static($this->uri->withHost($host));
}
public function withFragment(BackedEnum|Stringable|string|null $fragment): static
{
if ($fragment instanceof FragmentDirective) {
$fragment = new FragmentDirectives($fragment);
}
if ($fragment instanceof BackedEnum) {
$fragment = (string) $fragment->value;
}
if (!$fragment instanceof FragmentInterface) {
$fragment = str_starts_with((string) $fragment, FragmentDirectives::DELIMITER)
? FragmentDirectives::fromFragment($fragment)
: Fragment::new($fragment);
}
return new static($this->uri->withFragment(
$this->uri instanceof Psr7UriInterface
? $fragment->toString()
: $fragment->value()
));
}
public function withPort(?int $port): static
{
return new static($this->uri->withPort($port));
}
public function withPath(BackedEnum|Stringable|string $path): static
{
if ($this->uri instanceof Rfc3986Uri) {
$path = Encoder::encodePath($path);
}
return new static(self::normalizePath($this->uri, Path::new($path)));
}
final public function transform(callable $callback): static
{
return $callback($this);
}
final public function when(callable|bool $condition, callable $onSuccess, ?callable $onFail = null): static
{
if (!is_bool($condition)) {
$condition = $condition($this);
}
return match (true) {
$condition => $onSuccess($this),
null !== $onFail => $onFail($this),
default => $this,
} ?? $this;
}
/*********************************
* Query modifier methods
*********************************/
public function withQuery(BackedEnum|Stringable|string|null $query): static
{
$query = self::normalizeComponent($query, $this->uri);
$query = match (true) {
$this->uri instanceof Rfc3986Uri => match (true) {
Encoder::isQueryEncoded($query) => $query,
default => Encoder::encodeQueryOrFragment($query),
},
$this->uri instanceof WhatWgUrl => URLSearchParams::new($query)->value(),
default => $query,
};
return match (true) {
$this->uri instanceof Rfc3986Uri && $query === $this->uri->getRawQuery(),
$query === $this->uri->getQuery() => $this,
default => new static($this->uri->withQuery($query)),
};
}
/**
* Change the encoding of the query.
*/
public function encodeQuery(KeyValuePairConverter|int $to, KeyValuePairConverter|int|null $from = null, StringCoercionMode $coercionMode = StringCoercionMode::Native): static
{
if (!$to instanceof KeyValuePairConverter) {
$to = KeyValuePairConverter::fromEncodingType($to);
}
$from = match (true) {
null === $from => KeyValuePairConverter::fromRFC3986(),
!$from instanceof KeyValuePairConverter => KeyValuePairConverter::fromEncodingType($from),
default => $from,
};
if ($to == $from) {
return $this;
}
$originalQuery = $this->uri->getQuery();
if (null === $originalQuery || '' === trim($originalQuery)) {
return $this;
}
/** @var string $query */
$query = QueryString::buildFromPairs(QueryString::parseFromValue($originalQuery, $from), $to, $coercionMode);
if ($query === $originalQuery) {
return $this;
}
return $this->withQuery($query);
}
/**
* Sort the URI query by keys.
*/
public function sortQuery(): static
{
return $this->withQuery(Query::fromUri($this->uri)->sort()->value());
}
/**
* Append the new query data to the existing URI query.
*/
public function appendQuery(BackedEnum|Stringable|string|null $query, StringCoercionMode $coercionMode = StringCoercionMode::Native): static
{
return $this->withQuery(Query::fromUri($this->uri)->append($query, $coercionMode)->value());
}
/**
* Prepend the new query data to the existing URI query.
*/
public function prependQuery(BackedEnum|Stringable|string|null $query, StringCoercionMode $coercionMode = StringCoercionMode::Native): static
{
return $this->withQuery(Query::fromUri($this->uri)->prepend($query, $coercionMode)->value());
}
/**
* Merge query pairs with the existing URI query.
*
* @param iterable<int, array{0:string, 1:string|null}> $pairs
*/
public function appendQueryPairs(iterable $pairs, string $prefix = '', StringCoercionMode $coercionMode = StringCoercionMode::Native): self
{
return $this->appendQuery(Query::fromPairs($pairs, prefix: $prefix, coercionMode: $coercionMode)->value());
}
public function prefixQueryPairs(string $prefix, StringCoercionMode $coercionMode = StringCoercionMode::Native): self
{
return $this->withQuery(Query::fromPairs(Query::fromUri($this->uri), prefix: $prefix, coercionMode: $coercionMode)->value());
}
public function prefixQueryParameters(string $prefix, QueryComposeMode $composeMode = QueryComposeMode::Native): self
{
return $this->withQuery(Query::fromVariable(Query::fromUri($this->uri)->parameters(), prefix: $prefix, composeMode: $composeMode));
}
/**
* Append PHP query parameters to the existing URI query.
*/
public function appendQueryParameters(object|array $parameters, string $prefix = '', QueryComposeMode $composeMode = QueryComposeMode::Native): self
{
return $this->appendQuery(Query::fromVariable($parameters, prefix: $prefix, composeMode: $composeMode)->value());
}
/**
* Prepend PHP query parameters to the existing URI query.
*/
public function prependQueryParameters(object|array $parameters, string $prefix = '', QueryComposeMode $composeMode = QueryComposeMode::Native): self
{
return $this->withQuery(Query::fromVariable($parameters, prefix: $prefix, composeMode: $composeMode)->append(Query::fromUri($this->uri)->value())->value());
}
public function replaceQueryParameter(string $name, mixed $value, QueryComposeMode $composeMode = QueryComposeMode::Native): self
{
return $this->withQuery(Query::fromUri($this->uri)->replaceParameter($name, $value, $composeMode)->value());
}
/**
* Merge a new query with the existing URI query.
*/
public function mergeQuery(BackedEnum|Stringable|string|null $query, StringCoercionMode $coercionMode = StringCoercionMode::Native): static
{
return $this->withQuery(Query::fromUri($this->uri)->merge($query, $coercionMode)->value());
}
/**
* Returns a new instance with the specified query values redacted.
*
* Only values are redacted. Missing keys are ignored.
*
* Example: redactQueryPairs(token)
* ?token=abc&mode=edit → token=[REDACTED]&mode=edit (when 'token' is passed)
*/
public function redactQueryPairs(string ...$keys): static
{
if ([] === $keys) {
return $this;
}
$hasChanged = false;
$pairs = [];
foreach (Query::fromUri($this->uri) as $pair) {
if (in_array($pair[0], $keys, true)) {
$hasChanged = true;
$pair[1] = self::MASK;
}
$pairs[] = $pair[0].'='.$pair[1];
}
return $hasChanged ? $this->withQuery(implode('&', $pairs)) : $this;
}
/**
* Merge query pairs with the existing URI query.
*
* @param iterable<int, array{0:string, 1:string|null}> $pairs
*/
public function mergeQueryPairs(iterable $pairs, string $prefix = '', StringCoercionMode $coercionMode = StringCoercionMode::Native): self
{
$currentPairs = [...Query::fromUri($this->uri)->pairs()];
$pairs = [...$pairs];
return match (true) {
[] === $pairs,
$currentPairs === $pairs => $this,
default => $this->mergeQuery(Query::fromPairs($pairs, prefix: $prefix, coercionMode: $coercionMode)->value()),
};
}
/**
* Merge PHP query parameters with the existing URI query.
*/
public function mergeQueryParameters(object|array $parameters, string $prefix = '', QueryComposeMode $composeMode = QueryComposeMode::Native): self
{
return $this->withQuery(Query::fromUri($this->uri)->mergeParameters($parameters, prefix: $prefix, composeMode: $composeMode)->value());
}
/**
* Remove query data according to their key name.
*/
public function removeQueryPairsByKey(string ...$keys): static
{
$query = Query::fromUri($this->uri);
$newQuery = $query->withoutPairByKey(...$keys);
return $newQuery->value() === $query->value() ? $this : $this->withQuery($newQuery);
}
/**
* Remove query pair according to their value.
*/
public function removeQueryPairsByValue(array|BackedEnum|Stringable|string|int|float|bool|null $values, StringCoercionMode $coercionMode = StringCoercionMode::Native): static
{
$query = Query::fromUri($this->uri);
$newQuery = $query->withoutPairByValue($values, $coercionMode);
return $newQuery->value() === $query->value() ? $this : $this->withQuery($newQuery);
}
/**
* Remove query-pair according to their key/value name.
*/
public function removeQueryPairsByKeyValue(string $key, BackedEnum|Stringable|string|int|bool|null $value, StringCoercionMode $coercionMode = StringCoercionMode::Native): static
{
$query = Query::fromUri($this->uri);
$newQuery = $query->withoutPairByKeyValue($key, $value, $coercionMode);
return $newQuery->value() === $query->value() ? $this : $this->withQuery($newQuery);
}
/**
* Remove query data according to their PHP parameter key name.
*/
public function removeQueryParameters(string ...$keys): static
{
$query = Query::fromUri($this->uri);
$newQuery = $query->withoutParameters(...$keys);
return $newQuery->value() === $query->value() ? $this : $this->withQuery($newQuery);
}
/**
* Remove empty pairs from the URL query component.
*
* A pair is considered empty if its name is the empty string
* and its value is either the empty string or the null value
*/
public function removeEmptyQueryPairs(): static
{
return $this->withQuery(Query::fromUri($this->uri)->withoutEmptyPairs()->value());
}
/**
* Returns an instance where numeric indices associated to PHP's array like key are removed.
*
* This method MUST retain the state of the current instance, and return
* an instance that contains the query component normalized so that numeric indexes
* are removed from the pair key value.
*
* ie.: toto[3]=bar[3]&foo=bar becomes toto[]=bar[3]&foo=bar
*/
public function removeQueryParameterIndices(): static
{
$query = Query::fromUri($this->uri);
$newQuery = $query->withoutNumericIndices()->value();
return match ($newQuery) {
$query->value() => $this,
default => $this->withQuery($newQuery),
};
}
public function replaceQueryPair(int $offset, string $key, BackedEnum|Stringable|string|int|float|bool|null $value, StringCoercionMode $coercionMode = StringCoercionMode::Native): static
{
return $this->withQuery(Query::fromUri($this->uri)->replace($offset, $key, $value, $coercionMode)->value());
}
/*********************************
* Host modifier methods
*********************************/
/**
* Add the root label to the URI.
*/
public function addRootLabel(): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
return match (true) {
null === $host,
str_ends_with($host, '.') => $this,
default => $this->withHost($host.'.'),
};
}
/**
* Append a label or a host to the current URI host.
*
* @throws SyntaxError If the host cannot be appended
*/
public function appendLabel(BackedEnum|Stringable|string|null $label): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$isAsciiDomain = null === $host || IdnaConverter::toAscii($host)->domain() === $host;
$host = Host::new($host);
$label = Host::new($label);
if (null === $label->value()) {
return $this;
}
if ($host->isIpv4()) {
return $this->withHost($host->value().'.'.ltrim($label->value(), '.'));
}
if (!$host->isDomain()) {
throw new SyntaxError('The URI host '.$host->toString().' cannot be appended.');
}
$newHost = Domain::new($host)->append($label);
$newHost = !$isAsciiDomain ? $newHost->toUnicode() : $newHost->toAscii();
return $this->withHost($newHost);
}
/**
* Convert the URI host part to its ASCII value.
*/
public function hostToAscii(): static
{
$currentHost = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$host = IdnaConverter::toAsciiOrFail((string) $currentHost);
return match (true) {
null === $currentHost,
'' === $currentHost,
$host === $currentHost => $this,
default => $this->withHost($host),
};
}
/**
* Convert the URI host part to its Unicode value.
*/
public function hostToUnicode(): static
{
$currentHost = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$host = IdnaConverter::toUnicode((string) $currentHost)->domain();
return match (true) {
null === $currentHost,
'' === $currentHost,
$host === $currentHost => $this,
default => $this->withHost($host),
};
}
/**
* Normalizes the URI host content to an IPv4 dot-decimal notation if possible
* otherwise returns the uri instance unchanged.
*
* @see https://url.spec.whatwg.org/#concept-ipv4-parser
*/
public function hostToDecimal(): static
{
$currentHost = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$hostIp = self::ipv4Converter()->toDecimal($currentHost);
return match (true) {
null === $currentHost,
'' === $currentHost,
null === $hostIp,
$currentHost === $hostIp => $this,
default => $this->withHost($hostIp),
};
}
/**
* Normalizes the URI host content to a IPv4 octal notation if possible
* otherwise returns the uri instance unchanged.
*
* @see https://url.spec.whatwg.org/#concept-ipv4-parser
*/
public function hostToOctal(): static
{
$currentHost = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$hostIp = self::ipv4Converter()->toOctal($currentHost);
return match (true) {
null === $currentHost,
'' === $currentHost,
null === $hostIp,
$currentHost === $hostIp => $this,
default => $this->withHost($hostIp),
};
}
/**
* Normalizes the URI host content to a IPv4 octal notation if possible
* otherwise returns the uri instance unchanged.
*
* @see https://url.spec.whatwg.org/#concept-ipv4-parser
*/
public function hostToHexadecimal(): static
{
$currentHost = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$hostIp = self::ipv4Converter()->toHexadecimal($currentHost);
return match (true) {
null === $currentHost,
'' === $currentHost,
null === $hostIp,
$currentHost === $hostIp => $this,
default => $this->withHost($hostIp),
};
}
public function hostToIpv6Compressed(): static
{
return $this->withHost(IPv6Converter::compress($this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost()));
}
public function hostToIpv6Expanded(): static
{
return $this->withHost(IPv6Converter::expand($this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost()));
}
/**
* Prepend a label or a host to the current URI host.
*
* @throws SyntaxError If the host cannot be prepended
*/
public function prependLabel(BackedEnum|Stringable|string|null $label): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$isAsciiDomain = null === $host || IdnaConverter::toAscii($host)->domain() === $host;
$host = Host::new($host);
$label = Host::new($label);
if (null === $label->value()) {
return $this;
}
if ($host->isIpv4()) {
return $this->withHost(rtrim($label->value(), '.').'.'.$host->value());
}
if (!$host->isDomain()) {
throw new SyntaxError('The URI host '.$host->toString().' cannot be prepended.');
}
$newHost = Domain::new($host)->prepend($label);
$newHost = !$isAsciiDomain ? $newHost->toUnicode() : $newHost->toAscii();
return $this->withHost($newHost);
}
/**
* Remove host labels according to their offset.
*/
public function removeLabels(int ...$keys): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
if (null === $host || ('' === $host && $this->uri instanceof Psr7UriInterface)) {
return $this;
}
$isAsciiDomain = IdnaConverter::toAscii($host)->domain() === $host;
$newHost = Domain::new($host)->withoutLabel(...$keys);
$newHost = !$isAsciiDomain ? $newHost->toUnicode() : $newHost->toAscii();
return $this->withHost($newHost);
}
/**
* Remove the root label to the URI.
*/
public function removeRootLabel(): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
return match (true) {
null === $host,
'' === $host,
!str_ends_with($host, '.') => $this,
default => $this->withHost(substr($host, 0, -1)),
};
}
/**
* Slice the host from the URI.
*/
public function sliceLabels(int $offset, ?int $length = null): static
{
$currentHost = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
if (null === $currentHost || ('' === $currentHost && $this->uri instanceof Psr7UriInterface)) {
return $this;
}
$isAsciiDomain = IdnaConverter::toAscii($currentHost)->domain() === $currentHost;
$host = Domain::new($currentHost)->slice($offset, $length);
$host = !$isAsciiDomain ? $host->toUnicode() : $host->toAscii();
if ($currentHost === $host) {
return $this;
}
return $this->withHost($host);
}
/**
* Remove the host zone identifier.
*/
public function removeZoneId(): static
{
$host = Host::fromUri($this->uri);
return match (true) {
$host->hasZoneIdentifier() => $this->withHost($host->withoutZoneIdentifier()->value()),
default => $this,
};
}
/**
* Replace a label of the current URI host.
*/
public function replaceLabel(int $offset, Stringable|string|null $label): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
$isAsciiDomain = null === $host || IdnaConverter::toAscii($host)->domain() === $host;
$newHost = Domain::new($host)->withLabel($offset, $label);
$newHost = !$isAsciiDomain ? $newHost->toUnicode() : $newHost->toAscii();
return $this->withHost($newHost);
}
public function normalizeIp(): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
if (in_array($host, [null, ''], true)) {
return $this;
}
try {
$converted = IPv4Converter::fromEnvironment()->toDecimal($host);
} catch (MissingFeature) {
$converted = null;
}
if (false === filter_var($converted, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$converted = IPv6Converter::compress($host);
}
if ($converted !== $host) {
return $this->withHost($converted);
}
return $this;
}
public function normalizeHost(): static
{
$host = $this->uri instanceof WhatWgUrl ? $this->uri->getAsciiHost() : $this->uri->getHost();
if (in_array($host, [null, ''], true)) {
return $this;
}
$new = $this->normalizeIp();
$newHost = $new->uri instanceof WhatWgUrl ? $new->uri->getAsciiHost() : $new->uri->getHost();
if ($newHost !== $host) {
return $new;
}
return $this->withHost(Host::new($host)->toAscii());
}
/*********************************
* Path modifier methods
*********************************/
/**
* Add a new base path to the URI path.
*/
public function addBasePath(BackedEnum|Stringable|string $path): static
{
/** @var HierarchicalPath $path */
$path = HierarchicalPath::new($path)->withLeadingSlash();
/** @var HierarchicalPath $currentPath */
$currentPath = HierarchicalPath::fromUri($this->uri)->withLeadingSlash();
return match (true) {
!str_starts_with($currentPath->toString(), $path->toString()) => $this->withPath($path->append($currentPath)->toString()),
default => $this->withPath($currentPath),
};
}
/**
* Add a leading slash to the URI path.
*/
public function addLeadingSlash(): static
{
$path = $this->uri->getPath();
return match (true) {
str_starts_with($path, '/') => $this,
default => $this->withPath('/'.$path),
};
}
/**
* Add a trailing slash to the URI path.
*/
public function addTrailingSlash(): static
{
$path = $this->uri->getPath();
return match (true) {
str_ends_with($path, '/') => $this,
default => $this->withPath($path.'/'),
};
}
/**
* Append a new path or add a path to the URI path.
*/
public function appendPath(BackedEnum|Stringable|string $path): static
{
return $this->withPath(HierarchicalPath::fromUri($this->uri)->append($path));
}
/**
* Prepend a path or add a new path to the URI path.
*/
public function prependPath(BackedEnum|Stringable|string $path): static
{
return $this->withPath(HierarchicalPath::fromUri($this->uri)->prepend($path));
}
/**
* Append a list of segments or a new path to the URI path.