Skip to content

Commit

Permalink
$this type inside object creation (#2620)
Browse files Browse the repository at this point in the history
* Add test

* Fixing regression of object type creation classes

* using do while for less code

* improving test names

* Fixing stuff

---------

Co-authored-by: przepompownia <przepompownia@users.noreply.github.com>
  • Loading branch information
mamazu and przepompownia committed Mar 30, 2024
1 parent f504fe3 commit 1fe432d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
19 changes: 11 additions & 8 deletions lib/WorseReflection/Core/Inference/Walker/FunctionLikeWalker.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,16 @@ public function exit(FrameResolver $resolver, Frame $frame, Node $node): Frame
private function walkFunctionLike(FrameResolver $resolver, Frame $frame, FunctionLike $node): void
{
$namespace = $node->getNamespaceDefinition();
$classNode = $node->getFirstAncestor(
ClassDeclaration::class,
InterfaceDeclaration::class,
TraitDeclaration::class,
EnumDeclaration::class,
ObjectCreationExpression::class, // For Inline classes
);
do {
// If we are here we found a normal ObjectCreationExpression like: new A(); and this is not useful and we continue traversing
$classNode = ($classNode ?? $node)->getFirstAncestor(
ClassDeclaration::class,
InterfaceDeclaration::class,
TraitDeclaration::class,
EnumDeclaration::class,
ObjectCreationExpression::class, // For Inline classes
);
} while ($classNode instanceof ObjectCreationExpression && $classNode->classTypeDesignator instanceof Node);

if ($node instanceof AnonymousFunctionCreationExpression) {
$this->addAnonymousImports($frame, $node);
Expand All @@ -87,7 +90,7 @@ private function walkFunctionLike(FrameResolver $resolver, Frame $frame, Functio
}

// works for both closure and class method (we currently ignore binding)
if ($classNode) {
if ($classNode !== null) {
$classType = $resolver->resolveNode($frame, $classNode)->type();
$this->addClassContext($node, $classType, $frame);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,29 @@ public function hello()
$this->assertEquals(false, $frame->locals()->byName('this')->first()->isProperty());
}];

yield 'It returns this with correct type in an anonymous function' => [
<<<'EOT'
<?php
namespace Foobar\Barfoo;
use Acme\Factory;
class Foobar
{
public function hello()
{
new \ReflectionFunction(function() { <> });
}
}
EOT
, function (Frame $frame): void {
$this->assertCount(1, $frame->locals()->byName('this'));
$this->assertEquals('Foobar\Barfoo\Foobar', $frame->locals()->byName('this')->first()->type()->__toString());
$this->assertEquals(false, $frame->locals()->byName('this')->first()->isProperty());
}];

yield 'It returns method arguments' => [
<<<'EOT'
<?php
Expand Down

0 comments on commit 1fe432d

Please sign in to comment.