Skip to content

Commit 2ed3aa8

Browse files
Don't require parentheses for short-ternaries (#7604)
Chaining of short-ternaries (`?:` also called elvis operator) is stable and behaves reasonably This is described in the PHP Manual right below the warning about using nested ternary expressions. The example code is taken from the PHP Manual. https://www.php.net/manual/en/language.operators.comparison.php#:~:text=Chaining%20of%20short%2Dternaries%20(%3F%3A)%2C%20however%2C%20is%20stable%20and%20behaves%20reasonably
1 parent 8376d26 commit 2ed3aa8

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
function elvisDoesNotNeedParentheses()
4+
{
5+
echo 0 ?: 1 ?: 2 ?: 3, PHP_EOL; //1
6+
echo 0 ?: 0 ?: 2 ?: 3, PHP_EOL; //2
7+
echo 0 ?: 0 ?: 0 ?: 3, PHP_EOL; //3
8+
}

rules/Php74/Rector/Ternary/ParenthesizeNestedTernaryRector.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,12 @@ public function getNodeTypes(): array
6161
public function refactor(Node $node): ?Node
6262
{
6363
if ($node->cond instanceof Ternary || $node->else instanceof Ternary) {
64+
// Chaining of short-ternaries (elvis operator) is stable and behaves reasonably
65+
$isElvis = $node->cond instanceof Ternary && $node->cond->if === null;
66+
if ($isElvis) {
67+
return null;
68+
}
69+
6470
if ($this->parenthesizedNestedTernaryAnalyzer->isParenthesized($this->file, $node)) {
6571
return null;
6672
}

0 commit comments

Comments
 (0)