Code-Checker is a tool distributed by Moodle HQ which lets you validate code against core coding standards. You install it as a local plugin in a development environment and run it against specified files. It then spits out all kinds of nit-picky errors:
-
#76: ····page\_heading();·?>
-
This comment is 67% valid code; is this commented out code?
-
Inline comments must start with a capital letter, digit or 3-dots sequence
-
Inline comments must end in full-stops, exclamation marks, or question marks
Code-Checker leverages the PHP_CodeSniffer tool; in essence it’s a set of CodeSniffer definitions wrapped in a Moodle plugin. This adds a fair amount of overhead for testing coding standards–you shouldn’t need a functional Moodle environment, nor for that matter a web server.
My preferred integration tool is gulp.js, a task-runner built on node. It’s similar to grunt but without all the front-loaded configuration. There’s a plugin for gulp called gulp-phpcs which integrates PHP_CodeSniffer with gulp and lets you check the files in your project. Happily it was pretty simple to do this with Moodle.
First, you need to have PHP_CodeSniffer available in your development environment. This is how I did it on my Macbook:
1 | cd /usr/local |
I then added that directory to my PATH:
1 | PATH=/usr/local/scripts/phpcs/scripts:$PATH |
Finally, I cloned in the Moodle plugin and added its standards definition to the installed paths for PHP_CodeSniffer:
1 | git clone https://github.com/moodlehq/moodle-local\_codechecker.git moodlecs |
At this point we’re ready to integrate it into gulp. We need to install the gulp-phpcs module and add it to the project:
1 | npm install gulp-phpcs --save-dev |
Now we provide a basic configuration in our gulpfile.js. This example will check all the php files in Lafayette’s Stellar theme:
1 | // List of modules used. |
Invoked from the command line, we get the same results as from the web interface, but faster and without the overhead:
1 | [10:24:21] PHP Code Sniffer found a problem in ../theme_stellar/layout/default.php |
This also lets you create watcher tasks to catch errors introduced while developing.