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
|
<?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 Deprecated;
use Iterator;
use League\Uri\Contracts\PathInterface;
use League\Uri\Contracts\SegmentedPathInterface;
use League\Uri\Contracts\UriInterface;
use League\Uri\Encoder;
use League\Uri\Exceptions\OffsetOutOfBounds;
use League\Uri\Exceptions\SyntaxError;
use Psr\Http\Message\UriInterface as Psr7UriInterface;
use Stringable;
use TypeError;
use function array_count_values;
use function array_filter;
use function array_keys;
use function array_pop;
use function array_unshift;
use function count;
use function dirname;
use function explode;
use function implode;
use function ltrim;
use function rtrim;
use function sprintf;
use function str_contains;
use function str_replace;
use function str_starts_with;
use function strrpos;
use function substr;
use const ARRAY_FILTER_USE_KEY;
use const FILTER_VALIDATE_INT;
use const PATHINFO_EXTENSION;
final class HierarchicalPath extends Component implements SegmentedPathInterface
{
private const SEPARATOR = '/';
private const IS_ABSOLUTE = 1;
private const IS_RELATIVE = 0;
private readonly PathInterface $path;
/** @var array<string> */
private readonly array $segments;
private function __construct(Stringable|string $path)
{
if (!$path instanceof PathInterface) {
$path = Path::new($path);
}
$this->path = $path;
$segments = $this->path->decoded();
if ($this->path->isAbsolute()) {
$segments = substr($segments, 1);
}
$this->segments = explode(self::SEPARATOR, $segments);
}
/**
* Returns a new instance from a string or a stringable object.
*/
public static function new(Stringable|string $value = ''): self
{
return new self($value);
}
/**
* Create a new instance from a URI object.
*/
public static function fromUri(Stringable|string $uri): self
{
return new self(Path::fromUri($uri));
}
/**
* Returns a new instance from an iterable structure.
*
* @throws TypeError If the segments are malformed
*/
public static function fromRelative(string ...$segments): self
{
return self::fromSegments(self::IS_RELATIVE, $segments);
}
/**
* Returns a new instance from an iterable structure.
*
* @throws TypeError If the segments are malformed
*/
public static function fromAbsolute(string ...$segments): self
{
return self::fromSegments(self::IS_ABSOLUTE, $segments);
}
/**
* @param array<string> $segments
*/
private static function fromSegments(int $pathType, array $segments): self
{
$path = implode(self::SEPARATOR, $segments);
return match (true) {
self::IS_RELATIVE === $pathType => new self(ltrim($path, self::SEPARATOR)),
self::SEPARATOR !== ($path[0] ?? '') => new self(self::SEPARATOR.$path),
default => new self($path),
};
}
public function count(): int
{
return count($this->segments);
}
public function getIterator(): Iterator
{
yield from $this->segments;
}
public function isAbsolute(): bool
{
return $this->path->isAbsolute();
}
public function hasTrailingSlash(): bool
{
return $this->path->hasTrailingSlash();
}
public function value(): ?string
{
return $this->path->value();
}
public function decoded(): string
{
return $this->path->decoded();
}
public function getDirname(): string
{
$path = $this->path->decoded();
return str_replace(
['\\', "\0"],
[self::SEPARATOR, '\\'],
dirname(str_replace('\\', "\0", $path))
);
}
public function getBasename(): string
{
$data = $this->segments;
$basename = (string) array_pop($data);
$pos = strpos($basename, ';');
return match (false) {
$pos => $basename,
default => substr($basename, 0, $pos),
};
}
public function getExtension(): string
{
[$basename] = explode(';', $this->getBasename(), 2);
return pathinfo($basename, PATHINFO_EXTENSION);
}
public function get(int $offset): ?string
{
if ($offset < 0) {
$offset += count($this->segments);
}
return $this->segments[$offset] ?? null;
}
public function keys(Stringable|string|null $segment = null): array
{
$segment = self::filterComponent($segment);
return match (null) {
$segment => array_keys($this->segments),
default => array_keys($this->segments, $segment, true),
};
}
public function withoutDotSegments(): PathInterface
{
$path = $this->path->withoutDotSegments();
return match ($this->path) {
$path => $this,
default => new self($path),
};
}
public function withLeadingSlash(): PathInterface
{
$path = $this->path->withLeadingSlash();
return match ($this->path) {
$path => $this,
default => new self($path),
};
}
public function withoutLeadingSlash(): PathInterface
{
$path = $this->path->withoutLeadingSlash();
return match ($this->path) {
$path => $this,
default => new self($path),
};
}
public function withoutTrailingSlash(): PathInterface
{
$path = $this->path->withoutTrailingSlash();
return match ($this->path) {
$path => $this,
default => new self($path),
};
}
public function withTrailingSlash(): PathInterface
{
$path = $this->path->withTrailingSlash();
return match ($this->path) {
$path => $this,
default => new self($path),
};
}
public function append(Stringable|string $segment): SegmentedPathInterface
{
/** @var string $segment */
$segment = self::filterComponent($segment);
return new self(
rtrim($this->path->toString(), self::SEPARATOR)
.self::SEPARATOR
.ltrim($segment, self::SEPARATOR)
);
}
public function prepend(Stringable|string $segment): SegmentedPathInterface
{
/** @var string $segment */
$segment = self::filterComponent($segment);
return new self(
rtrim($segment, self::SEPARATOR)
.self::SEPARATOR
.ltrim($this->path->toString(), self::SEPARATOR)
);
}
public function withSegment(int $key, Stringable|string $segment): SegmentedPathInterface
{
$nbSegments = count($this->segments);
if ($key < - $nbSegments - 1 || $key > $nbSegments) {
throw new OffsetOutOfBounds(sprintf('The given key `%s` is invalid.', $key));
}
if (0 > $key) {
$key += $nbSegments;
}
if ($nbSegments === $key) {
return $this->append($segment);
}
if (-1 === $key) {
return $this->prepend($segment);
}
if (!$segment instanceof PathInterface) {
$segment = new self($segment);
}
$segment = Encoder::decodeAll($segment);
if ($segment === $this->segments[$key]) {
return $this;
}
$segments = $this->segments;
$segments[$key] = $segment;
if ($this->isAbsolute()) {
array_unshift($segments, '');
}
return new self(implode(self::SEPARATOR, $segments));
}
public function withoutEmptySegments(): SegmentedPathInterface
{
/** @var string $path */
$path = preg_replace(',/+,', self::SEPARATOR, $this->toString());
return new self($path);
}
public function withoutSegment(int ...$keys): SegmentedPathInterface
{
if ([] === $keys) {
return $this;
}
$nb_segments = count($this->segments);
$options = ['options' => ['min_range' => - $nb_segments, 'max_range' => $nb_segments - 1]];
$deleted_keys = [];
foreach ($keys as $value) {
/** @var false|int $offset */
$offset = filter_var($value, FILTER_VALIDATE_INT, $options);
if (false === $offset) {
throw new OffsetOutOfBounds(sprintf('The key `%s` is invalid.', $value));
}
if ($offset < 0) {
$offset += $nb_segments;
}
$deleted_keys[] = $offset;
}
$deleted_keys = array_keys(array_count_values($deleted_keys));
$filter = static fn ($key): bool => !in_array($key, $deleted_keys, true);
$path = implode(self::SEPARATOR, array_filter($this->segments, $filter, ARRAY_FILTER_USE_KEY));
if ($this->isAbsolute()) {
return new self(self::SEPARATOR.$path);
}
return new self($path);
}
public function slice(int $offset, ?int $length = null): self
{
$nbSegments = count($this->segments);
if ($offset < -$nbSegments || $offset > $nbSegments) {
throw new OffsetOutOfBounds(sprintf('No segment can be found with at : `%s`.', $offset));
}
$segments = array_slice($this->segments, $offset, $length, true);
if ($this->hasTrailingSlash()) {
$segments[] = '';
}
return match (true) {
$segments === $this->segments => $this,
$this->isAbsolute() => self::fromAbsolute(...$segments),
default => self::fromRelative(...$segments),
};
}
public function withDirname(Stringable|string $path): SegmentedPathInterface
{
if (!$path instanceof PathInterface) {
$path = Path::new($path);
}
if ($path->value() === $this->getDirname()) {
return $this;
}
$segments = $this->segments;
return new self(
rtrim($path->toString(), self::SEPARATOR)
.self::SEPARATOR
.array_pop($segments)
);
}
public function withBasename(Stringable|string $basename): SegmentedPathInterface
{
/** @var string $basename */
$basename = $this->validateComponent($basename);
return match (true) {
str_contains($basename, self::SEPARATOR) => throw new SyntaxError('The basename cannot contain the path separator.'),
default => $this->withSegment(count($this->segments) - 1, $basename),
};
}
public function withExtension(Stringable|string $extension): SegmentedPathInterface
{
/** @var string $extension */
$extension = $this->validateComponent($extension);
if (str_contains($extension, self::SEPARATOR)) {
throw new SyntaxError('An extension sequence cannot contain a path delimiter.');
}
if (str_starts_with($extension, '.')) {
throw new SyntaxError('An extension sequence cannot contain a leading `.` character.');
}
/** @var string $basename */
$basename = $this->segments[array_key_last($this->segments)];
[$ext, $param] = explode(';', $basename, 2) + [1 => null];
if ('' === $ext) {
return $this;
}
return $this->withBasename($this->buildBasename($extension, (string) $ext, $param));
}
/**
* Creates a new basename with a new extension.
*/
private function buildBasename(string $extension, string $ext, ?string $param = null): string
{
$length = strrpos($ext, '.'.pathinfo($ext, PATHINFO_EXTENSION));
if (false !== $length) {
$ext = substr($ext, 0, $length);
}
if (null !== $param && '' !== $param) {
$param = ';'.$param;
}
$extension = trim($extension);
if ('' === $extension) {
return $ext.$param;
}
return $ext.'.'.$extension.$param;
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated Since version 7.0.0
* @see HierarchicalPath::getIterator()
*
* @codeCoverageIgnore
*
* Returns a new instance from a string or a stringable object.
*/
#[Deprecated(message:'use League\Uri\Components\HierarchicalPath::getIterator() instead', since:'league/uri-components:7.0.0')]
public function segments(): array
{
return $this->segments;
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated Since version 7.0.0
* @see HierarchicalPath::new()
*
* @codeCoverageIgnore
*
* Returns a new instance from a string or a stringable object.
*/
#[Deprecated(message:'use League\Uri\Components\HierarchicalPath::new() instead', since:'league/uri-components:7.0.0')]
public static function createFromString(Stringable|string $path): self
{
return self::new($path);
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated Since version 7.0.0
* @see HierarchicalPath::new()
*
* @codeCoverageIgnore
*/
#[Deprecated(message:'use League\Uri\Components\HierarchicalPath::new() instead', since:'league/uri-components:7.0.0')]
public static function createFromPath(PathInterface $path): self
{
return self::new($path);
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @throws TypeError If the segments are malformed
*@see HierarchicalPath::fromRelative()
*
* @codeCoverageIgnore
*
* Returns a new instance from an iterable structure.
*
* @deprecated Since version 7.0.0
*/
#[Deprecated(message:'use League\Uri\Components\HierarchicalPath::fromRelative() instead', since:'league/uri-components:7.0.0')]
public static function createRelativeFromSegments(iterable $segments): self
{
return self::fromRelative(...$segments);
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @throws TypeError If the segments are malformed
*@see HierarchicalPath::fromAbsolute()
*
* @codeCoverageIgnore
*
* Returns a new instance from an iterable structure.
*
* @deprecated Since version 7.0.0
*/
#[Deprecated(message:'use League\Uri\Components\HierarchicalPath::fromAbsolute() instead', since:'league/uri-components:7.0.0')]
public static function createAbsoluteFromSegments(iterable $segments): self
{
return self::fromAbsolute(...$segments);
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated Since version 7.0.0
* @see HierarchicalPath::fromUri()
*
* @codeCoverageIgnore
*
* Create a new instance from a URI object.
*/
#[Deprecated(message:'use League\Uri\Components\HierarchicalPath::fromUri() instead', since:'league/uri-components:7.0.0')]
public static function createFromUri(Psr7UriInterface|UriInterface $uri): self
{
return self::fromUri($uri);
}
}
|