I love functional programming languages. I really do. One of the things (among others) that is very nice about functional languages is that they are far more predisposed towards writing beautiful code (the benefits, of which, are a common enough topic). At work, I don't work with functional languages, I work with PHP. While PHP 5.3 is well on its way towards having the key features of a functional language, its roots are clearly as a simplified Perl. As such, it is a language particularly prone to having ugly code written in it. I was working on some code that I knew would be fairly ugly and, having read of some PHP pretty printers in the past, I regoogled for a bit. I eventually settled on the PHPBeautifier tool at PEAR.
It seems to work fairly well and the filter architecture looks promising. After some tinkering, the following command got (for me) fairly good results:
php_beautifier -f $1 --filters "IndentStyles(style=allman) ArrayNested NewLines(before=T_CLASS,after=T_COMMENT,before=if)"
In simple terms this specifies the following rules:
- Allman/BSD indention style
- Nest arrays
- Newlines before classes and if statements
- Newlines after comments
It certainly isn't a perfect match for my coding style (the definition of perfect, right? ;-), but it came pretty close on a pretty good test. Things I would like to tweak but couldn't get to work with the current filters (it would probably require creating a new filter or altering an existing one):
- Newlines after certain blocks. For example, I usually put a newline after the end of an if/elseif/else sequence but I couldn't find a way to make this work reliably
- Indention of HTML in a sequences of echoes. In the code I have to maintain, there are long strings of echo foo, echo bar, echo baz. Not the way I would do it (I prefer either using templates or, if that is not an option, using heredocs with echo), but I also don't want to have to rewrite it all.
- The option to indent all code between the opening and closing tags. This helps when it is interjected into a ton of HTML. I honestly don't know if I would use it all the time, but it would be nice to have.
Admittedly, this is nitpicking stuff. php_beautifier is passably documented (finding command line invocation methods in the docs is kind of a pain as it is kind of an after thought in a sea of library docs) and does an excellent example at pretty printing PHP code.