Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top