Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\If_\ShortenElseIfRector\Fixture;

function skipAlternativeSyntax($n, $c, $x, $e, $d)
{
if ($n == $c) :
$a = 1;
else :
if ($x || $n <= $e) :
$a = 2;
elseif ($d && ! $x) :
$a = 3;
endif;
endif;

return $a;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\If_\ShortenElseIfRector\Fixture;

function skipInnerAlternativeSyntax($cond1, $cond2)
{
if ($cond1) {
$a = 1;
} else {
if ($cond2) :
$a = 2;
endif;
}

return $a;
}
34 changes: 34 additions & 0 deletions rules/CodeQuality/Rector/If_/ShortenElseIfRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PhpParser\Node\Stmt\ElseIf_;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Nop;
use PhpParser\Token;
use Rector\Contract\Rector\HTMLAverseRectorInterface;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Rector\AbstractRector;
Expand Down Expand Up @@ -89,6 +90,11 @@ private function shortenElseIf(If_ $node): ?If_
return null;
}

// alternative syntax (if/else/endif) cannot be merged to elseif without producing mixed brace/colon syntax
if ($this->isAlternativeSyntax($node) || $this->isAlternativeSyntax($if)) {
return null;
}

// Try to shorten the nested if before transforming it to elseif
$refactored = $this->shortenElseIf($if);

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

return $node;
}

private function isAlternativeSyntax(If_ $if): bool
{
$startTokenPos = $if->cond->getEndTokenPos();
if ($startTokenPos < 0) {
return false;
}

$oldTokens = $this->getFile()
->getOldTokens();

for ($i = $startTokenPos + 1; isset($oldTokens[$i]); ++$i) {
$token = $oldTokens[$i];
if (! $token instanceof Token) {
continue;
}

if ($token->text === ':') {
return true;
}

if ($token->text === '{') {
return false;
}
}

return false;
}
}
Loading