Skip to content

Commit

Permalink
Bleeding edge - report unused results of "&&" and "||"
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Dec 8, 2023
1 parent 9664f7a commit cf2c8bb
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Rules/DeadCode/NoopRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ public function processNode(Node $node, Scope $scope): array
];
}

if ($expr instanceof Node\Expr\BinaryOp\BooleanAnd || $expr instanceof Node\Expr\BinaryOp\BooleanOr) {
if (!$this->isNoopExpr($expr->right)) {
return [];
}

return [
RuleErrorBuilder::message(sprintf(
'Unused result of "%s" operator.',
$expr->getOperatorSigil(),
))->line($expr->getLine())
->build(),
];
}

if ($expr instanceof Node\Expr\Ternary) {
$if = $expr->if;
if ($if === null) {
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/DeadCode/NoopRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ public function testRule(): void
'Unused result of ternary operator.',
41,
],
[
'Unused result of "||" operator.',
46,
],
[
'Unused result of "&&" operator.',
49,
],
]);
}

Expand Down
6 changes: 6 additions & 0 deletions tests/PHPStan/Rules/DeadCode/data/noop.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,10 @@ function (stdClass $foo, bool $a, bool $b) {
$a ? doFoo() : $s;
$a ? $b : doFoo();
$a ? doFoo() : doBar();

$a || $b;
$a || doFoo();

This comment has been minimized.

Copy link
@staabm

staabm Dec 8, 2023

Contributor

if the function is pure, it could also error


$a && $b;
$a && doFoo();
};

0 comments on commit cf2c8bb

Please sign in to comment.