Simple Is Good!

How To Web Dev

PHP Code Sniffer and Git Pre Hook

In an effort to create higher quality more consistent code I have really wanted to implement PHP Code Sniffer to make sure that I stick to a good coding standard.  If you are not familiar with it I am going to try and write about how to get code sniffer up and running on your system.  Because I am implementing this on projects that have been around a while, I don’t want to worry about updating my entire code base all at once because that is just tedious.  Also I didn’t want to add an extra step in my coding process because well, that takes time and if it isn’t integrated well then I probably wont do it.  Since I use GIT to store revision information for most of my projects it made sense to have Code Sniffer run every time I wanted to commit code.  How you ask, well easier then I thought using Pre-Commits in Git.  So go ahead and browse over to your git checkout, then go to .git/hooks/pre-commit this will open up a file that will run before every commit.  So here is the code you should drop in.

$output = array();
$return = 0;
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $return);
// Get GIT revision
$against = $return == 0 ? 'HEAD' : '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
// Get the list of files in this commit.
exec("git diff-index --cached --name-only {$against}", $output);
$filename_pattern = '/\.php$/';
$exit_status = 0;
// Loop through files.
foreach ($output as $file) {
    if ( ! preg_match($filename_pattern, $file)) {
        // don't check files that aren't PHP
    // If file is removed from git do not sniff. 
    if ( ! file_exists($file))
    $lint_output = array();
    // Run the sniff
    exec("phpcs --standard=Kohana " . escapeshellarg($file), $lint_output, $return);
    if ($return == 0) {
    echo implode("\n", $lint_output), "\n";
    $exit_status = 1;