Skip to content

Commit

Permalink
Fix resolving of __DIR__, __NAMESPACE__ in traits
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Jan 11, 2023
1 parent c39d114 commit acee0af
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Reflection/InitializerExprTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,13 @@ public function getType(Expr $expr, InitializerExprContext $context): Type
}

if ($expr instanceof MagicConst\Class_) {
if ($context->getTraitName() !== null) {
return TypeCombinator::intersect(
new ClassStringType(),
new AccessoryLiteralStringType(),
);
}

if ($context->getClassName() === null) {
return new ConstantStringType('');
}
Expand All @@ -344,6 +351,13 @@ public function getType(Expr $expr, InitializerExprContext $context): Type
}

if ($expr instanceof MagicConst\Namespace_) {
if ($context->getTraitName() !== null) {
return TypeCombinator::intersect(
new StringType(),
new AccessoryLiteralStringType(),
);
}

return new ConstantStringType($context->getNamespace() ?? '');
}

Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1174,6 +1174,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8625.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8621.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8084.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-3019.php');
}

/**
Expand Down
35 changes: 35 additions & 0 deletions tests/PHPStan/Analyser/data/bug-3019.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Bug3019;

use function PHPStan\Testing\assertType;

trait FooTrait
{
public function doFoo(): void
{
assertType('class-string&literal-string', __CLASS__);
assertType('literal-string', __NAMESPACE__);
}

public function doFooBaz(): void
{
$key = __CLASS__ === 'Bug3019\Foo' ? 'display' : 'layout';
}
}

class Foo
{
use FooTrait;

public function doFooBar(): void
{
assertType("'Bug3019\\\Foo'", __CLASS__);
assertType("'Bug3019'", __NAMESPACE__);
}
}

class Bar
{
use FooTrait;
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,10 @@ public function testReportPhpDoc(): void
]);
}

public function testBug3019(): void
{
$this->treatPhpDocTypesAsCertain = true;
$this->analyse([__DIR__ . '/../../Analyser/data/bug-3019.php'], []);
}

}

0 comments on commit acee0af

Please sign in to comment.