Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\NarrowUnusedSetUpDefinedPropertyRector\Fixture;

use PHPUnit\Framework\TestCase;

final class SkipPropertyUsedInClosure extends TestCase
{
private array $dataSource;

protected function setUp(): void
{
$this->dataSource = [1, 2, 3];

$this->resolver = function () {
return $this->dataSource;
};
}

public function test()
{
$resolver = $this->resolver;
$this->assertSame([1, 2, 3], $resolver());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Class_;
Expand Down Expand Up @@ -121,6 +122,12 @@ public function refactor(Node $node): ?Node
continue;
}

// referenced inside a nested closure that may run after setUp() - turning it into a local
// variable would leave it out of the closure scope, as there is no "use" binding to add it
if ($this->isPropertyUsedInNestedClosure($setUpClassMethod, $propertyName)) {
continue;
}

$hasChanged = true;

unset($node->stmts[$key]);
Expand Down Expand Up @@ -189,6 +196,35 @@ private function isPropertyUsedOutsideSetUpClassMethod(
return $isPropertyUsed;
}

private function isPropertyUsedInNestedClosure(ClassMethod $setUpClassMethod, string $propertyName): bool
{
// only regular closures are unsafe: they do not capture outer variables without an
// explicit "use" binding. Arrow functions auto-capture by value, so narrowing is safe there.
$closures = $this->nodeFinder->findInstanceOf($setUpClassMethod, Closure::class);

foreach ($closures as $closure) {
$usedPropertyFetch = $this->nodeFinder->findFirst($closure, function (Node $node) use (
$propertyName
): bool {
if (! $node instanceof PropertyFetch) {
return false;
}

if (! $this->isName($node->var, 'this')) {
return false;
}

return $this->isName($node->name, $propertyName);
});

if ($usedPropertyFetch instanceof PropertyFetch) {
return true;
}
}

return false;
}

private function shouldSkipProperty(
bool $isFinalClass,
Property $property,
Expand Down
Loading