updated plugin WP-WebAuthn version 1.3.4

This commit is contained in:
2024-10-09 12:44:38 +00:00
committed by Gitium
parent f970470c59
commit e73c3de31d
56 changed files with 1040 additions and 1173 deletions

View File

@ -44,21 +44,22 @@
}
],
"require": {
"php": "^7.4 || ^8.0",
"php": "^8.1",
"ext-json": "*",
"psr/http-message": "^1.0",
"psr/http-message": "^1.0.1",
"league/uri-interfaces": "^2.3"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^v3.3.2",
"nyholm/psr7": "^1.5",
"php-http/psr7-integration-tests": "^1.1",
"phpstan/phpstan": "^1.2.0",
"friendsofphp/php-cs-fixer": "^v3.9.5",
"nyholm/psr7": "^1.5.1",
"php-http/psr7-integration-tests": "^1.1.1",
"phpbench/phpbench": "^1.2.6",
"phpstan/phpstan": "^1.8.5",
"phpstan/phpstan-deprecation-rules": "^1.0",
"phpstan/phpstan-phpunit": "^1.0.0",
"phpstan/phpstan-strict-rules": "^1.1.0",
"phpunit/phpunit": "^9.5.10",
"psr/http-factory": "^1.0"
"phpstan/phpstan-phpunit": "^1.1.1",
"phpstan/phpstan-strict-rules": "^1.4.3",
"phpunit/phpunit": "^9.5.24",
"psr/http-factory": "^1.0.1"
},
"autoload": {
"psr-4": {
@ -74,6 +75,7 @@
"league/uri-schemes": "^1.0"
},
"scripts": {
"benchmark": "phpbench run src --report=default",
"phpcs": "php-cs-fixer fix -v --diff --dry-run --allow-risky=yes --ansi",
"phpcs:fix": "php-cs-fixer fix -vvv --allow-risky=yes --ansi",
"phpstan": "phpstan analyse -l max -c phpstan.neon src --ansi --memory-limit=256M",

View File

@ -17,19 +17,14 @@ use JsonSerializable;
use League\Uri\Contracts\UriInterface;
use League\Uri\Exceptions\SyntaxError;
use Psr\Http\Message\UriInterface as Psr7UriInterface;
use function is_object;
use Stringable;
use function is_scalar;
use function method_exists;
use function sprintf;
final class Http implements Psr7UriInterface, JsonSerializable
{
private UriInterface $uri;
private function __construct(UriInterface $uri)
private function __construct(private readonly UriInterface $uri)
{
$this->validate($uri);
$this->uri = $uri;
$this->validate($this->uri);
}
/**
@ -39,19 +34,18 @@ final class Http implements Psr7UriInterface, JsonSerializable
*/
private function validate(UriInterface $uri): void
{
$scheme = $uri->getScheme();
if (null === $scheme && '' === $uri->getHost()) {
throw new SyntaxError(sprintf('an URI without scheme can not contains a empty host string according to PSR-7: %s', (string) $uri));
if (null === $uri->getScheme() && '' === $uri->getHost()) {
throw new SyntaxError('An URI without scheme can not contains a empty host string according to PSR-7: '.$uri);
}
$port = $uri->getPort();
if (null !== $port && ($port < 0 || $port > 65535)) {
throw new SyntaxError(sprintf('The URI port is outside the established TCP and UDP port ranges: %s', (string) $uri->getPort()));
throw new SyntaxError('The URI port is outside the established TCP and UDP port ranges: '.$uri);
}
}
/**
* Static method called by PHP's var export.
* @param array{uri:UriInterface} $components
*/
public static function __set_state(array $components): self
{
@ -60,10 +54,8 @@ final class Http implements Psr7UriInterface, JsonSerializable
/**
* Create a new instance from a string.
*
* @param string|mixed $uri
*/
public static function createFromString($uri = ''): self
public static function createFromString(Stringable|UriInterface|String $uri = ''): self
{
return new self(Uri::createFromString($uri));
}
@ -91,21 +83,18 @@ final class Http implements Psr7UriInterface, JsonSerializable
* Create a new instance from a URI and a Base URI.
*
* The returned URI must be absolute.
*
* @param mixed $uri the input URI to create
* @param mixed $base_uri the base URI used for reference
*/
public static function createFromBaseUri($uri, $base_uri = null): self
{
public static function createFromBaseUri(
Stringable|UriInterface|String $uri,
Stringable|UriInterface|String $base_uri = null
): self {
return new self(Uri::createFromBaseUri($uri, $base_uri));
}
/**
* Create a new instance from a URI object.
*
* @param Psr7UriInterface|UriInterface $uri the input URI to create
*/
public static function createFromUri($uri): self
public static function createFromUri(Psr7UriInterface|UriInterface $uri): self
{
if ($uri instanceof UriInterface) {
return new self($uri);
@ -178,145 +167,6 @@ final class Http implements Psr7UriInterface, JsonSerializable
return (string) $this->uri->getFragment();
}
/**
* {@inheritDoc}
*/
public function withScheme($scheme): self
{
/** @var string $scheme */
$scheme = $this->filterInput($scheme);
if ('' === $scheme) {
$scheme = null;
}
$uri = $this->uri->withScheme($scheme);
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* Safely stringify input when possible.
*
* @param mixed $str the value to evaluate as a string
*
* @throws SyntaxError if the submitted data can not be converted to string
*
* @return string|mixed
*/
private function filterInput($str)
{
if (is_scalar($str) || (is_object($str) && method_exists($str, '__toString'))) {
return (string) $str;
}
return $str;
}
/**
* {@inheritDoc}
*/
public function withUserInfo($user, $password = null): self
{
/** @var string $user */
$user = $this->filterInput($user);
if ('' === $user) {
$user = null;
}
$uri = $this->uri->withUserInfo($user, $password);
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* {@inheritDoc}
*/
public function withHost($host): self
{
/** @var string $host */
$host = $this->filterInput($host);
if ('' === $host) {
$host = null;
}
$uri = $this->uri->withHost($host);
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* {@inheritDoc}
*/
public function withPort($port): self
{
$uri = $this->uri->withPort($port);
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* {@inheritDoc}
*/
public function withPath($path): self
{
$uri = $this->uri->withPath($path);
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* {@inheritDoc}
*/
public function withQuery($query): self
{
/** @var string $query */
$query = $this->filterInput($query);
if ('' === $query) {
$query = null;
}
$uri = $this->uri->withQuery($query);
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* {@inheritDoc}
*/
public function withFragment($fragment): self
{
/** @var string $fragment */
$fragment = $this->filterInput($fragment);
if ('' === $fragment) {
$fragment = null;
}
$uri = $this->uri->withFragment($fragment);
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* {@inheritDoc}
*/
@ -332,4 +182,88 @@ final class Http implements Psr7UriInterface, JsonSerializable
{
return $this->uri->__toString();
}
/**
* Safely stringify input when possible for League UriInterface compatibility.
*
* @throws SyntaxError
*/
private function filterInput(mixed $str): string|null
{
if (!is_scalar($str) && !$str instanceof Stringable) {
throw new SyntaxError('The component must be a string, a scalar or a Stringable object; `'.gettype($str).'` given.');
}
$str = (string) $str;
if ('' === $str) {
return null;
}
return $str;
}
private function newInstance(UriInterface $uri): self
{
if ((string) $uri === (string) $this->uri) {
return $this;
}
return new self($uri);
}
/**
* {@inheritDoc}
*/
public function withScheme($scheme): self
{
return $this->newInstance($this->uri->withScheme($this->filterInput($scheme)));
}
/**
* {@inheritDoc}
*/
public function withUserInfo($user, $password = null): self
{
return $this->newInstance($this->uri->withUserInfo($this->filterInput($user), $password));
}
/**
* {@inheritDoc}
*/
public function withHost($host): self
{
return $this->newInstance($this->uri->withHost($this->filterInput($host)));
}
/**
* {@inheritDoc}
*/
public function withPort($port): self
{
return $this->newInstance($this->uri->withPort($port));
}
/**
* {@inheritDoc}
*/
public function withPath($path): self
{
return $this->newInstance($this->uri->withPath($path));
}
/**
* {@inheritDoc}
*/
public function withQuery($query): self
{
return $this->newInstance($this->uri->withQuery($this->filterInput($query)));
}
/**
* {@inheritDoc}
*/
public function withFragment($fragment): self
{
return $this->newInstance($this->uri->withFragment($this->filterInput($fragment)));
}
}

View File

@ -21,8 +21,11 @@ use League\Uri\Exceptions\IdnSupportMissing;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\Idna\Idna;
use Psr\Http\Message\UriInterface as Psr7UriInterface;
use SensitiveParameter;
use Stringable;
use TypeError;
use function array_filter;
use function array_key_first;
use function array_map;
use function base64_decode;
use function base64_encode;
@ -33,14 +36,15 @@ use function filter_var;
use function implode;
use function in_array;
use function inet_pton;
use function is_object;
use function is_int;
use function is_scalar;
use function method_exists;
use function is_string;
use function ltrim;
use function preg_match;
use function preg_replace;
use function preg_replace_callback;
use function rawurlencode;
use function sprintf;
use function str_contains;
use function str_replace;
use function strlen;
use function strpos;
@ -81,14 +85,14 @@ final class Uri implements UriInterface
*
* @var string
*/
private const REGEXP_CHARS_UNRESERVED = 'A-Za-z0-9_\-\.~';
private const REGEXP_CHARS_UNRESERVED = 'A-Za-z\d_\-\.~';
/**
* RFC3986 schema regular expression pattern.
*
* @link https://tools.ietf.org/html/rfc3986#section-3.1
*/
private const REGEXP_SCHEME = ',^[a-z]([-a-z0-9+.]+)?$,i';
private const REGEXP_SCHEME = ',^[a-z]([-a-z\d+.]+)?$,i';
/**
* RFC3986 host identified by a registered name regular expression pattern.
@ -96,9 +100,9 @@ final class Uri implements UriInterface
* @link https://tools.ietf.org/html/rfc3986#section-3.2.2
*/
private const REGEXP_HOST_REGNAME = '/^(
(?<unreserved>[a-z0-9_~\-\.])|
(?<unreserved>[a-z\d_~\-\.])|
(?<sub_delims>[!$&\'()*+,;=])|
(?<encoded>%[A-F0-9]{2})
(?<encoded>%[A-F\d]{2})
)+$/x';
/**
@ -114,9 +118,9 @@ final class Uri implements UriInterface
* @link https://tools.ietf.org/html/rfc3986#section-3.2.2
*/
private const REGEXP_HOST_IPFUTURE = '/^
v(?<version>[A-F0-9])+\.
v(?<version>[A-F\d])+\.
(?:
(?<unreserved>[a-z0-9_~\-\.])|
(?<unreserved>[a-z\d_~\-\.])|
(?<sub_delims>[!$&\'()*+,;=:]) # also include the : character
)+
$/ix';
@ -176,20 +180,11 @@ final class Uri implements UriInterface
];
/**
* URI validation methods per scheme.
* Maximum number of formatted host cached.
*
* @var array<string>
* @var int
*/
private const SCHEME_VALIDATION_METHOD = [
'data' => 'isUriWithSchemeAndPathOnly',
'file' => 'isUriWithSchemeHostAndPathOnly',
'ftp' => 'isNonEmptyHostUriWithoutFragmentAndQuery',
'gopher' => 'isNonEmptyHostUriWithoutFragmentAndQuery',
'http' => 'isNonEmptyHostUri',
'https' => 'isNonEmptyHostUri',
'ws' => 'isNonEmptyHostUriWithoutFragment',
'wss' => 'isNonEmptyHostUriWithoutFragment',
];
private const MAXIMUM_FORMATTED_HOST_CACHED = 100;
/**
* All ASCII letters sorted by typical frequency of occurrence.
@ -203,7 +198,7 @@ final class Uri implements UriInterface
private ?string $host;
private ?int $port;
private ?string $authority;
private string $path = '';
private string $path;
private ?string $query;
private ?string $fragment;
private ?string $uri;
@ -211,7 +206,7 @@ final class Uri implements UriInterface
private function __construct(
?string $scheme,
?string $user,
?string $pass,
#[SensitiveParameter] ?string $pass,
?string $host,
?int $port,
string $path,
@ -226,49 +221,49 @@ final class Uri implements UriInterface
$this->path = $this->formatPath($path);
$this->query = $this->formatQueryAndFragment($query);
$this->fragment = $this->formatQueryAndFragment($fragment);
$this->assertValidState();
}
/**
* Format the Scheme and Host component.
*
* @param ?string $scheme
* @throws SyntaxError if the scheme is invalid
*/
private function formatScheme(?string $scheme): ?string
{
if (null === $scheme) {
if (null === $scheme || array_key_exists($scheme, self::SCHEME_DEFAULT_PORT)) {
return $scheme;
}
$formatted_scheme = strtolower($scheme);
if (1 === preg_match(self::REGEXP_SCHEME, $formatted_scheme)) {
if (array_key_exists($formatted_scheme, self::SCHEME_DEFAULT_PORT) || 1 === preg_match(self::REGEXP_SCHEME, $formatted_scheme)) {
return $formatted_scheme;
}
throw new SyntaxError(sprintf('The scheme `%s` is invalid.', $scheme));
throw new SyntaxError('The scheme `'.$scheme.'` is invalid.');
}
/**
* Set the UserInfo component.
* @param ?string $user
* @param ?string $password
*/
private function formatUserInfo(?string $user, ?string $password): ?string
{
private function formatUserInfo(
?string $user,
#[SensitiveParameter] ?string $password
): ?string {
if (null === $user) {
return $user;
return null;
}
static $user_pattern = '/(?:[^%'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f0-9]{2}))/';
$user = preg_replace_callback($user_pattern, [Uri::class, 'urlEncodeMatch'], $user);
static $user_pattern = '/[^%'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f\d]{2})/';
$user = preg_replace_callback($user_pattern, Uri::urlEncodeMatch(...), $user);
if (null === $password) {
return $user;
}
static $password_pattern = '/(?:[^%:'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f0-9]{2}))/';
static $password_pattern = '/[^%:'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.']++|%(?![A-Fa-f\d]{2})/';
return $user.':'.preg_replace_callback($password_pattern, [Uri::class, 'urlEncodeMatch'], $password);
return $user.':'.preg_replace_callback($password_pattern, Uri::urlEncodeMatch(...), $password);
}
/**
@ -281,7 +276,6 @@ final class Uri implements UriInterface
/**
* Validate and Format the Host component.
* @param ?string $host
*/
private function formatHost(?string $host): ?string
{
@ -289,11 +283,18 @@ final class Uri implements UriInterface
return $host;
}
if ('[' !== $host[0]) {
return $this->formatRegisteredName($host);
static $formattedHostCache = [];
if (isset($formattedHostCache[$host])) {
return $formattedHostCache[$host];
}
return $this->formatIp($host);
$formattedHost = '[' === $host[0] ? $this->formatIp($host) : $this->formatRegisteredName($host);
$formattedHostCache[$host] = $formattedHost;
if (self::MAXIMUM_FORMATTED_HOST_CACHED < count($formattedHostCache)) {
unset($formattedHostCache[array_key_first($formattedHostCache)]);
}
return $formattedHost;
}
/**
@ -312,7 +313,7 @@ final class Uri implements UriInterface
}
if (1 === preg_match(self::REGEXP_HOST_GEN_DELIMS, $formatted_host)) {
throw new SyntaxError(sprintf('The host `%s` is invalid : a registered name can not contain URI delimiters or spaces', $host));
throw new SyntaxError('The host `'.$host.'` is invalid : a registered name can not contain URI delimiters or spaces.');
}
$info = Idna::toAscii($host, Idna::IDNA2008_ASCII);
@ -341,35 +342,33 @@ final class Uri implements UriInterface
$pos = strpos($ip, '%');
if (false === $pos) {
throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host));
throw new SyntaxError('The host `'.$host.'` is invalid : the IP host is malformed.');
}
if (1 === preg_match(self::REGEXP_HOST_GEN_DELIMS, rawurldecode(substr($ip, $pos)))) {
throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host));
throw new SyntaxError('The host `'.$host.'` is invalid : the IP host is malformed.');
}
$ip = substr($ip, 0, $pos);
if (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host));
throw new SyntaxError('The host `'.$host.'` is invalid : the IP host is malformed.');
}
//Only the address block fe80::/10 can have a Zone ID attach to
//let's detect the link local significant 10 bits
if (0 === strpos((string) inet_pton($ip), self::HOST_ADDRESS_BLOCK)) {
if (str_starts_with((string)inet_pton($ip), self::HOST_ADDRESS_BLOCK)) {
return $host;
}
throw new SyntaxError(sprintf('The host `%s` is invalid : the IP host is malformed', $host));
throw new SyntaxError('The host `'.$host.'` is invalid : the IP host is malformed.');
}
/**
* Format the Port component.
*
* @param object|null|int|string $port
*
* @throws SyntaxError
*/
private function formatPort($port = null): ?int
private function formatPort(Stringable|string|int|null $port = null): ?int
{
if (null === $port || '' === $port) {
return null;
@ -381,7 +380,7 @@ final class Uri implements UriInterface
$port = (int) $port;
if (0 > $port) {
throw new SyntaxError(sprintf('The port `%s` is invalid', $port));
throw new SyntaxError('The port `'.$port.'` is invalid.');
}
$defaultPort = self::SCHEME_DEFAULT_PORT[$this->scheme] ?? null;
@ -392,9 +391,6 @@ final class Uri implements UriInterface
return $port;
}
/**
* {@inheritDoc}
*/
public static function __set_state(array $components): self
{
$components['user'] = null;
@ -416,22 +412,21 @@ final class Uri implements UriInterface
}
/**
* Create a new instance from a URI and a Base URI.
* Creates a new instance from a URI and a Base URI.
*
* The returned URI must be absolute.
*
* @param mixed $uri the input URI to create
* @param null|mixed $base_uri the base URI used for reference
*/
public static function createFromBaseUri($uri, $base_uri = null): UriInterface
{
public static function createFromBaseUri(
Stringable|UriInterface|String $uri,
Stringable|UriInterface|String $base_uri = null
): UriInterface {
if (!$uri instanceof UriInterface) {
$uri = self::createFromString($uri);
}
if (null === $base_uri) {
if (null === $uri->getScheme()) {
throw new SyntaxError(sprintf('the URI `%s` must be absolute', (string) $uri));
throw new SyntaxError('the URI `'.$uri.'` must be absolute.');
}
if (null === $uri->getAuthority()) {
@ -449,7 +444,7 @@ final class Uri implements UriInterface
}
if (null === $base_uri->getScheme()) {
throw new SyntaxError(sprintf('the base URI `%s` must be absolute', (string) $base_uri));
throw new SyntaxError('the base URI `'.$base_uri.'` must be absolute.');
}
/** @var UriInterface $uri */
@ -460,10 +455,8 @@ final class Uri implements UriInterface
/**
* Create a new instance from a string.
*
* @param string|mixed $uri
*/
public static function createFromString($uri = ''): self
public static function createFromString(Stringable|string $uri = ''): self
{
$components = UriString::parse($uri);
@ -517,7 +510,7 @@ final class Uri implements UriInterface
// @codeCoverageIgnoreStart
if (!$finfo_support) {
throw new FileinfoSupportMissing(sprintf('Please install ext/fileinfo to use the %s() method.', __METHOD__));
throw new FileinfoSupportMissing('Please install ext/fileinfo to use the '.__METHOD__.'() method.');
}
// @codeCoverageIgnoreEnd
@ -528,9 +521,12 @@ final class Uri implements UriInterface
$mime_args[] = $context;
}
$raw = @file_get_contents(...$file_args);
set_error_handler(fn (int $errno, string $errstr, string $errfile, int $errline) => true);
$raw = file_get_contents(...$file_args);
restore_error_handler();
if (false === $raw) {
throw new SyntaxError(sprintf('The file `%s` does not exist or is not readable', $path));
throw new SyntaxError('The file `'.$path.'` does not exist or is not readable.');
}
$mimetype = (string) (new finfo(FILEINFO_MIME))->file(...$mime_args);
@ -546,7 +542,7 @@ final class Uri implements UriInterface
*/
public static function createFromUnixPath(string $uri = ''): self
{
$uri = implode('/', array_map('rawurlencode', explode('/', $uri)));
$uri = implode('/', array_map(rawurlencode(...), explode('/', $uri)));
if ('/' !== ($uri[0] ?? '')) {
return Uri::createFromComponents(['path' => $uri]);
}
@ -565,7 +561,7 @@ final class Uri implements UriInterface
$uri = substr($uri, strlen($root));
}
$uri = str_replace('\\', '/', $uri);
$uri = implode('/', array_map('rawurlencode', explode('/', $uri)));
$uri = implode('/', array_map(rawurlencode(...), explode('/', $uri)));
//Local Windows absolute path
if ('' !== $root) {
@ -573,7 +569,7 @@ final class Uri implements UriInterface
}
//UNC Windows Path
if ('//' !== substr($uri, 0, 2)) {
if (!str_starts_with($uri, '//')) {
return Uri::createFromComponents(['path' => $uri]);
}
@ -584,10 +580,8 @@ final class Uri implements UriInterface
/**
* Create a new instance from a URI object.
*
* @param Psr7UriInterface|UriInterface $uri the input URI to create
*/
public static function createFromUri($uri): self
public static function createFromUri(Psr7UriInterface|UriInterface $uri): self
{
if ($uri instanceof UriInterface) {
$user_info = $uri->getUserInfo();
@ -609,10 +603,6 @@ final class Uri implements UriInterface
);
}
if (!$uri instanceof Psr7UriInterface) {
throw new TypeError(sprintf('The object must implement the `%s` or the `%s`', Psr7UriInterface::class, UriInterface::class));
}
$scheme = $uri->getScheme();
if ('' === $scheme) {
$scheme = null;
@ -657,19 +647,12 @@ final class Uri implements UriInterface
*/
public static function createFromServer(array $server): self
{
[$user, $pass] = self::fetchUserInfo($server);
[$host, $port] = self::fetchHostname($server);
[$path, $query] = self::fetchRequestUri($server);
$components = ['scheme' => self::fetchScheme($server)];
[$components['user'], $components['pass']] = self::fetchUserInfo($server);
[$components['host'], $components['port']] = self::fetchHostname($server);
[$components['path'], $components['query']] = self::fetchRequestUri($server);
return Uri::createFromComponents([
'scheme' => self::fetchScheme($server),
'user' => $user,
'pass' => $pass,
'host' => $host,
'port' => $port,
'path' => $path,
'query' => $query,
]);
return Uri::createFromComponents($components);
}
/**
@ -686,14 +669,14 @@ final class Uri implements UriInterface
/**
* Returns the environment user info.
*
* @return array{0:?string, 1:?string}
* @return non-empty-array{0:?string, 1:?string}
*/
private static function fetchUserInfo(array $server): array
{
$server += ['PHP_AUTH_USER' => null, 'PHP_AUTH_PW' => null, 'HTTP_AUTHORIZATION' => ''];
$user = $server['PHP_AUTH_USER'];
$pass = $server['PHP_AUTH_PW'];
if (0 === strpos(strtolower($server['HTTP_AUTHORIZATION']), 'basic')) {
if (str_starts_with(strtolower($server['HTTP_AUTHORIZATION']), 'basic')) {
$userinfo = base64_decode(substr($server['HTTP_AUTHORIZATION'], 6), true);
if (false === $userinfo) {
throw new SyntaxError('The user info could not be detected');
@ -751,20 +734,17 @@ final class Uri implements UriInterface
/**
* Returns the environment path.
*
* @return array{0:?string, 1:?string}
* @return non-empty-array{0:?string, 1:?string}
*/
private static function fetchRequestUri(array $server): array
{
$server += ['IIS_WasUrlRewritten' => null, 'UNENCODED_URL' => '', 'PHP_SELF' => '', 'QUERY_STRING' => null];
if ('1' === $server['IIS_WasUrlRewritten'] && '' !== $server['UNENCODED_URL']) {
/** @var array{0:?string, 1:?string} $retval */
$retval = explode('?', $server['UNENCODED_URL'], 2) + [1 => null];
return $retval;
return explode('?', $server['UNENCODED_URL'], 2) + [1 => null];
}
if (isset($server['REQUEST_URI'])) {
[$path, ] = explode('?', $server['REQUEST_URI'], 2);
[$path] = explode('?', $server['REQUEST_URI'], 2);
$query = ('' !== $server['QUERY_STRING']) ? $server['QUERY_STRING'] : null;
return [$path, $query];
@ -799,13 +779,21 @@ final class Uri implements UriInterface
*/
private function formatPath(string $path): string
{
$path = $this->formatDataPath($path);
if ('data' === $this->scheme) {
$path = $this->formatDataPath($path);
}
static $pattern = '/(?:[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.'%:@\/}{]++|%(?![A-Fa-f0-9]{2}))/';
if ('/' !== $path) {
static $pattern = '/[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.':@\/}{]++|%(?![A-Fa-f\d]{2})/';
$path = (string) preg_replace_callback($pattern, [Uri::class, 'urlEncodeMatch'], $path);
$path = (string) preg_replace_callback($pattern, Uri::urlEncodeMatch(...), $path);
}
return $this->formatFilePath($path);
if ('file' === $this->scheme) {
$path = $this->formatFilePath($path);
}
return $path;
}
/**
@ -817,16 +805,12 @@ final class Uri implements UriInterface
*/
private function formatDataPath(string $path): string
{
if ('data' !== $this->scheme) {
return $path;
}
if ('' == $path) {
return 'text/plain;charset=us-ascii,';
}
if (strlen($path) !== strspn($path, self::ASCII) || false === strpos($path, ',')) {
throw new SyntaxError(sprintf('The path `%s` is invalid according to RFC2937', $path));
if (strlen($path) !== strspn($path, self::ASCII) || !str_contains($path, ',')) {
throw new SyntaxError('The path `'.$path.'` is invalid according to RFC2937.');
}
$parts = explode(',', $path, 2) + [1 => null];
@ -857,7 +841,7 @@ final class Uri implements UriInterface
private function assertValidPath(string $mimetype, string $parameters, string $data): void
{
if (1 !== preg_match(self::REGEXP_MIMETYPE, $mimetype)) {
throw new SyntaxError(sprintf('The path mimetype `%s` is invalid', $mimetype));
throw new SyntaxError('The path mimetype `'.$mimetype.'` is invalid.');
}
$is_binary = 1 === preg_match(self::REGEXP_BINARY, $parameters, $matches);
@ -865,9 +849,9 @@ final class Uri implements UriInterface
$parameters = substr($parameters, 0, - strlen($matches[0]));
}
$res = array_filter(array_filter(explode(';', $parameters), [$this, 'validateParameter']));
$res = array_filter(array_filter(explode(';', $parameters), $this->validateParameter(...)));
if ([] !== $res) {
throw new SyntaxError(sprintf('The path paremeters `%s` is invalid', $parameters));
throw new SyntaxError('The path paremeters `'.$parameters.'` is invalid.');
}
if (!$is_binary) {
@ -876,7 +860,7 @@ final class Uri implements UriInterface
$res = base64_decode($data, true);
if (false === $res || $data !== base64_encode($res)) {
throw new SyntaxError(sprintf('The path data `%s` is invalid', $data));
throw new SyntaxError('The path data `'.$data.'` is invalid.');
}
}
@ -895,10 +879,6 @@ final class Uri implements UriInterface
*/
private function formatFilePath(string $path): string
{
if ('file' !== $this->scheme) {
return $path;
}
$replace = static function (array $matches): string {
return $matches['delim'].$matches['volume'].':'.$matches['rest'];
};
@ -915,8 +895,6 @@ final class Uri implements UriInterface
* <li> a boolean flag telling wether the delimiter is to be added to the component
* when building the URI string representation</li>
* </ul>
*
* @param ?string $component
*/
private function formatQueryAndFragment(?string $component): ?string
{
@ -924,8 +902,8 @@ final class Uri implements UriInterface
return $component;
}
static $pattern = '/(?:[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/';
return preg_replace_callback($pattern, [Uri::class, 'urlEncodeMatch'], $component);
static $pattern = '/[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.':@\/?]++|%(?![A-Fa-f\d]{2})/';
return preg_replace_callback($pattern, Uri::urlEncodeMatch(...), $component);
}
/**
@ -943,27 +921,31 @@ final class Uri implements UriInterface
throw new SyntaxError('If an authority is present the path must be empty or start with a `/`.');
}
if (null === $this->authority && 0 === strpos($this->path, '//')) {
throw new SyntaxError(sprintf('If there is no authority the path `%s` can not start with a `//`.', $this->path));
if (null === $this->authority && str_starts_with($this->path, '//')) {
throw new SyntaxError('If there is no authority the path `'.$this->path.'` can not start with a `//`.');
}
$pos = strpos($this->path, ':');
if (null === $this->authority
&& null === $this->scheme
&& false !== $pos
&& false === strpos(substr($this->path, 0, $pos), '/')
&& !str_contains(substr($this->path, 0, $pos), '/')
) {
throw new SyntaxError('In absence of a scheme and an authority the first path segment cannot contain a colon (":") character.');
}
$validationMethod = self::SCHEME_VALIDATION_METHOD[$this->scheme] ?? null;
if (null === $validationMethod || true === $this->$validationMethod()) {
$this->uri = null;
$this->uri = null;
return;
if (! match ($this->scheme) {
'data' => $this->isUriWithSchemeAndPathOnly(),
'file' => $this->isUriWithSchemeHostAndPathOnly(),
'ftp', 'gopher' => $this->isNonEmptyHostUriWithoutFragmentAndQuery(),
'http', 'https' => $this->isNonEmptyHostUri(),
'ws', 'wss' => $this->isNonEmptyHostUriWithoutFragment(),
default => true,
}) {
throw new SyntaxError('The uri `'.$this.'` is invalid for the `'.$this->scheme.'` scheme.');
}
throw new SyntaxError(sprintf('The uri `%s` is invalid for the `%s` scheme.', (string) $this, $this->scheme));
}
/**
@ -1019,11 +1001,6 @@ final class Uri implements UriInterface
* Generate the URI string representation from its components.
*
* @link https://tools.ietf.org/html/rfc3986#section-5.3
*
* @param ?string $scheme
* @param ?string $authority
* @param ?string $query
* @param ?string $fragment
*/
private function getUriString(
?string $scheme,
@ -1053,15 +1030,13 @@ final class Uri implements UriInterface
public function toString(): string
{
$this->uri = $this->uri ?? $this->getUriString(
return $this->uri ??= $this->getUriString(
$this->scheme,
$this->authority,
$this->path,
$this->query,
$this->fragment
);
return $this->uri;
}
/**
@ -1081,9 +1056,15 @@ final class Uri implements UriInterface
}
/**
* {@inheritDoc}
*
* @return array{scheme:?string, user_info:?string, host:?string, port:?int, path:string, query:?string, fragment:?string}
* @return array{
* scheme:?string,
* user_info:?string,
* host:?string,
* port:?int,
* path:string,
* query:?string,
* fragment:?string
* }
*/
public function __debugInfo(): array
{
@ -1143,7 +1124,7 @@ final class Uri implements UriInterface
*/
public function getPath(): string
{
if (0 === strpos($this->path, '//')) {
if (str_starts_with($this->path, '//')) {
return '/'.ltrim($this->path, '/');
}
@ -1192,18 +1173,14 @@ final class Uri implements UriInterface
*
* @throws SyntaxError if the submitted data can not be converted to string
*/
private function filterString($str): ?string
private function filterString(mixed $str): ?string
{
if (null === $str) {
return $str;
return null;
}
if (is_object($str) && method_exists($str, '__toString')) {
$str = (string) $str;
}
if (!is_scalar($str)) {
throw new SyntaxError(sprintf('The component must be a string, a scalar or a stringable object; `%s` given.', gettype($str)));
if (!is_scalar($str) && !$str instanceof Stringable) {
throw new SyntaxError('The component must be a string, a scalar or a Stringable object; `'.gettype($str).'` given.');
}
$str = (string) $str;
@ -1211,14 +1188,16 @@ final class Uri implements UriInterface
return $str;
}
throw new SyntaxError(sprintf('The component `%s` contains invalid characters.', $str));
throw new SyntaxError('The component `'.$str.'` contains invalid characters.');
}
/**
* {@inheritDoc}
*/
public function withUserInfo($user, $password = null): UriInterface
{
public function withUserInfo(
$user,
#[SensitiveParameter] $password = null
): UriInterface {
$user_info = null;
$user = $this->filterString($user);
if (null !== $password) {

View File

@ -15,18 +15,15 @@ namespace League\Uri;
use League\Uri\Contracts\UriInterface;
use Psr\Http\Message\UriInterface as Psr7UriInterface;
use TypeError;
use function explode;
use function implode;
use function preg_replace_callback;
use function rawurldecode;
use function sprintf;
final class UriInfo
{
private const REGEXP_ENCODED_CHARS = ',%(2[D|E]|3[0-9]|4[1-9|A-F]|5[0-9|AF]|6[1-9|A-F]|7[0-9|E]),i';
private const WHATWG_SPECIAL_SCHEMES = ['ftp' => 21, 'http' => 80, 'https' => 443, 'ws' => 80, 'wss' => 443];
private const REGEXP_ENCODED_CHARS = ',%(2[D|E]|3\d|4[1-9|A-F]|5[\d|A|F]|6[1-9|A-F]|7[\d|E]),i';
private const WHATWG_SPECIAL_SCHEMES = ['ftp', 'http', 'https', 'ws', 'wss'];
/**
* @codeCoverageIgnore
@ -35,46 +32,17 @@ final class UriInfo
{
}
/**
* @param Psr7UriInterface|UriInterface $uri
*/
private static function emptyComponentValue($uri): ?string
private static function emptyComponentValue(Psr7UriInterface|UriInterface $uri): ?string
{
return $uri instanceof Psr7UriInterface ? '' : null;
}
/**
* Filter the URI object.
*
* To be valid an URI MUST implement at least one of the following interface:
* - League\Uri\UriInterface
* - Psr\Http\Message\UriInterface
*
* @param mixed $uri the URI to validate
*
* @throws TypeError if the URI object does not implements the supported interfaces.
*
* @return Psr7UriInterface|UriInterface
* Normalizes an URI for comparison.
*/
private static function filterUri($uri)
private static function normalize(Psr7UriInterface|UriInterface $uri): Psr7UriInterface|UriInterface
{
if ($uri instanceof Psr7UriInterface || $uri instanceof UriInterface) {
return $uri;
}
throw new TypeError(sprintf('The uri must be a valid URI object received `%s`', is_object($uri) ? get_class($uri) : gettype($uri)));
}
/**
* Normalize an URI for comparison.
*
* @param Psr7UriInterface|UriInterface $uri
*
* @return Psr7UriInterface|UriInterface
*/
private static function normalize($uri)
{
$uri = self::filterUri($uri);
$null = self::emptyComponentValue($uri);
$path = $uri->getPath();
@ -107,36 +75,28 @@ final class UriInfo
}
/**
* Tell whether the URI represents an absolute URI.
*
* @param Psr7UriInterface|UriInterface $uri
* Tells whether the URI represents an absolute URI.
*/
public static function isAbsolute($uri): bool
public static function isAbsolute(Psr7UriInterface|UriInterface $uri): bool
{
return self::emptyComponentValue($uri) !== self::filterUri($uri)->getScheme();
return self::emptyComponentValue($uri) !== $uri->getScheme();
}
/**
* Tell whether the URI represents a network path.
*
* @param Psr7UriInterface|UriInterface $uri
*/
public static function isNetworkPath($uri): bool
public static function isNetworkPath(Psr7UriInterface|UriInterface $uri): bool
{
$uri = self::filterUri($uri);
$null = self::emptyComponentValue($uri);
return $null === $uri->getScheme() && $null !== $uri->getAuthority();
}
/**
* Tell whether the URI represents an absolute path.
*
* @param Psr7UriInterface|UriInterface $uri
* Tells whether the URI represents an absolute path.
*/
public static function isAbsolutePath($uri): bool
public static function isAbsolutePath(Psr7UriInterface|UriInterface $uri): bool
{
$uri = self::filterUri($uri);
$null = self::emptyComponentValue($uri);
return $null === $uri->getScheme()
@ -147,11 +107,9 @@ final class UriInfo
/**
* Tell whether the URI represents a relative path.
*
* @param Psr7UriInterface|UriInterface $uri
*/
public static function isRelativePath($uri): bool
public static function isRelativePath(Psr7UriInterface|UriInterface $uri): bool
{
$uri = self::filterUri($uri);
$null = self::emptyComponentValue($uri);
return $null === $uri->getScheme()
@ -160,12 +118,9 @@ final class UriInfo
}
/**
* Tell whether both URI refers to the same document.
*
* @param Psr7UriInterface|UriInterface $uri
* @param Psr7UriInterface|UriInterface $base_uri
* Tells whether both URI refers to the same document.
*/
public static function isSameDocument($uri, $base_uri): bool
public static function isSameDocument(Psr7UriInterface|UriInterface $uri, Psr7UriInterface|UriInterface $base_uri): bool
{
$uri = self::normalize($uri);
$base_uri = self::normalize($base_uri);
@ -182,31 +137,30 @@ final class UriInfo
* For URI without a special scheme the method returns null
* For URI with the file scheme the method will return null (as this is left to the implementation decision)
* For URI with a special scheme the method returns the scheme followed by its authority (without the userinfo part)
*
* @param Psr7UriInterface|UriInterface $uri
*/
public static function getOrigin($uri): ?string
public static function getOrigin(Psr7UriInterface|UriInterface $uri): ?string
{
$scheme = self::filterUri($uri)->getScheme();
$scheme = $uri->getScheme();
if ('blob' === $scheme) {
$uri = Uri::createFromString($uri->getPath());
$scheme = $uri->getScheme();
}
if (null === $scheme || !array_key_exists($scheme, self::WHATWG_SPECIAL_SCHEMES)) {
return null;
if (in_array($scheme, self::WHATWG_SPECIAL_SCHEMES, true)) {
$null = self::emptyComponentValue($uri);
return (string) $uri->withFragment($null)->withQuery($null)->withPath('')->withUserInfo($null, null);
}
$null = self::emptyComponentValue($uri);
return (string) $uri->withFragment($null)->withQuery($null)->withPath('')->withUserInfo($null);
return null;
}
/**
* @param Psr7UriInterface|UriInterface $uri
* @param Psr7UriInterface|UriInterface $base_uri
* Tells whether two URI do not share the same origin.
*
* @see UriInfo::getOrigin()
*/
public static function isCrossOrigin($uri, $base_uri): bool
public static function isCrossOrigin(Psr7UriInterface|UriInterface $uri, Psr7UriInterface|UriInterface $base_uri): bool
{
return null === ($uriString = self::getOrigin(Uri::createFromUri($uri)))
|| null === ($baseUriString = self::getOrigin(Uri::createFromUri($base_uri)))

View File

@ -15,16 +15,13 @@ namespace League\Uri;
use League\Uri\Contracts\UriInterface;
use Psr\Http\Message\UriInterface as Psr7UriInterface;
use TypeError;
use function array_pop;
use function array_reduce;
use function count;
use function end;
use function explode;
use function gettype;
use function implode;
use function in_array;
use function sprintf;
use function str_repeat;
use function strpos;
use function substr;
@ -44,20 +41,13 @@ final class UriResolver
}
/**
* Resolve an URI against a base URI using RFC3986 rules.
* Resolves an URI against a base URI using RFC3986 rules.
*
* If the first argument is a UriInterface the method returns a UriInterface object
* If the first argument is a Psr7UriInterface the method returns a Psr7UriInterface object
*
* @param Psr7UriInterface|UriInterface $uri
* @param Psr7UriInterface|UriInterface $base_uri
*
* @return Psr7UriInterface|UriInterface
*/
public static function resolve($uri, $base_uri)
public static function resolve(Psr7UriInterface|UriInterface $uri, Psr7UriInterface|UriInterface $base_uri): Psr7UriInterface|UriInterface
{
self::filterUri($uri);
self::filterUri($base_uri);
$null = $uri instanceof Psr7UriInterface ? '' : null;
if ($null !== $uri->getScheme()) {
@ -90,38 +80,24 @@ final class UriResolver
;
}
/**
* Filter the URI object.
*
* @param mixed $uri an URI object
*
* @throws TypeError if the URI object does not implements the supported interfaces.
*/
private static function filterUri($uri): void
{
if (!$uri instanceof UriInterface && !$uri instanceof Psr7UriInterface) {
throw new TypeError(sprintf('The uri must be a valid URI object received `%s`', gettype($uri)));
}
}
/**
* Remove dot segments from the URI path.
*/
private static function removeDotSegments(string $path): string
{
if (false === strpos($path, '.')) {
if (!str_contains($path, '.')) {
return $path;
}
$old_segments = explode('/', $path);
$new_path = implode('/', array_reduce($old_segments, [UriResolver::class, 'reducer'], []));
$new_path = implode('/', array_reduce($old_segments, UriResolver::reducer(...), []));
if (isset(self::DOT_SEGMENTS[end($old_segments)])) {
$new_path .= '/';
}
// @codeCoverageIgnoreStart
// added because some PSR-7 implementations do not respect RFC3986
if (0 === strpos($path, '/') && 0 !== strpos($new_path, '/')) {
if (str_starts_with($path, '/') && !str_starts_with($new_path, '/')) {
return '/'.$new_path;
}
// @codeCoverageIgnoreEnd
@ -150,21 +126,20 @@ final class UriResolver
}
/**
* Resolve an URI path and query component.
*
* @param Psr7UriInterface|UriInterface $uri
* @param Psr7UriInterface|UriInterface $base_uri
* Resolves an URI path and query component.
*
* @return array{0:string, 1:string|null}
*/
private static function resolvePathAndQuery($uri, $base_uri): array
{
private static function resolvePathAndQuery(
Psr7UriInterface|UriInterface $uri,
Psr7UriInterface|UriInterface $base_uri
): array {
$target_path = $uri->getPath();
$target_query = $uri->getQuery();
$null = $uri instanceof Psr7UriInterface ? '' : null;
$baseNull = $base_uri instanceof Psr7UriInterface ? '' : null;
if (0 === strpos($target_path, '/')) {
if (str_starts_with($target_path, '/')) {
return [$target_path, $target_query];
}
@ -176,7 +151,7 @@ final class UriResolver
$target_path = $base_uri->getPath();
//@codeCoverageIgnoreStart
//because some PSR-7 Uri implementations allow this RFC3986 forbidden construction
if ($baseNull !== $base_uri->getAuthority() && 0 !== strpos($target_path, '/')) {
if ($baseNull !== $base_uri->getAuthority() && !str_starts_with($target_path, '/')) {
$target_path = '/'.$target_path;
}
//@codeCoverageIgnoreEnd
@ -201,23 +176,18 @@ final class UriResolver
}
/**
* Relativize an URI according to a base URI.
* Relativizes an URI according to a base URI.
*
* This method MUST retain the state of the submitted URI instance, and return
* an URI instance of the same type that contains the applied modifications.
*
* This method MUST be transparent when dealing with error and exceptions.
* It MUST not alter of silence them apart from validating its own parameters.
*
* @param Psr7UriInterface|UriInterface $uri
* @param Psr7UriInterface|UriInterface $base_uri
*
* @return Psr7UriInterface|UriInterface
*/
public static function relativize($uri, $base_uri)
{
self::filterUri($uri);
self::filterUri($base_uri);
public static function relativize(
Psr7UriInterface|UriInterface $uri,
Psr7UriInterface|UriInterface $base_uri
): Psr7UriInterface|UriInterface {
$uri = self::formatHost($uri);
$base_uri = self::formatHost($base_uri);
if (!self::isRelativizable($uri, $base_uri)) {
@ -231,7 +201,7 @@ final class UriResolver
return $uri->withPath(self::relativizePath($target_path, $base_uri->getPath()));
}
if (self::componentEquals('getQuery', $uri, $base_uri)) {
if (self::componentEquals('query', $uri, $base_uri)) {
return $uri->withPath('')->withQuery($null);
}
@ -244,23 +214,26 @@ final class UriResolver
/**
* Tells whether the component value from both URI object equals.
*
* @param Psr7UriInterface|UriInterface $uri
* @param Psr7UriInterface|UriInterface $base_uri
*/
private static function componentEquals(string $method, $uri, $base_uri): bool
{
return self::getComponent($method, $uri) === self::getComponent($method, $base_uri);
private static function componentEquals(
string $property,
Psr7UriInterface|UriInterface $uri,
Psr7UriInterface|UriInterface $base_uri
): bool {
return self::getComponent($property, $uri) === self::getComponent($property, $base_uri);
}
/**
* Returns the component value from the submitted URI object.
*
* @param Psr7UriInterface|UriInterface $uri
*/
private static function getComponent(string $method, $uri): ?string
private static function getComponent(string $property, Psr7UriInterface|UriInterface $uri): ?string
{
$component = $uri->$method();
$component = match ($property) {
'query' => $uri->getQuery(),
'authority' => $uri->getAuthority(),
default => $uri->getScheme(), //scheme
};
if ($uri instanceof Psr7UriInterface && '' === $component) {
return null;
}
@ -270,14 +243,8 @@ final class UriResolver
/**
* Filter the URI object.
*
* @param Psr7UriInterface|UriInterface $uri
*
* @throws TypeError if the URI object does not implements the supported interfaces.
*
* @return Psr7UriInterface|UriInterface
*/
private static function formatHost($uri)
private static function formatHost(Psr7UriInterface|UriInterface $uri): Psr7UriInterface|UriInterface
{
if (!$uri instanceof Psr7UriInterface) {
return $uri;
@ -292,20 +259,19 @@ final class UriResolver
}
/**
* Tell whether the submitted URI object can be relativize.
*
* @param Psr7UriInterface|UriInterface $uri
* @param Psr7UriInterface|UriInterface $base_uri
* Tells whether the submitted URI object can be relativize.
*/
private static function isRelativizable($uri, $base_uri): bool
{
private static function isRelativizable(
Psr7UriInterface|UriInterface $uri,
Psr7UriInterface|UriInterface $base_uri
): bool {
return !UriInfo::isRelativePath($uri)
&& self::componentEquals('getScheme', $uri, $base_uri)
&& self::componentEquals('getAuthority', $uri, $base_uri);
&& self::componentEquals('scheme', $uri, $base_uri)
&& self::componentEquals('authority', $uri, $base_uri);
}
/**
* Relative the URI for a authority-less target URI.
* Relatives the URI for an authority-less target URI.
*/
private static function relativizePath(string $path, string $basepath): string
{

View File

@ -17,15 +17,11 @@ use League\Uri\Exceptions\IdnaConversionFailed;
use League\Uri\Exceptions\IdnSupportMissing;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\Idna\Idna;
use TypeError;
use Stringable;
use function array_merge;
use function explode;
use function filter_var;
use function gettype;
use function inet_pton;
use function is_object;
use function is_scalar;
use function method_exists;
use function preg_match;
use function rawurldecode;
use function sprintf;
@ -87,7 +83,7 @@ final class UriString
*
* @link https://tools.ietf.org/html/rfc3986#section-3.1
*/
private const REGEXP_URI_SCHEME = '/^([a-z][a-z\d\+\.\-]*)?$/i';
private const REGEXP_URI_SCHEME = '/^([a-z][a-z\d+.-]*)?$/i';
/**
* IPvFuture regular expression.
@ -157,16 +153,7 @@ final class UriString
* @link https://tools.ietf.org/html/rfc3986#section-5.3
* @link https://tools.ietf.org/html/rfc3986#section-7.5
*
* @param array{
* scheme:?string,
* user:?string,
* pass:?string,
* host:?string,
* port:?int,
* path:?string,
* query:?string,
* fragment:?string
* } $components
* @param array{scheme:?string, user:?string, pass:?string, host:?string, port:?int, path:?string, query:?string, fragment:?string} $components
*/
public static function build(array $components): string
{
@ -242,35 +229,17 @@ final class UriString
*
* @link https://tools.ietf.org/html/rfc3986
*
* @param mixed $uri any scalar or stringable object
* @param Stringable|string|int|float $uri any scalar or stringable object
*
* @throws SyntaxError if the URI contains invalid characters
* @throws SyntaxError if the URI contains an invalid scheme
* @throws SyntaxError if the URI contains an invalid path
*
* @return array{
* scheme:?string,
* user:?string,
* pass:?string,
* host:?string,
* port:?int,
* path:string,
* query:?string,
* fragment:?string
* }
* @return array{scheme:?string, user:?string, pass:?string, host:?string, port:?int, path:string, query:?string, fragment:?string}
*/
public static function parse($uri): array
public static function parse(Stringable|string|int|float $uri): array
{
if (is_object($uri) && method_exists($uri, '__toString')) {
$uri = (string) $uri;
}
if (!is_scalar($uri)) {
throw new TypeError(sprintf('The uri must be a scalar or a stringable object `%s` given', gettype($uri)));
}
$uri = (string) $uri;
if (isset(self::URI_SCHORTCUTS[$uri])) {
/** @var array{scheme:?string, user:?string, pass:?string, host:?string, port:?int, path:string, query:?string, fragment:?string} $components */
$components = array_merge(self::URI_COMPONENTS, self::URI_SCHORTCUTS[$uri]);
@ -395,7 +364,7 @@ final class UriString
return $host;
}
if ('[' !== $host[0] || ']' !== substr($host, -1)) {
if ('[' !== $host[0] || !str_ends_with($host, ']')) {
return self::filterRegisteredName($host);
}
@ -462,6 +431,6 @@ final class UriString
$ip_host = substr($ip_host, 0, $pos);
return false !== filter_var($ip_host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)
&& 0 === strpos((string) inet_pton($ip_host), self::ZONE_ID_ADDRESS_BLOCK);
&& str_starts_with((string)inet_pton($ip_host), self::ZONE_ID_ADDRESS_BLOCK);
}
}

View File

@ -19,7 +19,7 @@ use League\Uri\Exceptions\SyntaxError;
use League\Uri\Exceptions\TemplateCanNotBeExpanded;
use League\Uri\UriTemplate\Template;
use League\Uri\UriTemplate\VariableBag;
use TypeError;
use Stringable;
/**
* Defines the URI Template syntax and the process for expanding a URI Template into a URI reference.
@ -34,25 +34,22 @@ use TypeError;
*/
final class UriTemplate
{
private Template $template;
private VariableBag $defaultVariables;
public readonly Template $template;
public readonly VariableBag $defaultVariables;
/**
* @param object|string $template a string or an object with the __toString method
*
* @throws TypeError if the template is not a string or an object with the __toString method
* @throws SyntaxError if the template syntax is invalid
* @throws TemplateCanNotBeExpanded if the template variables are invalid
*/
public function __construct($template, array $defaultVariables = [])
public function __construct(Template|Stringable|string $template, VariableBag|array $defaultVariables = [])
{
$this->template = Template::createFromString($template);
$this->template = $template instanceof Template ? $template : Template::createFromString($template);
$this->defaultVariables = $this->filterVariables($defaultVariables);
}
public static function __set_state(array $properties): self
{
return new self($properties['template']->toString(), $properties['defaultVariables']->all());
return new self($properties['template'], $properties['defaultVariables']);
}
/**
@ -60,16 +57,19 @@ final class UriTemplate
*
* @param array<string,string|array<string>> $variables
*/
private function filterVariables(array $variables): VariableBag
private function filterVariables(VariableBag|array $variables): VariableBag
{
$output = new VariableBag();
foreach ($this->template->variableNames() as $name) {
if (isset($variables[$name])) {
$output->assign($name, $variables[$name]);
}
}
return array_reduce(
$this->template->variableNames,
function (VariableBag $curry, string $name) use ($variables): VariableBag {
if (isset($variables[$name])) {
$curry[$name] = $variables[$name];
}
return $output;
return $curry;
},
new VariableBag()
);
}
/**
@ -77,7 +77,7 @@ final class UriTemplate
*/
public function getTemplate(): string
{
return $this->template->toString();
return $this->template->value;
}
/**
@ -87,7 +87,7 @@ final class UriTemplate
*/
public function getVariableNames(): array
{
return $this->template->variableNames();
return $this->template->variableNames;
}
/**
@ -111,19 +111,16 @@ final class UriTemplate
* If present, variables whose name is not part of the current template
* possible variable names are removed.
*/
public function withDefaultVariables(array $defaultDefaultVariables): self
public function withDefaultVariables(VariableBag|array $defaultDefaultVariables): self
{
return new self(
$this->template->toString(),
$this->filterVariables($defaultDefaultVariables)->all()
);
return new self($this->template, $defaultDefaultVariables);
}
/**
* @throws TemplateCanNotBeExpanded if the variable contains nested array values
* @throws UriException if the resulting expansion can not be converted to a UriInterface instance
*/
public function expand(array $variables = []): UriInterface
public function expand(VariableBag|array $variables = []): UriInterface
{
return Uri::createFromString(
$this->template->expand(

View File

@ -16,7 +16,6 @@ namespace League\Uri\UriTemplate;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\Exceptions\TemplateCanNotBeExpanded;
use function array_filter;
use function array_keys;
use function array_map;
use function array_unique;
use function explode;
@ -24,7 +23,6 @@ use function implode;
use function preg_match;
use function rawurlencode;
use function str_replace;
use function strpos;
use function substr;
final class Expression
@ -64,46 +62,29 @@ final class Expression
'&' => ['prefix' => '&', 'joiner' => '&', 'query' => true],
];
private string $operator;
/** @var array<VarSpecifier> */
private array $varSpecifiers;
private string $joiner;
/** @var array<string> */
private array $variableNames;
private string $expressionString;
public readonly array $variableNames;
public readonly string $value;
private function __construct(string $operator, VarSpecifier ...$varSpecifiers)
private function __construct(private string $operator, VarSpecifier ...$varSpecifiers)
{
$this->operator = $operator;
$this->varSpecifiers = $varSpecifiers;
$this->joiner = self::OPERATOR_HASH_LOOKUP[$operator]['joiner'];
$this->variableNames = $this->setVariableNames();
$this->expressionString = $this->setExpressionString();
$this->variableNames = array_unique(array_map(
static fn (VarSpecifier $varSpecifier): string => $varSpecifier->name,
$varSpecifiers
));
$this->value = '{'.$operator.implode(',', array_map(
static fn (VarSpecifier $varSpecifier): string => $varSpecifier->toString(),
$varSpecifiers
)).'}';
}
/**
* @return array<string>
*/
private function setVariableNames(): array
{
return array_unique(array_map(
static fn (VarSpecifier $varSpecifier): string => $varSpecifier->name(),
$this->varSpecifiers
));
}
private function setExpressionString(): string
{
$varSpecifierString = implode(',', array_map(
static fn (VarSpecifier $variable): string => $variable->toString(),
$this->varSpecifiers
));
return '{'.$this->operator.$varSpecifierString.'}';
}
/**
* {@inheritDoc}
* @param array{operator:string, varSpecifiers:array<VarSpecifier>} $properties
*/
public static function __set_state(array $properties): self
{
@ -123,7 +104,7 @@ final class Expression
/** @var array{operator:string, variables:string} $parts */
$parts = $parts + ['operator' => ''];
if ('' !== $parts['operator'] && false !== strpos(self::RESERVED_OPERATOR, $parts['operator'])) {
if ('' !== $parts['operator'] && str_contains(self::RESERVED_OPERATOR, $parts['operator'])) {
throw new SyntaxError('The operator used in the expression "'.$expression.'" is reserved.');
}
@ -136,13 +117,18 @@ final class Expression
/**
* Returns the expression string representation.
*
* @deprecated since version 6.6.0 use the readonly property instead
* @codeCoverageIgnore
*/
public function toString(): string
{
return $this->expressionString;
return $this->value;
}
/**
* @deprecated since version 6.6.0 use the readonly property instead
* @codeCoverageIgnore
*
* @return array<string>
*/
public function variableNames(): array
@ -178,7 +164,7 @@ final class Expression
*/
private function replace(VarSpecifier $varSpec, VariableBag $variables): string
{
$value = $variables->fetch($varSpec->name());
$value = $variables->fetch($varSpec->name);
if (null === $value) {
return '';
}
@ -190,10 +176,10 @@ final class Expression
}
if ('&' !== $this->joiner && '' === $expanded) {
return $varSpec->name();
return $varSpec->name;
}
return $varSpec->name().'='.$expanded;
return $varSpec->name.'='.$expanded;
}
/**
@ -201,7 +187,7 @@ final class Expression
*
* @return array{0:string, 1:bool}
*/
private function inject($value, VarSpecifier $varSpec, bool $useQuery): array
private function inject(array|string $value, VarSpecifier $varSpec, bool $useQuery): array
{
if (is_string($value)) {
return $this->replaceString($value, $varSpec, $useQuery);
@ -217,16 +203,15 @@ final class Expression
*/
private function replaceString(string $value, VarSpecifier $varSpec, bool $useQuery): array
{
if (':' === $varSpec->modifier()) {
$value = substr($value, 0, $varSpec->position());
if (':' === $varSpec->modifier) {
$value = substr($value, 0, $varSpec->position);
}
$expanded = rawurlencode($value);
if ('+' === $this->operator || '#' === $this->operator) {
return [$this->decodeReserved($expanded), $useQuery];
if (in_array($this->operator, ['+', '#'], true)) {
return [$this->decodeReserved(rawurlencode($value)), $useQuery];
}
return [$expanded, $useQuery];
return [rawurlencode($value), $useQuery];
}
/**
@ -244,48 +229,45 @@ final class Expression
return ['', false];
}
if (':' === $varSpec->modifier()) {
throw TemplateCanNotBeExpanded::dueToUnableToProcessValueListWithPrefix($varSpec->name());
if (':' === $varSpec->modifier) {
throw TemplateCanNotBeExpanded::dueToUnableToProcessValueListWithPrefix($varSpec->name);
}
$pairs = [];
$isAssoc = $this->isAssoc($value);
$isList = array_is_list($value);
foreach ($value as $key => $var) {
if ($isAssoc) {
if (!$isList) {
$key = rawurlencode((string) $key);
}
$var = rawurlencode($var);
if ('+' === $this->operator || '#' === $this->operator) {
if (in_array($this->operator, ['+', '#'], true)) {
$var = $this->decodeReserved($var);
}
if ('*' === $varSpec->modifier()) {
if ($isAssoc) {
if ('*' === $varSpec->modifier) {
if (!$isList) {
$var = $key.'='.$var;
} elseif ($key > 0 && $useQuery) {
$var = $varSpec->name().'='.$var;
$var = $varSpec->name.'='.$var;
}
}
$pairs[$key] = $var;
}
if ('*' === $varSpec->modifier()) {
if ($isAssoc) {
// Don't prepend the value name when using the explode
// modifier with an associative array.
if ('*' === $varSpec->modifier) {
if (!$isList) {
// Don't prepend the value name when using the `explode` modifier with an associative array.
$useQuery = false;
}
return [implode($this->joiner, $pairs), $useQuery];
}
if ($isAssoc) {
// When an associative array is encountered and the
// explode modifier is not set, then the result must be
// a comma separated list of keys followed by their
// respective values.
if (!$isList) {
// When an associative array is encountered and the `explode` modifier is not set, then
// the result must be a comma separated list of keys followed by their respective values.
foreach ($pairs as $offset => &$data) {
$data = $offset.','.$data;
}
@ -296,19 +278,6 @@ final class Expression
return [implode(',', $pairs), $useQuery];
}
/**
* Determines if an array is associative.
*
* This makes the assumption that input arrays are sequences or hashes.
* This assumption is a trade-off for accuracy in favor of speed, but it
* should work in almost every case where input is supplied for a URI
* template.
*/
private function isAssoc(array $array): bool
{
return [] !== $array && 0 !== array_keys($array)[0];
}
/**
* Removes percent encoding on reserved characters (used with + and # modifiers).
*/

View File

@ -15,17 +15,11 @@ namespace League\Uri\UriTemplate;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\Exceptions\TemplateCanNotBeExpanded;
use TypeError;
use function array_merge;
use Stringable;
use function array_unique;
use function gettype;
use function is_object;
use function is_string;
use function method_exists;
use function preg_match_all;
use function preg_replace;
use function sprintf;
use function strpos;
use function str_contains;
use const PREG_SET_ORDER;
final class Template
@ -33,53 +27,42 @@ final class Template
/**
* Expression regular expression pattern.
*/
private const REGEXP_EXPRESSION_DETECTOR = '/\{[^\}]*\}/x';
private const REGEXP_EXPRESSION_DETECTOR = '/\{[^}]*}/x';
private string $template;
/** @var array<string, Expression> */
private array $expressions = [];
/** @var array<string> */
private array $variableNames;
public readonly array $variableNames;
private function __construct(string $template, Expression ...$expressions)
private function __construct(public readonly string $value, Expression ...$expressions)
{
$this->template = $template;
$variableNames = [];
foreach ($expressions as $expression) {
$this->expressions[$expression->toString()] = $expression;
$variableNames[] = $expression->variableNames();
$this->expressions[$expression->value] = $expression;
$variableNames = [...$variableNames, ...$expression->variableNames];
}
$this->variableNames = array_unique(array_merge([], ...$variableNames));
$this->variableNames = array_unique($variableNames);
}
/**
* {@inheritDoc}
* @param array{value:string, template?:string, expressions:array<string, Expression>} $properties
*/
public static function __set_state(array $properties): self
{
return new self($properties['template'], ...array_values($properties['expressions']));
return new self($properties['template'] ?? $properties['value'], ...array_values($properties['expressions']));
}
/**
* @param object|string $template a string or an object with the __toString method
*
* @throws TypeError if the template is not a string or an object with the __toString method
* @throws SyntaxError if the template contains invalid expressions
* @throws SyntaxError if the template contains invalid variable specification
*/
public static function createFromString($template): self
public static function createFromString(Stringable|string $template): self
{
if (is_object($template) && method_exists($template, '__toString')) {
$template = (string) $template;
}
if (!is_string($template)) {
throw new TypeError(sprintf('The template must be a string or a stringable object %s given.', gettype($template)));
}
$template = (string) $template;
/** @var string $remainder */
$remainder = preg_replace(self::REGEXP_EXPRESSION_DETECTOR, '', $template);
if (false !== strpos($remainder, '{') || false !== strpos($remainder, '}')) {
if (str_contains($remainder, '{') || str_contains($remainder, '}')) {
throw new SyntaxError('The template "'.$template.'" contains invalid expressions.');
}
@ -96,12 +79,19 @@ final class Template
return new self($template, ...$arguments);
}
/**
* @deprecated since version 6.6.0 use the readonly property instead
* @codeCoverageIgnore
*/
public function toString(): string
{
return $this->template;
return $this->value;
}
/**
* @deprecated since version 6.6.0 use the readonly property instead
* @codeCoverageIgnore
*
* @return array<string>
*/
public function variableNames(): array
@ -115,7 +105,7 @@ final class Template
*/
public function expand(VariableBag $variables): string
{
$uriString = $this->template;
$uriString = $this->value;
/** @var Expression $expression */
foreach ($this->expressions as $pattern => $expression) {
$uriString = str_replace($pattern, $expression->expand($variables), $uriString);

View File

@ -28,19 +28,15 @@ final class VarSpecifier
(?<modifier>\:(?<position>\d+)|\*)?
$/x';
private string $name;
private string $modifier;
private int $position;
private function __construct(string $name, string $modifier, int $position)
{
$this->name = $name;
$this->modifier = $modifier;
$this->position = $position;
private function __construct(
public readonly string $name,
public readonly string $modifier,
public readonly int $position
) {
}
/**
* {@inheritDoc}
* @param array{name: string, modifier:string, position:int} $properties
*/
public static function __set_state(array $properties): self
{
@ -79,16 +75,28 @@ final class VarSpecifier
return $this->name.$this->modifier;
}
/**
* @codeCoverageIgnore
* @deprecated since version 6.6.0 use the readonly property instead
*/
public function name(): string
{
return $this->name;
}
/**
* @codeCoverageIgnore
* @deprecated since version 6.6.0 use the readonly property instead
*/
public function modifier(): string
{
return $this->modifier;
}
/**
* @codeCoverageIgnore
* @deprecated since version 6.6.0 use the readonly property instead
*/
public function position(): int
{
return $this->position;

View File

@ -13,17 +13,18 @@ declare(strict_types=1);
namespace League\Uri\UriTemplate;
use ArrayAccess;
use Countable;
use League\Uri\Exceptions\TemplateCanNotBeExpanded;
use TypeError;
use function gettype;
use function is_array;
use Stringable;
use function is_bool;
use function is_object;
use function is_scalar;
use function method_exists;
use function sprintf;
final class VariableBag
/**
* @implements ArrayAccess<string, string|bool|int|float|array<string|bool|int|float>>
*/
final class VariableBag implements ArrayAccess, Countable
{
/**
* @var array<string,string|array<string>>
@ -40,11 +41,39 @@ final class VariableBag
}
}
public function count(): int
{
return count($this->variables);
}
/**
* @param array{variables: array<string,string|array<string>>} $properties
*/
public static function __set_state(array $properties): self
{
return new self($properties['variables']);
}
public function offsetExists(mixed $offset): bool
{
return array_key_exists($offset, $this->variables);
}
public function offsetUnset(mixed $offset): void
{
unset($this->variables[$offset]);
}
public function offsetSet(mixed $offset, mixed $value): void
{
$this->assign($offset, $value); /* @phpstan-ignore-line */
}
public function offsetGet(mixed $offset): mixed
{
return $this->fetch($offset);
}
/**
* @return array<string,string|array<string>>
*/
@ -53,55 +82,45 @@ final class VariableBag
return $this->variables;
}
/**
* Tells whether the bag is empty or not.
*/
public function isEmpty(): bool
{
return [] === $this->variables;
}
/**
* Fetches the variable value if none found returns null.
*
* @return null|string|array<string>
*/
public function fetch(string $name)
public function fetch(string $name): null|string|array
{
return $this->variables[$name] ?? null;
}
/**
* @param string|bool|int|float|array<string|bool|int|float> $value
* @param string|bool|int|float|null|array<string|bool|int|float> $value
*/
public function assign(string $name, $value): void
public function assign(string $name, string|bool|int|float|array|null $value): void
{
$this->variables[$name] = $this->normalizeValue($value, $name, true);
}
/**
* @param mixed $value the value to be expanded
* @param Stringable|string|float|int|bool|null $value the value to be expanded
*
* @throws TemplateCanNotBeExpanded if the value contains nested list
*
* @return string|array<string>
*/
private function normalizeValue($value, string $name, bool $isNestedListAllowed)
private function normalizeValue(Stringable|array|string|float|int|bool|null $value, string $name, bool $isNestedListAllowed): array|string
{
if (is_bool($value)) {
return true === $value ? '1' : '0';
}
if (null === $value || is_scalar($value) || (is_object($value) && method_exists($value, '__toString'))) {
return (string) $value;
}
if (!is_array($value)) {
throw new TypeError(sprintf('The variable '.$name.' must be NULL, a scalar or a stringable object `%s` given', gettype($value)));
}
if (!$isNestedListAllowed) {
throw TemplateCanNotBeExpanded::dueToNestedListOfValue($name);
}
foreach ($value as &$var) {
$var = self::normalizeValue($var, $name, false);
}
unset($var);
return $value;
return match (true) {
is_bool($value) => true === $value ? '1' : '0',
(null === $value || is_scalar($value) || is_object($value)) => (string) $value,
!$isNestedListAllowed => throw TemplateCanNotBeExpanded::dueToNestedListOfValue($name),
default => array_map(fn ($var): array|string => self::normalizeValue($var, $name, false), $value),
};
}
/**