Sunday, June 08, 2008

How to customise PHP_CodeSniffer (writing custom coding standards)

PHP_CodeSniffer is a PEAR package which detects potential coding problems and enforces your style guide.

The default is the PEAR coding standard, but you can easily change that.

pear install PHP_CodeSniffer
pear install PEAR_PackageFileManager_Cli

Second, create a new folder somewhere -

Third, you'll want to make a
in that directory.

It should look somewhat like:

if (class_exists('PHP_CodeSniffer_Standards_CodingStandard', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_Standards_CodingStandard not found');

class PHP_CodeSniffer_Standards_Foo_FooCodingStandard extends PHP_CodeSniffer_Standards_CodingStandard

public function getIncludedSniffs()
return array(

}//end getIncludedSniffs()

}//end class

Spend a little time searching for the sniffs you want to use - some can be a huge help, or a huge pain.

Next, use the CLI tool
to create a package.xml in
. You want to set the base install directory to PHP/; and you want to watch out for case senstivity and the like.

Once you have your package.xml; you just want to type
pear package
in the same directory - if it works, you should have a new .tgz with you can install -
pear install PHP_CodeSniffer_Standards_Foo-0.0.1.tgz

Testing it:
phpcs -i
should show your new coding standard listed here if everything is working correctly.

To set it to your default coding standard:
phpcs --config-set default_standard Foo

What next?
You could set it up to run via Cron across your entire project, or you could integrate it with an SVN post commit hook.


Anonymous said...

Nice tip, thank you. We've been playing around with creating our own standard for internal projects, I'd been wondering about a nice way to package it.

However, we run phpcs via phpUnderControl ( Much nicer than using cron.

Anonymous said...

How about how to do HTML output like PEAR does?

Dan said...

If you use the --report=xml argument you can get a nice summary.

You can then use simplexml or xslt to transform that output into something human friendly.

Personally, I'm holding out for logging into a database; so I can do all sorts of neat tricks with it.

DanaLapid said...

Great tips! I just started playing around with PHP a few days ago, and was looking online for solutions for problems I've encountered.. I'm still looking for a good php code generator, so if anyone can advice me - I'm here!