Skip to content

Commit

Permalink
Adding IPv6 compression to BaseUri
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Jul 19, 2024
1 parent 9ed28d3 commit 7452049
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
11 changes: 11 additions & 0 deletions docs/uri/7.0/base-uri.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ echo $baseUri; // display 'http://www.example.com'

The instance also implements PHP's `Stringable` and `JsonSerializable` interface.

In addition to all the non-destructive rules from RFC3968, duting instantiation, the class
will convert the host if possible:

- to its IPv4 decimal representation
- to its compressed IPv6 representation (since version **7.5**)

```php
BaseUri::from('https://0:443/')->getUriString(); // returns 'https://0.0.0.0/
BaseUri::from('FtP://[1050:0000:0000:0000:0005:0000:300c:326b]/path')->getUriString(); // returns 'ftp://[1050::5:0:300c:326b]/path
```

## URI resolution

The `BaseUri::resolve` resolves a URI as a browser would for a relative URI while
Expand Down
5 changes: 5 additions & 0 deletions uri/BaseUri.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use League\Uri\Exceptions\MissingFeature;
use League\Uri\Idna\Converter;
use League\Uri\IPv4\Converter as IPv4Converter;
use League\Uri\IPv6\Converter as IPv6Converter;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface as Psr7UriInterface;
use Stringable;
Expand Down Expand Up @@ -556,6 +557,10 @@ final protected static function formatHost(Psr7UriInterface|UriInterface $uri):
$converted = null;
}

if (false === filter_var($converted, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$converted = IPv6Converter::compress($host);
}

return match (true) {
null !== $converted => $uri->withHost($converted),
'' === $host,
Expand Down
4 changes: 4 additions & 0 deletions uri/BaseUriTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,10 @@ public static function getOriginProvider(): array
'uri' => Uri::new('https://0:443/'),
'expectedOrigin' => 'https://0.0.0.0',
],
'compressed ipv6' => [
'uri' => 'https://[1050:0000:0000:0000:0005:0000:300c:326b]:443/',
'expectedOrigin' => 'https://[1050::5:0:300c:326b]',
],
];
}

Expand Down
1 change: 1 addition & 0 deletions uri/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ All Notable changes to `League\Uri` will be documented in this file

- Adding `SensitiveParameter` attribute in the `Uri` and the `BaseUri` class.
- Improve PSR-7 `Http` class implementation.
- `BaseUri::from` will compress the IPv6 host to its compressed form if possible.

### Deprecated

Expand Down

0 comments on commit 7452049

Please sign in to comment.