-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPath.php
More file actions
292 lines (248 loc) · 7.73 KB
/
Path.php
File metadata and controls
292 lines (248 loc) · 7.73 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
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
<?php
declare(strict_types=1);
namespace Internal\DLoad\Module\Common\FileSystem;
/**
* @psalm-internal Internal\DLoad
*/
final class Path implements \Stringable
{
private const DS = '/';
/**
* @param non-empty-string $path The filesystem path. In never ends with a separator.
* Might be ended with "." or ".." if the path is a directory.
*/
private function __construct(
private readonly string $path,
private readonly bool $isAbsolute,
) {}
/**
* Create a new path object
*/
public static function create(self|string $path = ''): self
{
return $path instanceof self
? $path
: new self($norm = self::normalizePath($path), self::_isAbsolute($norm));
}
/**
* Join this path with one or more path components
*/
public function join(self|string ...$paths): self
{
$result = $this->path;
foreach ($paths as $path) {
if ($path instanceof self) {
$path->isAbsolute and throw new \LogicException('Joining an absolute path is not allowed.');
$result .= self::DS . $path->path;
continue;
}
if ($path === '') {
continue;
}
$path = self::normalizePath($path);
self::_isAbsolute($path) and throw new \LogicException('Joining an absolute path is not allowed.');
$result .= self::DS . $path;
}
// We return the raw string, not a normalized path, since it's already normalized
return self::create($result);
}
/**
* Return the file name (the final path component)
*/
public function name(): string
{
$pos = \strrpos($this->path, self::DS);
return $pos === false
? $this->path
: \substr($this->path, $pos + 1);
}
/**
* Return the file stem (the file name without its extension)
*
* @return non-empty-string
*/
public function stem(): string
{
$name = $this->name();
$pos = \strrpos($name, '.');
return $pos === false || $pos === 0 ? $name : \substr($name, 0, $pos);
}
/**
* Return the file suffix (extension) without the leading dot
*/
public function extension(): string
{
$name = $this->name();
return \pathinfo($name, PATHINFO_EXTENSION);
}
/**
* Return the parent directory path
*/
public function parent(): self
{
$parts = \explode(self::DS, $this->path);
if (\count($parts) === 1) {
return match ($this->path) {
'.' => self::create('..'),
'..' => self::create('../..'),
default => self::create('.'),
};
}
if ($this->isAbsolute && \count($parts) === 2) {
// If the path is absolute and has only two parts, return the root
return self::create($parts[0] . self::DS);
}
if (!$this->isAbsolute && $parts[\array_key_last($parts)] === '..') {
return $this->join('..');
}
// Remove the last part of the path
\array_pop($parts);
return self::create(\implode(self::DS, $parts));
}
/**
* Return whether this path is absolute
*/
public function isAbsolute(): bool
{
return $this->isAbsolute;
}
/**
* Return whether this path is relative
*/
public function isRelative(): bool
{
return !$this->isAbsolute;
}
/**
* Check if the path exists.
*/
public function exists(): bool
{
return \file_exists($this->path);
}
/**
* Check if the path is a directory.
* True as the result doesn't mean that the directory exists.
*/
public function isDir(): bool
{
return match (true) {
$this->path === '.',
$this->path === '..',
$this->isAbsolute && \substr($this->path, -2) === self::DS . '.',
\is_dir($this->path) => true,
default => false,
};
}
/**
* @return bool True if the path exists and is writable.
*/
public function isWriteable(): bool
{
return $this->exists() && \is_writable($this->path);
}
/**
* Check if the path is a file.
* True as the result doesn't mean that the file exists.
*/
public function isFile(): bool
{
return match (true) {
$this->path === '.',
$this->path === '..',
$this->isAbsolute && \substr($this->path, -2) === self::DS . '.' => false,
\is_file($this->path) => true,
default => false,
};
}
/**
* Return a normalized absolute version of this path
*
* @param non-empty-string|null $cwd Current working directory to resolve relative paths against.
*/
public function absolute(?string $cwd = null): self
{
if ($this->isAbsolute()) {
return $this;
}
$cwd ??= \getcwd();
$cwd === false and throw new \RuntimeException('Cannot get current working directory.');
return self::create($cwd . self::DS . $this->path);
}
/**
* Return a normalized relative version of this path.
*
* @return non-empty-string
*/
public function __toString(): string
{
return $this->path;
}
/**
* Check if a path is absolute.
*
* @param non-empty-string $path A normalized path.
*/
private static function _isAbsolute(string $path): bool
{
return \preg_match('~^[a-zA-Z]:~', $path) === 1 || \str_starts_with($path, self::DS);
}
/**
* Normalize a path by converting directory separators and resolving special path segments.
*
* @return non-empty-string
*/
private static function normalizePath(string $path): string
{
// Normalize directory separators
$path = \trim(\str_replace(['\\', '/'], self::DS, $path));
// Normalize multiple separators
$path = (string) \preg_replace(
'~' . \preg_quote(self::DS, '~') . '{2,}~',
self::DS,
$path,
);
// Empty path becomes current directory
if ($path === '') {
return '.';
}
// Determine if the path is absolute
$isAbsolute = self::_isAbsolute($path);
// Resolve special path segments
$parts = \explode(self::DS, $path);
/** @var non-empty-string|null $driverLetter */
if ($isAbsolute && \preg_match('~^([a-zA-Z]):~', $path, $matches) === 1) {
// Windows-style path with a drive letter
$driverLetter = $matches[1];
\array_shift($parts);
} else {
$driverLetter = null;
}
$result = [];
foreach ($parts as $part) {
$part = \trim($part, ' ');
if ($part === '.' || $part === '') {
continue;
}
if ($part === '..') {
if ($result !== [] && $result[\array_key_last($result)] !== '..') {
\array_pop($result);
continue;
}
$isAbsolute and throw new \LogicException("Cannot go up from root in `{$path}`");
$result[] = '..';
continue;
}
$result[] = $part;
}
// Reconstruct the path
$normalizedPath = $result === [] ? '.' : \implode(self::DS, $result);
// Add an absolute path prefix if necessary
if ($isAbsolute) {
$normalizedPath = $driverLetter !== null
? "$driverLetter:" . self::DS . $normalizedPath
: self::DS . $normalizedPath;
}
return $normalizedPath;
}
}