Skip to content

Commit

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

if ($expr instanceof Node\Expr\Ternary) {
$if = $expr->if;
if ($if === null) {
$if = $expr->cond;
}

if (!$this->isNoopExpr($if) || !$this->isNoopExpr($expr->else)) {
return [];
}

return [
RuleErrorBuilder::message('Unused result of ternary operator.')
->line($expr->getLine())
->build(),
];
}
}
if (!$this->isNoopExpr($expr)) {
return [];
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 @@ -92,6 +92,14 @@ public function testRule(): void
38,
'This operator has unexpected precedence, try disambiguating the logic with parentheses ().',
],
[
'Unused result of ternary operator.',
40,
],
[
'Unused result of ternary operator.',
41,
],
]);
}

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 @@ -36,4 +36,10 @@ function (stdClass $foo, bool $a, bool $b) {

$s = $a or doFoo();
$t = $a or $b;

$a ? $b : $s;
$a ?: $b;
$a ? doFoo() : $s;
$a ? $b : doFoo();
$a ? doFoo() : doBar();
};

0 comments on commit 9664f7a

Please sign in to comment.