By: Eric Van Johnson (@shocm)

PHP Lint has got your back

Hopefully, you have one of those friends who has your back, who will step in and stop you from making a really, really stupid mistake. Because we all are fallible and whether it be in a moment of rage, or just because we are in a rush, we will make mistakes.

This is why I have PHP Lint added as a pre-commit hook on my PHP Project repos. It only takes a minute to set it up and will have you a ton of time, and headache in the future.

First, you need to make sure you have PHP Lint installed on your system. If you are a PHP developer, then the chances are you have it.

Next go to you PHP project .git directory and add the following code to the file .git/hooks/pre-commit

#!/usr/local/bin/php
<?php
# PHP LINTING
$output = array();
$return = 0;
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $return);
$against = $return == 0 ? 'HEAD' : '4b825dc642cb6eb9a060e54bf8d69288fbee4904';

exec("git diff-index --diff-filter=ACMRTUXB --cached --name-only {$against}", $output);

$filename_pattern = '/\.php$/';
$exit_status = 0;

foreach ($output as $file) {
    if (!preg_match($filename_pattern, $file)) {
        // don't check files that aren't PHP
        continue;
    }

    $lint_output = array();
    exec("php -l " . escapeshellarg($file), $lint_output, $return);
    if ($return == 0) {
        continue;
    }
    echo implode("\n", $lint_output), "\n";
    $exit_status = 1;
}

exit($exit_status);

And that should be it. Now every time you do a commit on some PHP code, your git workflow will send each file through the PHP Linter to check for errors. See the example below

Most editors will show you when you make an error, but we are rushing and don't notice that we forgot to add a semi-colon.

We add the file and attempt to do a commit but because of the hook, Git will refuse to commit the files, and we can sleep easier at night knowing we can't accidentally send broken code to our repo.

One thing to note, this git hook will only parse the files you are committing and not the entire project. Meaning if you have a co-working was not doing linting, and you pull in their changes but don't touch the file, your commit will not catch it.

php coding