A tool to reformat your php code and make it more readable
After searching for a php code formatter, I failed finding any good tool that will not break my code.
I wanted a tool that reformats php code to match my coding guidelines, so I coded my own solution.
So, here it is. A php code reformat tool that just works, at least on the code I tested. I'm releasing the code under the GPL license and everyone is invited to submit code on which this tool fails so I can improve it and make it better.
Test the Php code beautifier
The code is implemented as a class, a php file beautify.php is provided, so you can use it as a command line tool.
php beautify.php /myproject/sourcecode/ /myproject/beautifiedcode/
Or you can implement the class and use it however you want
include 'PhpBeautifier.inc'; $beautify = new PhpBeautifier(); $beautify -> tokenSpace = true;//put space between tokens $beautify -> blockLine = true;//put empty lines between blocks of code (if, while etc) $beautify -> optimize = true;//optimize strings (for now), if a double quoted string does not contain variables of special characters transform it to a single quoted string to save parsing time $beautify -> file( 'test.php', 'beautified.php' );
The beautifier strips all lines and leading spaces from your source code and then adds spaces and new lines only where is needed. You can modify the beautifier class code to suit your taste.
I will try to make everything optional. For now, you can specify only if you want to put space between tokens ( parenthesis ) or empty lines between code blocks ( loop structures, if structures etc).
You can even choose to optimize your code by putting double quotes to strings only where necessary. Every double quoted string that does not contain a variable or special character will be transformed to a single quoted string.
For the next version I plan to make a indenter, or maybe a reformatter for html insides php code. For now, inline html remains untouched.
I also intend to reformat multidimensional arrays so they can be easier to read. For now, they are put on single line :(.
You can download the class, the command line tool and the example from here