PHP CodeSniffer is a quick and easy way to ensure you adhere to a set of coding standards when writing your PHP applications. It will basically tokenize your PHP files and will try to detect violations of a defined coding standard (PSR).
A little bit of history 👨🏫:
The PHP Framework Interop Group is a group of over 20 members who have put together and maintaining a list of PHP Standard Recommendations (aka PSR
). Some of those PSRs are PSR-2 and PSR-12 (an improved version of the latter). WordPress has created its own coding standards that you can easily use with PHP CodeSniffer too.
Back to real DEV work 👨💻:
Here are the steps to integrate PHP CodeSniffer as part of your local development:
1. Install PHP CodeSniffer via Composer. Here you have two options:
You can either install it system-wide as a composer global package:
composer global require "squizlabs/php_codesniffer=*"
NOTE: Make sure to place Composer’s system-wide vendor bin directory in your $PATH
so the phpcs
executable can be located by your system. On a Mac, you just need to add
export PATH="$PATH:$HOME/.composer/vendor/bin"
to either ~/.bashrc
or ~/.zshrc
file depending on your shell:
# first check if you already have composer's vendor bin directory as part of your path:
echo $PATH
# if it's not there, then run (if you're using Bash):
echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bashrc
source ~/.bashrc
# OR run (if you're using Zsh):
echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.zshrc
source ~/.zshrc
# and then check the PATH once again:
echo $PATH
Or alternatively, include a dependency for squizlabs/php_codesniffer
in your composer.json
file. For example:
{
"require-dev": {
"squizlabs/php_codesniffer": "3.*"
}
}
Once you’re all done you should be able to use the phpcs
command globally within your terminal like so:
phpcs --version
> PHP_CodeSniffer version 3.6.0 (stable) by Squiz (http://www.squiz.net)
2. Test the phpcs
command against a sample PHP file (optional)
# go into your home directory (or any other directory you prefer):
cd ~
# create a new temporary directory in there
mkdir phpcs-test && cd phpcs-test
# create a new sample PHP file
touch sample.php
# open it in your code editor of choice (in my case I'll use VSCode):
code .
# and add some sample PHP code in there like the one below (I purposefully violated the PSR12 standard in there, so we can see proper results):
<?php
class Person {
public $name;
public function set_name( $name )
{
$this->name=$name;
}
public function getName($name) {
return $this->name;
}
}
# run PHP CodeSniffer against that file
phpcs --standard=PSR12 sample.php
# the output should look something like this:
FILE: /Users/vasilestefirta/phpcs-test/sample.php
----------------------------------------------------------------------------------------------------
FOUND 9 ERRORS AFFECTING 5 LINES
----------------------------------------------------------------------------------------------------
3 | ERROR | [ ] Each class must be in a namespace of at least one level (a top-level vendor name)
3 | ERROR | [x] Opening brace of a class must be on the line after the definition
6 | ERROR | [ ] Method name "Person::set_name" is not in camel caps format
6 | ERROR | [x] Expected 0 spaces after opening parenthesis; 1 found
6 | ERROR | [x] Expected 0 spaces before closing parenthesis; 1 found
8 | ERROR | [x] Expected at least 1 space before "="; 0 found
8 | ERROR | [x] Expected at least 1 space after "="; 0 found
11 | ERROR | [x] Opening brace should be on a new line
14 | ERROR | [x] Expected 1 newline at end of file; 0 found
----------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 7 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------------------------------------
Time: 80ms; Memory: 6MB
NOTE: if you want to view a list of all available coding standards, you can run the following command:
phpcs -i
> The installed coding standards are PEAR, Zend, PSR2, MySource, Squiz, PSR1 and PSR12
3. Attempt to fix some of the standard violations using PHP CodeSniffer’s phpcbf
CLI command (optional).
As we can see in the output above after running phpcs
, the end of the summary says:
PHPCBF CAN FIX THE 7 MARKED SNIFF VIOLATIONS AUTOMATICALLY
so, let’s try to run it and see what happens:
phpcbf --standard=PSR12 sample.php
# output
PHPCBF RESULT SUMMARY
----------------------------------------------------------------------
FILE FIXED REMAINING
----------------------------------------------------------------------
/Users/vasilestefirta/phpcs-test/sample.php 7 2
----------------------------------------------------------------------
A TOTAL OF 7 ERRORS WERE FIXED IN 1 FILE
----------------------------------------------------------------------
Time: 89ms; Memory: 6MB
As we can see, phpcbf
was able to fix 7 out of 9 errors for us automatically 👏. The remaining 2 require manual work like adding a namespace
and rename set_name()
to setName()
. The sample.php
file at this point should look like this:
<?php
// ERROR 1: manually add a namespace here
class Person
{
public $name;
public function set_name($name) // ERROR 2: rename method to be camel case.
{
$this->name = $name;
}
public function getName($name)
{
return $this->name;
}
}
4. This is all great, but running phpcs
and phpcbf
manually against every single PHP file you write, can be time-consuming and not the way to live your life, to be honest 😄.
Let’s fix that and integrate PHP CodeSniffer with Visual Studio Code by installing the vscode-phpcs by Ioannis Kappas extension first. This extension is pretty well documented, but you only need to configure a few settings:
{
"phpcs.enable": true,
"phpcs.standard": "PSR2",
"phpcs.ignorePatterns": ["*/vendor/*"]
}
NOTE: if this VSCode extension cannot locate the phpcs
executable for some reason, then you can set it manually via the phpcs.executablePath
setting like so:
{
"phpcs.executablePath": "/Users/vasilestefirta/.composer/vendor/bin/phpcs"
}
You can find that full path by running which phpcs
inside your terminal.
If everything went well, you should have the same results as in the video below:
5. Now let’s configure VSCode to fix some of those phpcs
detected errors automatically when we save the PHP file. For that, install the php cs fixer VSCode extension, and set the following settings:
{
"php-cs-fixer.rules": "@PSR2",
"php-cs-fixer.onsave": true
}
If everything went well, your code should be auto-formatted like in the video below:
Congrats if you made it this far 👏 and Happy Coding! 👩💻 👨💻
Photo by Andreas Gücklhorn on Unsplash.