3

I am looking for a command line tool that applies code formatting suggestions provided by PHP codesniffer into my code base.

There are some cool tools like PHP CodeSniffer plugin to Eclipse but in my use case I need to do this as a batch process rather than a manual task.

2 Answers2

4

While there isn't anything that will directly fix all issues reported by PHP_CodeSniffer, there is another unrelated project that tries to fix issues rather than report on them. In particular, it tries to make your code conform to the new PSR-1 and PSR-2 standards, which PHP_CodeSniffer is only just adding support for at the moment.

It's not going to fix everything, but it is probably as close as you are going to get to fixing some issues: https://github.com/fabpot/PHP-CS-Fixer

However, I strongly recommend not running batch fixing tools over your codebase. If you want your code to conform to a coding standard, you really need to learn it and just fix the errors over time. There is no reason to fix everything in one hit, and doing so with an automated tool is, in my experience, the best way to break your codebase.

Greg Sherwood
  • 6,992
  • 2
  • 29
  • 24
  • A good code formatter does not break your code. Ours does not; it uses a language-precise parser to read the code, and a language-precise prettyprinter to reformat it. You can run it as a batch on your entire code base. Safely. It doesn't listen to CodeSniffer, and it probably doesn't implement CodeSniffer's expected format. – Ira Baxter Jun 12 '12 at 22:36
  • 1
    Thanks Ira. I have no idea what your product is but you are obviously very confident in it. I was, of course, talking very generally. Assuming your tool is always updated with PHP version changes, is compatible across versions, and copes with the strange ways developers code sometimes, I'm sure it does a great job. I would still never recommend a tool for auto-formatting code because I am incredible paranoid and accept that developers make mistakes and that tools are never perfect. Even one obscure error creeping into the code is enough to cause an issue in production. – Greg Sherwood Jun 15 '12 at 08:09
  • Then why do you use PHP? The answer here is that well engineered tools are trustworthy. Your paranoia is appropriate for tools that are lashed together with bubblegum and bailing wire. For tools that are well engineered, the productivity gain exceeds the occasional glitch. (Yes, we have them too, but they are rare, and we do try to keep up). – Ira Baxter Jun 15 '12 at 10:26
  • ... you can find out about our formatter at http://www.semanticdesigns.com/Products/Formatters/PHPFormatter.html – Ira Baxter Jun 19 '12 at 06:36
2

CodeSniffer in version 2 introduced automatic error fixing. All you have to do is to upgrade your CodeSniffer to version 2 and run it with command:

phpcbf

instead of old phpcs which only list errors

More information: Fixing Errors Automatically

dardarlt
  • 1,199
  • 11
  • 12