I used to omit curly braces in PHP whenever they were not necessary, which - with increasing complexity my programs' control flows - has lead to code that is hard to comprehend and impossible to maintain:

    if (condition) {
        while (condition)
            foreach (x in y) {
               statement;
               statement;
            }
        statement;
    } elseif (condition)
        return value;
    else
        die;
My aim is to automatically turn that blob into this:
    if (condition)
    {
        while (condition)
        {
            foreach (x in y)
            {
               statement;
               statement;
            }
        }
        statement;
    }
    elseif (condition)
    {
        return value;
    }
    else
    {
        die;
    }
I know there are many discussions here on whether to add optional braces or not, but I could not find an answer to the question how to conveniently add them to existing PHP code. Thanks in advance!

有帮助吗?

解决方案

You can use token_get_all to build an AST, loop over the tokens, and add the braces in. From that you should be able to save back out the amended source file.

There's also the, excellent, PHP_Parser library too.

其他提示

I came up with a simple NetBeans editor macro that does the job reliably, though only semi-automatically:

caret-end-line " {" caret-down caret-end-line insert-break "}"

Thanks for your input!

You can use Fabien Potencier's PHP-CS-Fixer and then only use the "braces" fixer, for example as in

php-cs-fixer fix <directory> --fixers braces

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top