Skip to content

Commit dcde2be

Browse files
committed
Resolve __FILE__ and __DIR__ against the trait file in a trait context
1 parent 20e93ac commit dcde2be

5 files changed

Lines changed: 49 additions & 1 deletion

File tree

src/Reflection/InitializerExprContext.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,19 @@ public static function fromScope(Scope $scope): self
4242
{
4343
$function = $scope->getFunction();
4444

45+
// __FILE__ and __DIR__ are resolved at compile time, so in a trait context they
46+
// point at the file the trait is declared in, while Scope::getFile() returns the
47+
// file of the class that uses the trait.
48+
$file = $scope->getFile();
49+
if ($scope->isInTrait()) {
50+
$traitFileName = $scope->getTraitReflection()->getFileName();
51+
if ($traitFileName !== null) {
52+
$file = $traitFileName;
53+
}
54+
}
55+
4556
return new self(
46-
$scope->getFile(),
57+
$file,
4758
$scope->getNamespace(),
4859
$scope->isInClass() ? $scope->getClassReflection()->getName() : null,
4960
$scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,

tests/PHPStan/Analyser/PathConstantsTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,11 @@ public static function getAdditionalConfigFiles(): array
3838
];
3939
}
4040

41+
protected static function getAdditionalAnalysedFiles(): array
42+
{
43+
return [
44+
__DIR__ . '/data/path-constants-trait/PathConstantsTrait.php',
45+
];
46+
}
47+
4148
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace PathConstantsTestTrait;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
trait PathConstantsTrait
8+
{
9+
10+
public function doFoo(): void
11+
{
12+
assertType('\'path-constants-trait\'', substr(__DIR__, -20));
13+
assertType('\'PathConstantsTrait.php\'', substr(__FILE__, -22));
14+
}
15+
16+
}

tests/PHPStan/Analyser/data/pathConstants-win.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,10 @@
44

55
\PHPStan\Testing\assertType('\'Analyser\\\\data\'', substr(__DIR__, -13));
66
\PHPStan\Testing\assertType('\'pathConstants-win.php\'', substr(__FILE__, -21));
7+
8+
class PathConstantsClassWin
9+
{
10+
11+
use \PathConstantsTestTrait\PathConstantsTrait;
12+
13+
}

tests/PHPStan/Analyser/data/pathConstants.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,10 @@
44

55
\PHPStan\Testing\assertType('\'Analyser/data\'', substr(__DIR__, -13));
66
\PHPStan\Testing\assertType('\'pathConstants.php\'', substr(__FILE__, -17));
7+
8+
class PathConstantsClass
9+
{
10+
11+
use \PathConstantsTestTrait\PathConstantsTrait;
12+
13+
}

0 commit comments

Comments
 (0)