Repository navigation
Expand file tree
/
Copy pathPath.php
More file actions
87 lines (73 loc) · 2.21 KB
/
Copy pathPath.php
File metadata and controls
87 lines (73 loc) · 2.21 KB
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
<?php
declare(strict_types=1);
namespace Pharaonic\Diff;
use InvalidArgumentException;
use Pharaonic\Diff\Support\DotNotation;
/**
* The location of a value inside the compared data, as a list of keys and list indexes
*
* The root is the empty path. Segments are stored the way PHP stores array keys, so "4" and 4 are
* the same segment.
*/
final class Path
{
/**
* @param list<int|string> $segments
*/
private function __construct(private array $segments) {}
/**
* @param array<int|string> $segments
*/
public static function fromSegments(array $segments): self
{
return new self(array_map([self::class, 'segment'], array_values($segments)));
}
/**
* Parse dot notation: "users.4.email", with "\.", "\*" and "\\" for a literal dot, star or
* backslash inside a key. The empty string is the root.
*/
public static function fromDot(string $path): self
{
return self::fromSegments(array_map(
static fn(?string $segment): string => $segment ?? '*',
DotNotation::parse($path),
));
}
/**
* @return list<int|string>
*/
public function segments(): array
{
return $this->segments;
}
public function isRoot(): bool
{
return $this->segments === [];
}
/**
* Dot notation, escaped so that fromDot() reads it back
*/
public function toDot(): string
{
return DotNotation::format($this->segments);
}
/**
* RFC 6901 JSON Pointer: "" for the root, "/users/4/email" otherwise
*/
public function toJsonPointer(): string
{
$pointer = '';
foreach ($this->segments as $segment) {
$pointer .= '/' . strtr((string) $segment, ['~' => '~0', '/' => '~1']);
}
return $pointer;
}
private static function segment(mixed $segment): int|string
{
if (! is_int($segment) && ! is_string($segment)) {
throw new InvalidArgumentException(sprintf('A path segment must be an int or a string, %s given.', get_debug_type($segment)));
}
// Let PHP cast the key exactly as it would inside an array.
return array_key_first([$segment => true]);
}
}