Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically reformatting inherited PHP spaghetti code

I've taken over a mixed PHP4/PHP5 project which has been handed down from developer to developer, with each one making things worse. Before I spend too much time on it I'd like to develop a base-standard, with consistent formatting at a minimum.

Can anyone recommend a utility (Linux or Mac OS X preferably) that will reformat the code?

If I can set parameters which influence output (like tab-indentation, brace/bracket placement, when to split array values onto new lines etc.) then that's a benefit, though not crucial.

Preference goes to Open Source tools, though I'd like to know your experiences with purchased software too.

like image 569
mlambie Avatar asked Dec 15 '08 01:12

mlambie


4 Answers

I use phptidy: http://cmr.cx/phptidy/ https://github.com/cmrcx/phptidy

By design, it's not as aggressive as perltidy, but it's still very useful. It can be configured and will do all the php files in your project as a batch.

Update: for a more aggressive, standards-based tool, consider PHP CS Fixer: https://github.com/FriendsOfPhp/PHP-CS-Fixer

like image 45
oddnoc Avatar answered Nov 08 '22 16:11

oddnoc


You can do that with Netbeans or with Eclipse PDT, both excellent PHP editors. There's a Format Code option in each, which will reformat a selected file according to your code style preferences. There may be an option to format code in bulk as well.

I do recommend that if you do this, do the format and immediately check the code back in with a big fat "REFORMATTING!" comment. Trying to mix in other bug fixes with the reformat makes for nasty-looking diff files to try to decipher down the road.

like image 105
jodonnell Avatar answered Nov 08 '22 17:11

jodonnell


I've used http://www.phpformatter.com/, which is an online tool.

like image 2
Daniel Serodio Avatar answered Nov 08 '22 16:11

Daniel Serodio


Something I found recently, which I now love and use all the time. In vim:

gg=G

This requires the following configuration option, which you can set in your ~/.vimrc:

filetype plugin indent on
like image 1
mlambie Avatar answered Nov 08 '22 15:11

mlambie