Categories

Related tags

Source Code Analysis: Code Sniffer

22 May 2010

Choice problem

In the previous article we examined the only way of code analysis – PHP tokinizer. But digging deeper you’ll find many of options. Well-known expert of the subject Sebasitan Bergmann points out following

As far as you see, with such a set of tools you can do whatever you want. But here we are going to discuss the only application, which is known as code sniffing.

Code Sniffer

Ok, you have some team, working on the projects and, obviously, you have some code convention to adhere. The lead, making code review, checks the compliance with standards by sight. Common, tell me you are not fond of it. There is an amazing tool but again by Sebastian Bergmann so-called PHP CodeSniffer. Ideally you just select from provides standards and particular sniffs what you need, point them into new created standard folder (/Standards/YourCompany/YourCompanyCodingStandard.php) ad now you can check the source code automatically. When using the command line it can look like that:

You’ll find in the report.txt what is wrong with you code. Going further, you can bind the instruction to the application builder script. So when you are deploying project test version / production version from developers SVN, all the committed code is checked by the code sniffer. The report will likely appear in CI-tool if you use any. For example, phpUnderControl has precise section CodeSniffer where the report can be bound to.

But trying PHP CodeSniffer you find the need to modify some of provided sniffs or write new ones. Here is the tutorial from PHP CodeSniffer, but it’s much useful just to study how the provided sniffs are written.

Well, let’s see on an example, what I mean. First, you are creating your standard folder and put there configuration file. That is about all the provided sniffs you want to apply:

<?php
class PHP_CodeSniffer_Standards_YourCompany_YourCompanyCodingStandard extends PHP_CodeSniffer_Standards_CodingStandard
{
public function getIncludedSniffs()
{
return array(
// Checks that the opening brace of a function is on the line after the
// function declaration.
// function fooFunction($arg1, $arg2 = '') [\n] {
'Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php',
// Makes sure that shorthand PHP open tags are not used.
// Always use <%php %> to delimit PHP code, not the <% %> shorthand
'Generic/Sniffs/PHP/DisallowShortOpenTagSniff.php',
// Throws errors if tabs are used for indentation.
'Generic/Sniffs/WhiteSpace/DisallowTabIndentSniff.php',
// JS control for not use of firebug.console
'MySource/Sniffs/Debug/FirebugConsoleSniff.php',
// Checks the declaration of the class is correct.
'PEAR/Sniffs/Classes/ClassDeclarationSniff.php',
// A Sniff to ensure that parameters defined for a function that have a default
// value come at the end of the function signature.
'PEAR/Sniffs/Functions/ValidDefaultValueSniff.php',
// Checks that the closing braces of scopes are aligned correctly.
'PEAR/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php',
// Tests for functions outside of classes.
'Squiz/Sniffs/Functions/GlobalFunctionSniff.php',
// Runs the Zend Code Analyzer (from Zend Studio) on the file.
'Zend/Sniffs/Debug/CodeAnalyzerSniff.php',
// Checks that the file does not end with a closing tag.
'Zend/Sniffs/Files/ClosingTagSniff.php',
// Checks the naming of variables and member variables.
'Zend/Sniffs/NamingConventions/ValidVariableNameSniff.php',
);
}
}

Then you create Sniffs folder and fill it with your own sniffs or modificated sniffs of the package. For example, you follow Zend Framework coding standard and you need a sniff to check that the only class declared per file and class name corresponds the naming convention (the path to the file is reflected in its name). So we find a sniff of this sort among the provided ones (ClassDeclarationSniff.php or Squiz or of PEAR standard) . We study how it’s made and write our own sniff:

The index for encountered token (the list of what the tokens we are looking for is specified in the array of sniff class registered() method) is passed in as $stackPtr argument. So you can navigate on the FILE iterator like $phpcsFile->findNext(..) or $phpcsFile->findPrevious(..). Matching found token info with conditional values we can generate error $phpcsFile->addError or warning $phpcsFile->addWarning when it’s required.

What the custom sniffs I would need?

From my experience you are going to need to sniff whitespaces in control structures. So the expected code is like that:

if (..) {.. } // valid
if(..) { ..} // invalid

Another sniff you may need is a modification of MultiLineConditionSniff.php to check multiline condition against EOL between closing parenthesis and opening brace:

It’s a controversial point, because by Zend Framework standard conditional structures have EOLs before the opening parenthesis. Though in the case of multiline condition it will be indistinct where is the begin and the end for the structure.

I’m sure you have some custom template for PHPDOC headers, so take a look on FileCommentSniff.php to customize it.

You will find in all the implementations of LineLengthSniff.php the limit is set to 80/85 columns. For God sake, it’s not MS-DOS epoch anymore, let’s extend it till 100 at least.

I have a function syntax sniffs to propose. Function argument list can be multiline and in the case of, our standard for instance, comma can be on a new line. So space is still prohibited before the comma, but EOL is permitted:

Well, that’s all from my side, and that is only an example. The set of sniffs will depend of what the requirements you have according to your own coding standards.

In the previous article we examined the only way of code analysis – PHP tokinizer. But digging deeper you’ll find many of options. Well-known expert of the subject Sebasitan Bergmann points out following.

As far as you see, with such a set of tools you can do whatever you want. But here we are going to discuss the only application, which is known as code sniffing.

Ok, you have some team, working on the projects and, obviously, you have some code convention to adhere. The lead, making code review, checks the compliance with standards by sight. Common, tell me you are not fond of it. There is an amazing tool but again by Sebastian Bergmann so-called PHP CodeSniffer.

Who's the dude?

Dmitry Sheiko is a web-developer living and working in Frankfurt am Main, DE