Skip to content

Commit

Permalink
Improve PSR-7 interoperabilities
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Jul 7, 2024
1 parent a2afb28 commit 6b612a0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ All Notable changes to `League\Uri` will be documented in this file
### Fixed

- Adding `SensitiveParameter` attribute in the `Uri` and the `BaseUri` class.
- Improve PSR-7 `Http` class implementation.

### Deprecated

Expand Down
39 changes: 36 additions & 3 deletions Http.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,49 @@
*/
final class Http implements Stringable, Psr7UriInterface, JsonSerializable
{
private function __construct(private readonly UriInterface $uri)
private readonly UriInterface $uri;

private function __construct(UriInterface $uri)
{
if (null === $this->uri->getScheme() && '' === $this->uri->getHost()) {
if (null === $uri->getScheme() && '' === $uri->getHost()) {
throw new SyntaxError('An URI without scheme cannot contain an empty host string according to PSR-7: '.$uri);
}

$port = $this->uri->getPort();
$port = $uri->getPort();
if (null !== $port && ($port < 0 || $port > 65535)) {
throw new SyntaxError('The URI port is outside the established TCP and UDP port ranges: '.$uri);
}

$this->uri = $this->normalizePsr7Uri($uri);
}

/**
* PSR-7 UriInterface makes the following normalization
*
* Safely stringify input when possible for League UriInterface compatibility.
*
* Query, Fragment and User Info when undefined are normalized to the empty string
*/
private function normalizePsr7Uri(UriInterface $uri): UriInterface
{
$components = [];
if ('' === $uri->getFragment()) {
$components['fragment'] = null;
}

if ('' === $uri->getQuery()) {
$components['query'] = null;
}

if ('' === $uri->getUserInfo()) {
$components['user'] = null;
$components['pass'] = null;
}

return match ($components) {
[] => $uri,
default => Uri::fromComponents([...$uri->getComponents(), ...$components]), /* @phpstan-ignore-line */
};
}

/**
Expand Down

0 comments on commit 6b612a0

Please sign in to comment.