Skip to content

Commit bce6955

Browse files
committed
Fix simple relative path helper stripping first character when working directory is a slash
1 parent 7c9daa4 commit bce6955

2 files changed

Lines changed: 53 additions & 1 deletion

File tree

‎src/File/SimpleRelativePathHelper.php‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@ public function __construct(
2323
public function getRelativePath(string $filename): string
2424
{
2525
if ($this->currentWorkingDirectory !== '' && str_starts_with($filename, $this->currentWorkingDirectory)) {
26-
return str_replace('\\', '/', substr($filename, strlen($this->currentWorkingDirectory) + 1));
26+
$length = strlen($this->currentWorkingDirectory);
27+
28+
if ($this->currentWorkingDirectory !== '/') {
29+
$length += 1;
30+
}
31+
32+
return str_replace('\\', '/', substr($filename, $length));
2733
}
2834

2935
return str_replace('\\', '/', $filename);
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\File;
4+
5+
use PHPUnit\Framework\Attributes\DataProvider;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class SimpleRelativePathHelperTest extends TestCase
9+
{
10+
11+
public static function dataGetRelativePath(): array
12+
{
13+
return [
14+
[
15+
'/project',
16+
'/project/src/HelloWorld.php',
17+
'src/HelloWorld.php',
18+
],
19+
[
20+
'',
21+
'/project/src/HelloWorld.php',
22+
'/project/src/HelloWorld.php',
23+
],
24+
[
25+
'/',
26+
'/project/src/HelloWorld.php',
27+
'project/src/HelloWorld.php',
28+
],
29+
];
30+
}
31+
32+
#[DataProvider('dataGetRelativePath')]
33+
public function testGetRelativePath(
34+
string $currentWorkingDirectory,
35+
string $filename,
36+
string $expectedRelativePath,
37+
): void
38+
{
39+
$helper = new SimpleRelativePathHelper($currentWorkingDirectory);
40+
$this->assertSame(
41+
$expectedRelativePath,
42+
$helper->getRelativePath($filename),
43+
);
44+
}
45+
46+
}

0 commit comments

Comments
 (0)