Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/Rules/Keywords/RequireFileExistsRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ private function doesFileExist(string $path, Scope $scope): bool
$directories = array_merge(
[$this->currentWorkingDirectory],
explode(PATH_SEPARATOR, get_include_path()),
[dirname($scope->getFile())],
[dirname($this->getScopeFile($scope))],
);

foreach ($directories as $directory) {
Expand All @@ -116,6 +116,24 @@ private function doesFileExist(string $path, Scope $scope): bool
return false;
}

/**
* The "calling script's own directory" fallback of a relative include is resolved
* at compile time, so inside a trait it is the directory of the file the trait is
* declared in - not the file of the class that uses it, which is what
* Scope::getFile() returns in a trait context.
*/
private function getScopeFile(Scope $scope): string
{
if ($scope->isInTrait()) {
$traitFileName = $scope->getTraitReflection()->getFileName();
if ($traitFileName !== null) {
return $this->fileHelper->normalizePath($traitFileName);
}
}

return $scope->getFile();
}

private function doesFileExistForDirectory(string $path, string $workingDirectory): bool
{
$fileHelper = new FileHelper($workingDirectory);
Expand Down
13 changes: 13 additions & 0 deletions tests/PHPStan/Rules/Keywords/RequireFileExistsRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,19 @@ public function testBug12203(): void
]);
}

public function testRelativePathInTrait(): void
{
$this->analyse([
__DIR__ . '/data/include-relative-in-trait/trait-dir/IncludeRelativeTrait.php',
__DIR__ . '/data/include-relative-in-trait/class-dir/IncludeRelativeClass.php',
], [
[
'Path in include() "only-in-class-dir.php" is not a file or it does not exist.',
15,
],
]);
}

public function testInFileExists(): void
{
$this->analyse([__DIR__ . '/data/include-in-file-exists.php'], []);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace IncludeRelativeInTrait;

class IncludeRelativeClass
{

use IncludeRelativeTrait;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

return ['only-in-class-dir' => true];
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace IncludeRelativeInTrait;

trait IncludeRelativeTrait
{

public function relativeInTraitDir(): void
{
include 'only-in-trait-dir.php';
}

public function relativeInClassDir(): void
{
include 'only-in-class-dir.php';
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

return ['only-in-trait-dir' => true];
Loading