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
|
<?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\Components;
use ArgumentCountError;
use Closure;
use Countable;
use Deprecated;
use Iterator;
use IteratorAggregate;
use League\Uri\Contracts\QueryInterface;
use League\Uri\Contracts\UriComponentInterface;
use League\Uri\Contracts\UriInterface;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\KeyValuePair\Converter;
use League\Uri\QueryString;
use League\Uri\Uri;
use Stringable;
use function array_is_list;
use function array_key_exists;
use function array_keys;
use function array_map;
use function count;
use function func_get_arg;
use function func_num_args;
use function get_object_vars;
use function is_array;
use function is_iterable;
use function is_object;
use function is_scalar;
use function iterator_to_array;
use function json_encode;
use function spl_object_hash;
use function str_starts_with;
use const JSON_PRESERVE_ZERO_FRACTION;
/**
* @see https://url.spec.whatwg.org/#interface-urlsearchparams
*
* @implements IteratorAggregate<array{0:string, 1:string}>
*/
final class URLSearchParams implements Countable, IteratorAggregate, UriComponentInterface
{
private QueryInterface $pairs;
/**
* New instance.
*
* A string, which will be parsed from application/x-www-form-urlencoded format. A leading '?' character is ignored.
* A literal sequence of name-value string pairs, or any object with an iterator that produces a sequence of string pairs.
* A record of string keys and string values. Note that nesting is not supported.
*/
public function __construct(object|array|string|null $init = '')
{
$pairs = self::filterPairs(match (true) {
$init instanceof self,
$init instanceof QueryInterface => $init,
$init instanceof UriComponentInterface => self::parsePairs($init->value()),
is_iterable($init) => self::formatIterable($init),
$init instanceof Stringable, !is_object($init) => self::parsePairs(self::formatQuery($init)),
default => self::yieldPairs($init),
});
$this->pairs = Query::fromPairs($pairs);
}
/**
* @return array<int, array{0:string, 1:string|null}>
*/
private static function parsePairs(string|null $query): array
{
return QueryString::parseFromValue($query, Converter::fromFormData());
}
/**
* @return iterable<array{0:string, 1:string}>
*/
private static function formatIterable(iterable $iterable): iterable
{
if (!is_array($iterable)) {
$iterable = iterator_to_array($iterable);
}
return match (true) {
array_is_list($iterable) => $iterable,
default => self::yieldPairs($iterable)
};
}
/**
* Generates an Iterator containing pairs as items from an object or array.
*
* If an iterable is given, foreach will loop over the iterable structure
* If an object is give, foreach will loop over the object public properties if they are defined
*
* @param object|iterable<array-key, Stringable|string|float|int|bool|null> $associative
*
* @return Iterator<int, array{0:string, 1:string}>
*/
private static function yieldPairs(object|array $associative): Iterator
{
foreach ($associative as $key => $value) { /* @phpstan-ignore-line */
yield [self::uvString($key), self::uvString($value)];
}
}
/**
* @return Iterator<int, array{0:string, 1:string}>
*/
private static function filterPairs(iterable $pairs): iterable
{
$filter = static fn ($pair): ?array => match (true) {
!is_array($pair),
[0, 1] !== array_keys($pair) => throw new SyntaxError('A pair must be a sequential array starting at `0` and containing two elements.'),
null !== $pair[1] => [self::uvString($pair[0]), self::uvString($pair[1])],
'' !== $pair[0] => [self::uvString($pair[0]), ''],
default => null,
};
foreach ($pairs as $pair) {
if (null !== ($filteredPair = $filter($pair))) {
yield $filteredPair;
}
}
}
private static function formatQuery(Stringable|string|null $query): string
{
return match (true) {
null === $query => '',
str_starts_with((string) $query, '?') => substr((string) $query, 1),
default => (string) $query,
};
}
/**
* Normalizes type to UVString.
*
* @see https://webidl.spec.whatwg.org/#idl-USVString
*/
private static function uvString(Stringable|string|float|int|bool|null $value): string
{
return match (true) {
null === $value => 'null',
false === $value => 'false',
true === $value => 'true',
is_float($value) => (string) json_encode($value, JSON_PRESERVE_ZERO_FRACTION),
default => (string) $value,
};
}
/**
* Returns a new instance from a string or a stringable object.
*
* The input will be parsed from application/x-www-form-urlencoded format.
* The leading '?' character if present is ignored.
*/
public static function new(Stringable|string|null $query): self
{
return new self(Query::fromFormData(self::formatQuery($query)));
}
/**
* Returns a new instance from a literal sequence of name-value string pairs,
* or any object with an iterator that produces a sequence of string pairs.
*
* @param iterable<int, array{0:string, 1:string|null}> $pairs
*/
public static function fromPairs(iterable $pairs): self
{
return new self(Query::fromPairs($pairs));
}
/**
* Returns a new instance from a record of string keys and string values.
*
* A record can be, an iterable or any object with scalar or null public properties. Nesting is not supported.
*
* @param object|iterable<array-key, Stringable|string|float|int|bool|null> $associative
*/
public static function fromAssociative(object|array $associative): self
{
return new self(Query::fromPairs(self::yieldPairs($associative)));
}
/**
* Returns a new instance from a URI.
*/
public static function fromUri(Stringable|string $uri): self
{
$query = match (true) {
$uri instanceof UriInterface => $uri->getQuery(),
default => Uri::new($uri)->getQuery(),
};
return new self(Query::fromPairs(QueryString::parseFromValue($query, Converter::fromFormData())));
}
/**
* Returns a new instance from the input of PHP's http_build_query.
*/
public static function fromVariable(object|array $parameters): self
{
return self::fromPairs(self::parametersToPairs($parameters));
}
private static function parametersToPairs(array|object $data, string|int $prefix = '', array &$recursive = []): array
{
$yieldParameters = static fn (object|array $data): array => is_array($data) ? $data : get_object_vars($data);
$pairs = [];
foreach ($yieldParameters($data) as $name => $value) {
if (is_object($data)) {
$id = spl_object_hash($data);
if (!array_key_exists($id, $recursive)) {
$recursive[$id] = 1;
}
}
if (is_object($value)) {
$id = spl_object_hash($value);
if (array_key_exists($id, $recursive)) {
return [];
}
$recursive[$id] = 1;
}
if ('' !== $prefix) {
$name = $prefix.'['.$name.']';
}
$pairs = match (true) {
is_array($value),
is_object($value) => [...$pairs, ...self::parametersToPairs($value, $name, $recursive)],
is_scalar($value) => [...$pairs, [$name, self::uvString($value)]],
default => $pairs,
};
}
return $pairs;
}
public function value(): ?string
{
return $this->pairs->toFormData();
}
/**
* Returns a query string suitable for use in a URL.
*/
public function toString(): string
{
return $this->value() ?? '';
}
public function __toString(): string
{
return $this->toString();
}
public function jsonSerialize(): string
{
return $this->toString();
}
public function getUriComponent(): string
{
$value = $this->value() ?? '';
return match ('') {
$value => $value,
default => '?'.$value,
};
}
/**
* Returns an iterator allowing iteration through all keys contained in this object.
*
* @return iterable<string>
*/
public function keys(): iterable
{
foreach ($this->pairs as [$key, $__]) {
yield $key;
}
}
/**
* Returns an iterator allowing iteration through all values contained in this object.
*
* @return iterable<string>
*/
public function values(): iterable
{
foreach ($this->pairs as [$__, $value]) {
yield $value ?? '';
}
}
/**
* Tells whether the specified parameter is in the search parameters.
*
* The method requires at least one parameter as the pair name (string or null)
* and an optional second and last parameter as the pair value (Stringable|string|float|int|bool|null)
* <code>
* $params = new URLSearchParams('a=b&c);
* $params->has('c'); // return true
* $params->has('a', 'b'); // return true
* $params->has('a', 'c'); // return false
* </code>
*/
public function has(?string $name): bool
{
$name = self::uvString($name);
return match (func_num_args()) {
1 => $this->pairs->has($name),
2 => $this->pairs->hasPair($name, self::uvString(func_get_arg(1))), /* @phpstan-ignore-line */
default => throw new ArgumentCountError(__METHOD__.' requires at least one argument as the pair name and a second optional argument as the pair value.'),
};
}
/**
* Returns the first value associated to the given search parameter or null if none exists.
*/
public function get(?string $name): ?string
{
return match (true) {
$this->has($name) => $this->pairs->get(self::uvString($name)) ?? '',
default => null,
};
}
/**
* Returns all the values associated with a given search parameter as an array.
*
* @return array<string>
*/
public function getAll(?string $name): array
{
return array_map(
fn (?string $value): string => $value ?? '',
$this->pairs->getAll(self::uvString($name))
);
}
/**
* Tells whether the instance has some parameters.
*/
public function isNotEmpty(): bool
{
return ! $this->isEmpty();
}
/**
* Tells whether the instance has no parameters.
*/
public function isEmpty(): bool
{
return 0 === $this->size();
}
/**
* Returns the total number of distinct search parameter keys.
*/
public function uniqueKeyCount(): int
{
return count(
array_count_values(
array_column([...$this->pairs], 0)
)
);
}
/**
* Returns the total number of search parameter entries.
*/
public function size(): int
{
return count($this->pairs);
}
/**
* @see URLSearchParams::size()
*/
public function count(): int
{
return $this->size();
}
/**
* Allowing iteration through all key/value pairs contained in this object.
*
* The iterator returns key/value pairs in the same order as they appear in the query string.
* The key and value of each pair are string objects.
*/
public function entries(): Iterator
{
yield from $this->pairs;
}
/**
* @see URLSearchParams::entries()
*/
public function getIterator(): Iterator
{
return $this->entries();
}
/**
* Allows iteration through all values contained in this object via a callback function.
*
* @param Closure(string $value, string $key): void $callback
*/
public function each(Closure $callback): void
{
foreach ($this->pairs->pairs() as $key => $value) {
$callback($value ?? '', $key);
}
}
private function updateQuery(QueryInterface $query): void
{
if ($query->value() !== $this->pairs->value()) {
$this->pairs = $query;
}
}
/**
* Sets the value associated with a given search parameter to the given value.
*
* If there were several matching values, this method deletes the others.
* If the search parameter doesn't exist, this method creates it.
*/
public function set(?string $name, Stringable|string|float|int|bool|null $value): void
{
$this->updateQuery($this->pairs->withPair(self::uvString($name), self::uvString($value)));
}
/**
* Appends a specified key/value pair as a new search parameter.
*/
public function append(?string $name, Stringable|string|float|int|bool|null $value): void
{
$this->updateQuery($this->pairs->appendTo(self::uvString($name), self::uvString($value)));
}
/**
* Deletes specified parameters and their associated value(s) from the list of all search parameters.
*
* The method requires at least one parameter as the pair name (string or null)
* and an optional second and last parameter as the pair value (Stringable|string|float|int|bool|null)
* <code>
* $params = new URLSearchParams('a=b&c);
* $params->delete('c'); //delete all parameters with the key 'c'
* $params->delete('a', 'b') //delete all pairs with the key 'a' and the value 'b'
* </code>
*/
public function delete(?string $name): void
{
$name = self::uvString($name);
$this->updateQuery(match (func_num_args()) {
1 => $this->pairs->withoutPairByKey($name),
2 => $this->pairs->withoutPairByKeyValue($name, self::uvString(func_get_arg(1))), /* @phpstan-ignore-line */
default => throw new ArgumentCountError(__METHOD__.' requires at least one argument as the pair name and a second optional argument as the pair value.'),
});
}
/**
* Sorts all key/value pairs contained in this object in place and returns undefined.
*
* The sort order is according to unicode code points of the keys. This method
* uses a stable sorting algorithm (i.e. the relative order between
* key/value pairs with equal keys will be preserved).
*/
public function sort(): void
{
$this->updateQuery($this->pairs->sort());
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated Since version 7.4.0
* @see URLSearchParams::fromVariable()
*
* @codeCoverageIgnore
*
*/
#[Deprecated(message:'use League\Uri\Components\URLSearchParams::fromVariable() instead', since:'league/uri-components:7.4.0')]
public static function fromParameters(object|array $parameters): self
{
return new self(Query::fromParameters($parameters));
}
}
|