Skip to content

Commit 2ba4c44

Browse files
authored
[Php70] Handle return ternary on IfIssetToCoalescingRector (#7683)
* [Php70] Handle return ternary on IfIssetToCoalescingRector * fix
1 parent d7770c8 commit 2ba4c44

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
namespace Rector\Tests\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector\Fixture;
4+
5+
class WithTernaryReturn
6+
{
7+
private $values = [];
8+
private $nullable = false;
9+
10+
public function resolve($param)
11+
{
12+
if (isset($this->values[$param])) {
13+
return $this->values[$param];
14+
}
15+
16+
return $this->nullable ? null : false;
17+
}
18+
}
19+
20+
?>
21+
-----
22+
<?php
23+
24+
namespace Rector\Tests\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector\Fixture;
25+
26+
class WithTernaryReturn
27+
{
28+
private $values = [];
29+
private $nullable = false;
30+
31+
public function resolve($param)
32+
{
33+
return $this->values[$param] ?? ($this->nullable ? null : false);
34+
}
35+
}
36+
37+
?>

rules/Php70/Rector/StmtsAwareInterface/IfIssetToCoalescingRector.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@
88
use PhpParser\Node\Expr;
99
use PhpParser\Node\Expr\BinaryOp\Coalesce;
1010
use PhpParser\Node\Expr\Isset_;
11+
use PhpParser\Node\Expr\Ternary;
1112
use PhpParser\Node\Stmt;
1213
use PhpParser\Node\Stmt\Else_;
1314
use PhpParser\Node\Stmt\If_;
1415
use PhpParser\Node\Stmt\Return_;
16+
use Rector\NodeTypeResolver\Node\AttributeKey;
1517
use Rector\PhpParser\Enum\NodeGroup;
1618
use Rector\Rector\AbstractRector;
1719
use Rector\ValueObject\PhpVersionFeature;
@@ -113,6 +115,10 @@ public function refactor(Node $node): ?Node
113115

114116
unset($node->stmts[$key - 1]);
115117

118+
if ($stmt->expr instanceof Ternary) {
119+
$stmt->expr->setAttribute(AttributeKey::WRAPPED_IN_PARENTHESES, true);
120+
}
121+
116122
$stmt->expr = new Coalesce($ifOnlyStmt->expr, $stmt->expr);
117123
return $node;
118124
}

0 commit comments

Comments
 (0)