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:
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!
if (condition)
{
while (condition)
{
foreach (x in y)
{
statement;
statement;
}
}
statement;
}
elseif (condition)
{
return value;
}
else
{
die;
}
PHP: Add optional curly braces to control structures in existing code
305 Views Asked by Philipp Naumann At
3
There are 3 best solutions below
0

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!
0

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
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.