VVV PHP Code Sniffer with WordPress

Unbekownst to a lot of people that use VVV even on a daily basis is that there is a built in code sniffer or CS integrated into the machine that can be really useful if your committing code and want to maintain a higher standard. If you’ve provisioned the box then sitting inside your www directory there should be another directory called phpcs which stands for “PHP Code Sniffer”.

Sniffing Code from the console

After you’ve booted up the vm you’ll want to vagrant ssh into the box and check if phpcs is installed by typing which phpcs which should return the its executable path which is something like /srv/www/phpcs/scripts/phpcs. If nothing is returned then you need to add the executable to your path but it should be there by default when you provision the machine.

Using the built in php code sniffer with WordPress is easy. Once we’ve verified that phpcs is on the box and it’s executable then we need to test out a file to see if it’s up to coding standard. Let’s check out our wp-config.php file by running phpcs /srv/www/wordpress-default/wp-config.php . This should return results similar to those below.

Keep in mind that this sniffed using the default PEAR standard for the file and since we are working with WordPress we want a standard that is more our ballgame but to see which ones are installed type phpcs -i After that pick a standard listed, I’m going to use WordPress

1
phpcs /srv/www/wordpress-default/wp-config.php --standard=WordPress`

Notice now that the results are slightly different since we are using the WordPress standard to sniff our code. That’s a lot of errors though and I don’t want to manually go through and find them all fixing them on by one. That would be so boring and take way too long so let’s fix them in one go. Notice the message at the bottom of that command output.

PHPCBF CAN FIX THE MARKED SNIFF VIOLATIONS AUTOMATICALLY

Fixing Code

Is totally something you don’t want to miss and is just as easy to use as phpcs. If you don’t already have a patch or diff application setup for phpcbf then you’ll probably want to pass the flag –no-patch along with this next command otherwise you will most likely get an error.

1
phpcbf --standard=WordPress --no-patch /srv/www/wordpress-default/wp-config.php`

Now those errors should be all fixes to that coding standard. If you were to run the phpcs command again then the errors in question should no longer show up in the sniff results.

You can also fix entire directories using these tools but just be warned that though it works pretty well sometimes you just don’t get all of the perfect code that you expected.

As a note for those that work with VIP QuickStart the same packages are installed on the Vagrant box as well and can be used in the same fashion. If your a vim user I’ve found that this plugin works well.