Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix resolving of __DIR__, __NAMESPACE__ in traits #2043

Merged
merged 5 commits into from Jan 11, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Reflection/InitializerExprTypeResolver.php
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
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
@@ -0,0 +1,35 @@
<?php

namespace Bug3019;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I verified this code still fails without the patch for both Test-cases


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;
}
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'], []);
}

}