Thursday, July 14, 2011

Quality Assurance on PHP projects - PHPLint






PHP Lint
PHP Lint is probably the easiest way to validate your code on syntax errors, but it's also the most overlooked feature of PHP on command line.

Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in is written to standard output and the shell return code is 0. On failure, the text Errors parsing in addition to the internal parser error message is written to standard output and the shell return code is set to -1.

This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.

Example of detecting failures only
user@machine: $ /usr/bin/php -l /path/to/myfile.php

Example of detecting failures and fatal errors
user@machine: $ /usr/bin/php -lf /path/to/myfile.php

Since this tool also returns numeric return codes, you can use it immediately as a pre-commit hook of your favorite revision control system like Git or Subversion. And with PHP on command line, you can create your own hooks with PHP. 

Example of a Git pre-commit hook taken from Travis Swicegood's article "Don't submit that error" on the PHP Advent pages.
#!/usr/bin/php




// author: Travis Swicegood


$output = array();
$return = 0;
$php = '/usr/bin/php';

exec('git rev-parse --verify HEAD 2> /dev/null', $output, $return);
$against = $return == 0 ? 'HEAD' : '4b825dc642cb6eb9a060e54bf8d69288fbee4904';

exec("git diff-index --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} -lf " . escapeshellarg($file), $lint_output, $return);
    if ($return == 0) {
        continue;
    }
    echo implode("\n", $lint_output), "\n";
    $exit_status = 1;
}

exit($exit_status);

Example of a SVN pre-commit hook I use myself
#!/usr/bin/php




/**
 * Script that processes your code before it's committed to a Subversion
 * repository.
 */

/**
 * @var string Contains the path to the repository
 */
$repo = $argv[1];

/**
 * @var string Contains the ID of the transaction
 */
$transaction = $argv[2];

// Define the command line tools here
define('PHP', '/usr/bin/php');
define('SVNLOOK', '/usr/bin/svnlook');
define('GREP', '/usr/bin/grep');
define('AWK', '/usr/bin/awk');

/**
 * Checks for commit messages and sees if they are present. More fine
 * grained validation of commit messages can be provided here. If a
 * correct message was given, the function returns false. In all other
 * cases it will return an error message.
 *
 * @param string $transaction The ID of the transaction
 * @param string $repo The path to the repository
 * @return bool|string
 */
function checkCommitMessage($transaction, $repo)
{
    $message = false;
    $log = SVNLOOK . " log -t {$transaction} {$repo}";
    $commitMessage = null;
    exec($log, $commitMessage);
    if ('' === (string) $commitMessage[0]) {
        $message = 'Required commit message is missing' . PHP_EOL;
    }
    return $message;
}

/**
 * Checks the syntax of PHP Code with PHP Lint. If no errors where
 * detected, it will return false. In all other cases, it will
 * return the error messages
 *
 * @param string $transaction The ID of the transaction
 * @param string $repo The path to the repository
 * @return bool|string
 */
function checkSyntax($transaction, $repo)
{
    $messages = array ();
    $result = null;
    $return = false;
    $changed = SVNLOOK . " changed -t {$transaction} {$repo}|"
             . GREP . " \"^[UA]\"|"
             . GREP . " \"\\.php\$\"|"
             . AWK . " '{print \$2}'";
    exec ($changed, $result);
    foreach ($result as $file) {
       $phpLint = array ();
       $lint = SVNLOOK . " cat -t {$transaction} {$repo} {$file}|"
             . PHP . " -l 2>&1";
       $error = exec ($lint);
       if ('No syntax errors detected in -' === $error) continue;
       $messages[] = "{$file} contains PHP syntax errors";
    }
    if (!empty ($messages)) {
        $return = implode(PHP_EOL, $messages);
    }
    return $return;
}

/**
 * Checks return values of these pre-commit functions and returns
 * the return code: 0 for no messages and 1 in any other case.
 *
 * @param bool|string The message output of pre-commit functions
 * @return int The exit code
 */
function getExitCodes($message)
{
    if (false !== $message) {
        file_put_contents('php://stderr', $message);
        return 1;
    }
    return 0;
}

$exitCodes = array ();
$exitCodes[] = getExitCodes(checkCommitMessage($transaction, $repo));
$exitCodes[] = getExitCodes(checkSyntax($transaction, $repo));

if (in_array(1, $exitCodes)) {
    exit(1);
}
exit(0);

Once you have a pre-commit hook in place, you don't have to worry that you commit code contains errors and might cause a failure for other developers in your team. The revision control system will notify you about any failures.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License.