-
-
Notifications
You must be signed in to change notification settings - Fork 117
/
FilePath.php
122 lines (99 loc) · 2.82 KB
/
FilePath.php
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
<?php
namespace Phpactor\Filesystem\Domain;
use Phpactor\TextDocument\TextDocumentUri;
use RuntimeException;
use SplFileInfo;
use Symfony\Component\Filesystem\Path;
final class FilePath
{
private function __construct(private TextDocumentUri $uri)
{
}
public function __toString(): string
{
return $this->uri->path();
}
public function uriAsString(): string
{
return $this->uri->__toString();
}
public static function fromString(string $string): FilePath
{
$textDocumentUri = TextDocumentUri::fromString($string);
return new self($textDocumentUri);
}
/**
* @param array<string> $parts
*/
public static function fromParts(array $parts): FilePath
{
$path = Path::join(...$parts);
if (!Path::isAbsolute($path)) {
// Not sure if this makes sense… Maybe it should just throw?
$path = Path::makeAbsolute($path, '/');
}
return self::fromString($path);
}
public static function fromSplFileInfo(SplFileInfo $fileInfo): FilePath
{
return self::fromString((string) $fileInfo);
}
public static function fromFilePathOrString(FilePath|string $path): FilePath
{
if ($path instanceof FilePath) {
return $path;
}
if (is_string($path)) {
return self::fromString($path);
}
}
public function isDirectory(): bool
{
return is_dir($this->uri->path());
}
/**
* This will lose the scheme
*/
public function asSplFileInfo(): SplFileInfo
{
return new SplFileInfo($this->uri->path());
}
public function makeAbsoluteFromString(string $path): FilePath
{
if (Path::isAbsolute($path)) {
$path = self::fromString($path);
if (false === $path->isWithinOrSame($this)) {
throw new RuntimeException(sprintf(
'Trying to create descendant from absolute path "%s" that does not lie within context path "%s"',
(string) $path,
(string) $this
));
}
return $path;
}
return self::fromParts([(string) $this, $path]);
}
public function extension(): string
{
return Path::getExtension($this->uri->path());
}
public function isWithin(FilePath $path): bool
{
return Path::isBasePath($path->path(), $this->path());
}
public function isWithinOrSame(FilePath $path): bool
{
if ($this->path() == $path->path()) {
return true;
}
return $this->isWithin($path);
}
public function isNamed(string $name): bool
{
return basename($this->path()) == $name;
}
public function path(): string
{
return $this->uri->path();
}
}