nikic / PHP-Parser

A PHP parser written in PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`elseif` vs `else if` node structure

pmjones opened this issue · comments

This came up in pmjones/php-styler#4 earlier today. PHP-Styler rebuilds this original code using else if:

if ($foo) {
    $foo = 'bar';
} else if ($bar) {
    $foo = 'baz';
}

...to this:

if ($foo) {
    $foo = 'bar';
} else {
    if ($bar) {
        $foo = 'baz';
    }
}

This is because PHP-Parser sees a second If_ as part of the Else_, rather than an Elseif_ that is part of the If_.

How difficult would it be for PHP-Parser to recognize else if as elseif in these conditions? (My guess is that it would involve substantial effort.)

It's not difficult, but then I'll get complaints that the distinction between elseif and else if gets lost ;)

You should be able to easily print these without the extra nesting, like this:

if (\count($node->stmts) === 1 && $node->stmts[0] instanceof Stmt\If_) {
// Print as "else if" rather than "else { if }"
return 'else ' . $this->p($node->stmts[0]);
}

but then I'll get complaints

Man, I hear you. :-)

You should be able to easily print these

Excellent, I will try that -- thanks!

Thanks @nikic that did the trick.