Introducing PHP-Styler
PHP-Styler is a companion to PHP-Parser for reconstructing PHP code after it has been deconstructed into an abstract syntax tree. As an alternative to the pretty-printer bundled with PHP-Parser, it supports:
- configurable line-length, line-ending, and indent-string
- automatic indenting and line breaks
- automatic splitting of "too-long" lines
- programmable/customizable styling
PHP-Styler is not a coding style "fixer" per se. Instead, it will completely rebuild PHP code from the AST, applying its style rules along the way. The result is a consistent formatting style, regardless of the original formatting.
Whereas something like PHP-CS-Fixer has scores of configuration parameters, PHP-Styler gives you imperative control over its output. Extend the default Styler implementation with your own overrides to change where braces go, to place or remove the space after !
conditions, whether or not if/elseif/else should be on separate lines, and so on.
I'm especially happy with the line-splitting logic. PHP-Styler begins by building one statement per line, but if the line is too long, it follows an incremental set of rules to split that line into shorter readable parts.
There are still some outstanding formatting issues around closures and comments, but I have smoke-tested PHP-Styler against several codebases besides my own, and I found the results surprisingly acceptable (not perfect, but unexpectedly good). It's certainly good enough for my own projects, though it did reveal some of my own preferences that I was not aware of, as well as some inconsistencies in my own style choices.
If you are using PHP-Parser and want a better pretty-printer, or if you have been looking for an alternative to PHP-CS-Fixer, give PHP-Styler a try!