Skip to content

Commit 6db3213

Browse files
authored
[CodeQuality] Skip alternative syntax (if/endif) in ShortenElseIfRector (#8157)
1 parent 46515d2 commit 6db3213

3 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\If_\ShortenElseIfRector\Fixture;
4+
5+
function skipAlternativeSyntax($n, $c, $x, $e, $d)
6+
{
7+
if ($n == $c) :
8+
$a = 1;
9+
else :
10+
if ($x || $n <= $e) :
11+
$a = 2;
12+
elseif ($d && ! $x) :
13+
$a = 3;
14+
endif;
15+
endif;
16+
17+
return $a;
18+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\If_\ShortenElseIfRector\Fixture;
4+
5+
function skipInnerAlternativeSyntax($cond1, $cond2)
6+
{
7+
if ($cond1) {
8+
$a = 1;
9+
} else {
10+
if ($cond2) :
11+
$a = 2;
12+
endif;
13+
}
14+
15+
return $a;
16+
}

‎rules/CodeQuality/Rector/If_/ShortenElseIfRector.php‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PhpParser\Node\Stmt\ElseIf_;
1010
use PhpParser\Node\Stmt\If_;
1111
use PhpParser\Node\Stmt\Nop;
12+
use PhpParser\Token;
1213
use Rector\Contract\Rector\HTMLAverseRectorInterface;
1314
use Rector\NodeTypeResolver\Node\AttributeKey;
1415
use Rector\Rector\AbstractRector;
@@ -89,6 +90,11 @@ private function shortenElseIf(If_ $node): ?If_
8990
return null;
9091
}
9192

93+
// alternative syntax (if/else/endif) cannot be merged to elseif without producing mixed brace/colon syntax
94+
if ($this->isAlternativeSyntax($node) || $this->isAlternativeSyntax($if)) {
95+
return null;
96+
}
97+
9298
// Try to shorten the nested if before transforming it to elseif
9399
$refactored = $this->shortenElseIf($if);
94100

@@ -114,4 +120,32 @@ private function shortenElseIf(If_ $node): ?If_
114120

115121
return $node;
116122
}
123+
124+
private function isAlternativeSyntax(If_ $if): bool
125+
{
126+
$startTokenPos = $if->cond->getEndTokenPos();
127+
if ($startTokenPos < 0) {
128+
return false;
129+
}
130+
131+
$oldTokens = $this->getFile()
132+
->getOldTokens();
133+
134+
for ($i = $startTokenPos + 1; isset($oldTokens[$i]); ++$i) {
135+
$token = $oldTokens[$i];
136+
if (! $token instanceof Token) {
137+
continue;
138+
}
139+
140+
if ($token->text === ':') {
141+
return true;
142+
}
143+
144+
if ($token->text === '{') {
145+
return false;
146+
}
147+
}
148+
149+
return false;
150+
}
117151
}

0 commit comments

Comments
 (0)