From 9664f7a9d2223c07e750f0dfc949c3accfa6b65e Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Fri, 8 Dec 2023 12:32:55 +0100 Subject: [PATCH] Bleeding edge - report unused result of ternary --- src/Rules/DeadCode/NoopRule.php | 17 +++++++++++++++++ tests/PHPStan/Rules/DeadCode/NoopRuleTest.php | 8 ++++++++ tests/PHPStan/Rules/DeadCode/data/noop.php | 6 ++++++ 3 files changed, 31 insertions(+) diff --git a/src/Rules/DeadCode/NoopRule.php b/src/Rules/DeadCode/NoopRule.php index d33e767ee3..38c8efb6b9 100644 --- a/src/Rules/DeadCode/NoopRule.php +++ b/src/Rules/DeadCode/NoopRule.php @@ -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 []; diff --git a/tests/PHPStan/Rules/DeadCode/NoopRuleTest.php b/tests/PHPStan/Rules/DeadCode/NoopRuleTest.php index 50e52a4153..d28e07dccf 100644 --- a/tests/PHPStan/Rules/DeadCode/NoopRuleTest.php +++ b/tests/PHPStan/Rules/DeadCode/NoopRuleTest.php @@ -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, + ], ]); } diff --git a/tests/PHPStan/Rules/DeadCode/data/noop.php b/tests/PHPStan/Rules/DeadCode/data/noop.php index b268cd19a8..927fe41143 100644 --- a/tests/PHPStan/Rules/DeadCode/data/noop.php +++ b/tests/PHPStan/Rules/DeadCode/data/noop.php @@ -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(); };