Skip to content

[CodeQuality] Skip alternative syntax (if/endif) in ShortenElseIfRector#8157

Merged
TomasVotruba merged 1 commit into
mainfrom
fix-shorten-elseif-alternative-syntax
Jul 8, 2026
Merged

[CodeQuality] Skip alternative syntax (if/endif) in ShortenElseIfRector#8157
TomasVotruba merged 1 commit into
mainfrom
fix-shorten-elseif-alternative-syntax

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Fixes rectorphp/rector#9803

ShortenElseIfRector produced invalid PHP when a file used the alternative control syntax (if: / else: / endif). It merged else { if } into elseif regardless of syntax style: the freshly created ElseIf_ node prints braces while the surrounding unchanged nodes keep their colons, yielding mixed brace/colon output that fails to parse (and drops the trailing endif).

Before (broken output)

if ($n == $c) {
    $a = 1;
} elseif ($x || $n <= $e) {
    $a = 2;
} elseif ($d && ! $x) :
    $a = 3;

PHP Parse error: syntax error, unexpected token :

After

Files using alternative syntax are skipped, both when the outer if uses it and when only the nested if does. Normal brace syntax is unchanged:

 if ($cond1) {
     return $action1;
-} else {
-    if ($cond2) {
-        return $action2;
-    }
+} elseif ($cond2) {
+    return $action2;
 }

Detection reuses the same getOldTokens() token-scan approach as the sibling CompleteMissingIfElseBracketRector: scan tokens after the condition and skip if : appears before {.

Two skip_* fixtures added (full alternative syntax + brace-outer/alt-inner).

@TomasVotruba TomasVotruba merged commit 6db3213 into main Jul 8, 2026
65 checks passed
@TomasVotruba TomasVotruba deleted the fix-shorten-elseif-alternative-syntax branch July 8, 2026 16:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

ShortenElseIfRector still breaks pure-PHP alternative syntax: emits mixed } elseif (...) : and invalid PHP

1 participant