Skip to content

Commit

Permalink
Fix endless recursion with nested traits via anonymous classes
Browse files Browse the repository at this point in the history
  • Loading branch information
herndlm committed May 12, 2022
1 parent 43cb6ab commit aad29aa
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Analyser/MutatingScope.php
Expand Up @@ -3176,6 +3176,17 @@ public function enterClass(ClassReflection $classReflection): self
[
'this' => VariableTypeHolder::createYes(new ThisType($classReflection)),
],
[],
[],
null,
null,
true,
[],
[],
[],
[],
false,
$classReflection->isAnonymous() ? $this : null,
);
}

Expand Down
12 changes: 12 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Expand Up @@ -3725,8 +3725,20 @@ static function (): void {
*/
private function processTraitUse(Node\Stmt\TraitUse $node, MutatingScope $classScope, callable $nodeCallback): void
{
$parentTraitNames = [];
$parent = $classScope->getParentScope();
while ($parent !== null) {
if ($parent->isInTrait()) {
$parentTraitNames[] = $parent->getTraitReflection()->getName();
}
$parent = $parent->getParentScope();
}

foreach ($node->traits as $trait) {
$traitName = (string) $trait;
if (in_array($traitName, $parentTraitNames, true)) {
continue;
}
if (!$this->reflectionProvider->hasClass($traitName)) {
continue;
}
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Analyser/AnalyserIntegrationTest.php
Expand Up @@ -800,6 +800,14 @@ public function testDiscussion7124(): void
$this->assertSame(59, $errors[3]->getLine());
}

public function testBug7214(): void
{
$errors = $this->runAnalyse(__DIR__ . '/data/bug-7214.php');
$this->assertCount(1, $errors);
$this->assertSame('Method Bug7214\HelloWorld::getFoo() has no return type specified.', $errors[0]->getMessage());
$this->assertSame(6, $errors[0]->getLine());
}

/**
* @param string[]|null $allAnalysedFiles
* @return Error[]
Expand Down
19 changes: 19 additions & 0 deletions tests/PHPStan/Analyser/data/bug-7214.php
@@ -0,0 +1,19 @@
<?php declare(strict_types = 1);

namespace Bug7214;

trait foo {
public function getFoo()
{
return new class {
use foo;
};
}
}

class HelloWorld
{
use foo;
}

var_dump((new HelloWorld())->getFoo()->getFoo());

0 comments on commit aad29aa

Please sign in to comment.