Skip to content

Commit 371b67d

Browse files
authored
Treat all in-scope variables as used when an unused-parameter body accesses a variable variable ($$name) (#6058)
1 parent 501ac99 commit 371b67d

4 files changed

Lines changed: 50 additions & 2 deletions

File tree

‎src/Rules/UnusedFunctionParametersCheck.php‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,21 @@ private function getUsedVariables(Scope $scope, $node): array
8282
if ($node instanceof Node\Expr\Include_ || $node instanceof Node\Expr\Eval_) {
8383
return $scope->getDefinedVariables();
8484
}
85-
if ($node instanceof Variable && is_string($node->name) && $node->name !== 'this') {
86-
return [$node->name];
85+
if ($node instanceof Variable) {
86+
if (is_string($node->name)) {
87+
if ($node->name !== 'this') {
88+
return [$node->name];
89+
}
90+
} else {
91+
$nameType = $scope->getType($node->name);
92+
if ($nameType->getConstantStrings() === []) {
93+
return $scope->getDefinedVariables();
94+
}
95+
96+
foreach ($nameType->getConstantStrings() as $constantString) {
97+
$variableNames[] = $constantString->getValue();
98+
}
99+
}
87100
}
88101
if ($node instanceof Node\ClosureUse && is_string($node->var->name)) {
89102
return [$node->var->name];

‎tests/PHPStan/Rules/Classes/data/unused-constructor-parameters-include.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,16 @@ public function __construct(
1313
}
1414

1515
}
16+
17+
class Bar
18+
{
19+
20+
public function __construct(
21+
$usedViaVariableVariable,
22+
$name
23+
)
24+
{
25+
echo $$name;
26+
}
27+
28+
}

‎tests/PHPStan/Rules/Functions/UnusedClosureUsesRuleTest.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ public function testUnusedClosureUses(): void
3232
'Anonymous function has an unused use $usedInClosureUse.',
3333
10,
3434
],
35+
[
36+
'Anonymous function has an unused use $container.',
37+
43,
38+
],
3539
]);
3640
}
3741

‎tests/PHPStan/Rules/Functions/data/unused-closure-uses.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,21 @@ function () use ($container) {
2525
function () use ($container) {
2626
eval('echo $container;');
2727
};
28+
29+
$aap = 684;
30+
31+
$a = function () use ($aap) {
32+
require __DIR__ . '/echo_the_value_of_aap.php';
33+
};
34+
35+
$name = 'container';
36+
37+
function () use ($container, $name) {
38+
echo $$name;
39+
};
40+
41+
$otherName = 'notContainer';
42+
43+
function () use ($container, $otherName) {
44+
echo $$otherName;
45+
};

0 commit comments

Comments
 (0)