Skip to content

Commit

Permalink
Closure with by-ref parameter is impure
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jul 19, 2024
1 parent fc75deb commit f1abacd
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -1527,6 +1527,20 @@ static function (Node $node, Scope $scope) use ($arrowScope, &$arrowFunctionImpu
}
}

foreach ($parameters as $parameter) {
if ($parameter->passedByReference()->no()) {
continue;
}

$impurePoints[] = new ImpurePoint(
$this,
$node,
'functionCall',
'call to a Closure with by-ref parameter',
true,
);
}

$throwPointsForClosureType = array_map(static fn (ThrowPoint $throwPoint) => $throwPoint->isExplicit() ? SimpleThrowPoint::createExplicit($throwPoint->getType(), $throwPoint->canContainAnyThrowable()) : SimpleThrowPoint::createImplicit(), $throwPoints);
$impurePointsForClosureType = array_map(static fn (ImpurePoint $impurePoint) => new SimpleImpurePoint($impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain()), $impurePoints);

Expand Down
5 changes: 5 additions & 0 deletions tests/PHPStan/Rules/DeadCode/BetterNoopRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,9 @@ public function testBug11001(): void
$this->analyse([__DIR__ . '/data/bug-11001.php'], []);
}

public function testBug11361(): void
{
$this->analyse([__DIR__ . '/data/bug-11361.php'], []);
}

}
12 changes: 12 additions & 0 deletions tests/PHPStan/Rules/DeadCode/data/bug-11361.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Bug11361;

function foo(): void
{
$bar = function(&$var) {
$var++;
};
$a = array(0);
$bar($a[0]);
}
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/Pure/PureFunctionRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,14 @@ public function testFirstClassCallable(): void
]);
}

public function testBug11361(): void
{
$this->analyse([__DIR__ . '/data/bug-11361-pure.php'], [
[
'Impure call to a Closure with by-ref parameter in pure function Bug11361Pure\foo().',
14,
],
]);
}

}
17 changes: 17 additions & 0 deletions tests/PHPStan/Rules/Pure/data/bug-11361-pure.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Bug11361Pure;

/**
* @phpstan-pure
*/
function foo(): int
{
$bar = function(&$var) {
$var++;
};
$a = array(0);
$bar($a[0]);

return 1;
}

0 comments on commit f1abacd

Please sign in to comment.