msvrtan's blog

PHP syntax analysis - PHP lint


On more then few occasions I found myself committing broken code to our git repository (and deploying it onto staging server) so I started to look into how to minimize chance of doing that. As we are a team of 10 PHP developers working continuosly on multiple projects this is something we desperately need.

First step was probably the easiest: syntax error checking. Syntax errors are easy to fix, don't happen often (if you are actually testing code you are working on locally :) but however they do happen. Also you have to start somewhere :)

The easiest tool to do it in PHP is PHP itself by using -l option:

php -l name_of_file.php

Unfortunately it doesnt support recursive analysis, so I built a small bash script to do it (I work on Ubuntu Linux):

find application/ -name '*.php' -exec php -l {} \; |grep -v 'No syntax error'

This will look through whole application folder (including subfolders) for all *.php files. It will print only errors, that's why |grep part is needed so it will remove all data about files where no error was found. Output it returns will look like this:

PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in application/class/balance_sheet_fix.class.php on line 8
Errors parsing application/class/balance_sheet_fix.class.php

Current example was run on codebase for one of projects I work on, codebase has 9Mb and 1629 files and it took around 30 seconds on Intel based i5 desktop. PHP lint proved to be pretty nifty tool, not really meant to be runned after every change in code but you can always run it before commiting your changes and be sure to avoid those really basic bugs.

Hope I helped somebody, my next step was PHP CodeSniffer and if there will be any interest I can write a short tutorial on why and how. Also I hope to integrate all of code checking into one of those cool CI tools like Jenkins so if you have any suggestions or tips I would be very greatefull.

Update #1: I forgot to mention that this tool will return only first syntax error in file so after fixing it you must run it again to see if that file had more errors.

To get number of files use: "find application/ -name '*.php' | wc -l"