diff --git a/src/File/SimpleRelativePathHelper.php b/src/File/SimpleRelativePathHelper.php index 9c0caeca30..fda92e2493 100644 --- a/src/File/SimpleRelativePathHelper.php +++ b/src/File/SimpleRelativePathHelper.php @@ -6,16 +6,36 @@ class SimpleRelativePathHelper implements RelativePathHelper { /** @var string */ - private $currentWorkingDirectory; + private $directorySeparator; - public function __construct(string $currentWorkingDirectory) + /** @var string */ + private $currentWorkingDirectory = ''; + + public function __construct(string $currentWorkingDirectory, string $directorySeparator = DIRECTORY_SEPARATOR) { + $this->directorySeparator = $directorySeparator; + + if ($currentWorkingDirectory !== $directorySeparator) { + $currentWorkingDirectory = rtrim($currentWorkingDirectory, $directorySeparator); + } $this->currentWorkingDirectory = $currentWorkingDirectory; } public function getRelativePath(string $filename): string { - if ($this->currentWorkingDirectory !== '' && strpos($filename, $this->currentWorkingDirectory) === 0) { + if ($this->currentWorkingDirectory === '') { + return $filename; + } + + if ($this->currentWorkingDirectory === $this->directorySeparator) { + if (strpos($filename, $this->currentWorkingDirectory) === 0) { + return substr($filename, strlen($this->currentWorkingDirectory)); + } + + return $filename; + } + + if (strpos($filename, $this->currentWorkingDirectory . $this->directorySeparator) === 0) { return substr($filename, strlen($this->currentWorkingDirectory) + 1); } diff --git a/tests/PHPStan/File/SimpleRelativePathHelperTest.php b/tests/PHPStan/File/SimpleRelativePathHelperTest.php new file mode 100644 index 0000000000..969f4e0496 --- /dev/null +++ b/tests/PHPStan/File/SimpleRelativePathHelperTest.php @@ -0,0 +1,89 @@ +assertSame( + $expectedResult, + $helper->getRelativePath($filenameToRelativize) + ); + } + +}