Skip to content

Commit fcd8e0c

Browse files
committed
added FileSystem::resolvePath()
1 parent ea73797 commit fcd8e0c

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/Utils/FileSystem.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,19 @@ public static function joinPaths(string ...$paths): string
305305
}
306306

307307

308+
/**
309+
* Resolves a path against a base path. If the path is absolute, returns it directly, if it's relative, joins it with the base path.
310+
*/
311+
public static function resolvePath(string $basePath, string $path): string
312+
{
313+
return match (true) {
314+
self::isAbsolute($path) => self::platformSlashes($path),
315+
$path === '' => self::platformSlashes($basePath),
316+
default => self::joinPaths($basePath, $path),
317+
};
318+
}
319+
320+
308321
/**
309322
* Converts backslashes to slashes.
310323
*/
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Utils\FileSystem;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
test('absolute paths', function () {
13+
$S = DIRECTORY_SEPARATOR;
14+
Assert::same("{$S}abs{$S}path", FileSystem::resolvePath('/base/dir', '/abs/path'));
15+
Assert::same("c:{$S}abs{$S}path", FileSystem::resolvePath('/base/dir', 'c:/abs/path'));
16+
Assert::same('http://example.com', FileSystem::resolvePath('/base/dir', 'http://example.com'));
17+
Assert::same("{$S}", FileSystem::resolvePath('base', '/'));
18+
});
19+
20+
test('relative paths', function () {
21+
$S = DIRECTORY_SEPARATOR;
22+
Assert::same("base{$S}rel", FileSystem::resolvePath('base', 'rel'));
23+
Assert::same("{$S}base{$S}rel", FileSystem::resolvePath('/base', 'rel'));
24+
Assert::same("{$S}base{$S}dir{$S}file.txt", FileSystem::resolvePath('/base/dir/', 'file.txt'));
25+
});
26+
27+
test('path normalization', function () {
28+
$S = DIRECTORY_SEPARATOR;
29+
Assert::same("{$S}base{$S}", FileSystem::resolvePath('/base/dir', '../'));
30+
Assert::same("{$S}base{$S}other", FileSystem::resolvePath('/base/dir/', '../other'));
31+
Assert::same("{$S}..{$S}other", FileSystem::resolvePath('/base/', '../../other'));
32+
Assert::same("base{$S}dir", FileSystem::resolvePath('base/./dir/../', 'dir'));
33+
});
34+
35+
test('special cases', function () {
36+
$S = DIRECTORY_SEPARATOR;
37+
Assert::same('base', FileSystem::resolvePath('base', ''));
38+
Assert::same("base{$S}dir", FileSystem::resolvePath('base/dir', ''));
39+
Assert::same('', FileSystem::resolvePath('', ''));
40+
});

0 commit comments

Comments
 (0)