Skip to content
Closed
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
Expand Up @@ -9,7 +9,7 @@ function wrapToPreventPhpStanCallingMethods ($object)

isset ($b);

isset($b[func1()], $c[func2()], $d[func3()], $d[func4()]);
isset($b[func1()]);
}
?>
-----
Expand All @@ -23,8 +23,5 @@ function wrapToPreventPhpStanCallingMethods ($object)
$b = isset($b, $c, $d);

func1();
func2();
func3();
func4();
}
?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Rector\Tests\DeadCode\Rector\Expression\RemoveDeadStmtRector\Fixture;

function skipMultiArgIssetSideEffect ($b, $c, $d)
{
// func2() runs only when $b[func1()] is set
isset($b[func1()], $c[func2()], $d[func3()]);
}
?>
21 changes: 21 additions & 0 deletions rules/DeadCode/Rector/Expression/RemoveDeadStmtRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use PhpParser\Comment\Doc;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Cast\Void_;
use PhpParser\Node\Expr\Isset_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Nop;
use PhpParser\NodeVisitor;
Expand Down Expand Up @@ -70,6 +72,10 @@ public function refactor(Node $node): array|Node|null|int
return null;
}

if ($this->isShortCircuitIssetWithSideEffect($node)) {
return null;
}

$livingCode = $this->livingCodeManipulator->keepLivingCodeFromExpr($node->expr);
if ($livingCode === []) {
return $this->removeNodeAndKeepComments($node);
Expand Down Expand Up @@ -106,6 +112,21 @@ private function hasGetMagic(Expression $expression): bool
return ! $phpPropertyReflection instanceof PhpPropertyReflection;
}

/**
* isset() with more args stops on first unset one, so side effects in later args are conditional
*/
private function isShortCircuitIssetWithSideEffect(Expression $expression): bool
{
if (! $expression->expr instanceof Isset_) {
return false;
}

$vars = $expression->expr->vars;
array_shift($vars);

return array_any($vars, fn (Expr $var): bool => $this->livingCodeManipulator->keepLivingCodeFromExpr($var) !== []);
}

private function isVoidCastNoDiscardCall(Expression $expression): bool
{
if (! $expression->expr instanceof Void_) {
Expand Down
Loading