What is CodeSniffer?
CodeSniffer is a tool used to analyse PHP code to check if the code structure follows specific coding standards. These coding standards dictate a specific way of how you write your PHP code, when the coding standard is applied to CodeSniffer then CodeSniffer can be used to check weather your code is following the rules of that coding standard.
The PHP standard that everyone should be following is PSR-12, more information on PSR-12 can be found on the PHP-FIG website.
How to install CodeSniffer?
For this guide you will require composer to be installed which is the recommended way to install CodeSniffer.
Use the composer command to install CodeSniffer into the global composer folder. If you get a request to use —dev then say yes.
composer global require "squizlabs/php_codesniffer=*"
Try running the phpcs version command.
phpcs --version
You should see the version number returned.
PHP_CodeSniffer version 3.10.0 (stable) by Squiz and PHPCSStandards
Fix “command not found: phpcs” issue
If the phpcs command is not recognized then do the following.
Use the following command to ouput the path for the global composer package folder.
composer global config bin-dir --absolute
This was the output for me.
Changed current directory to /home/mesh/.config/composer
/home/mesh/.config/composer/vendor/bin
Update the PATH variable to include the above composer path that was printed. You may need to add this line to your .profile or .zshrc file.
export PATH=~/.config/composer/vendor/bin:$PATH
Try running the phpcs version command again and it should work this time.
phpcs --version
Commands
Get a list of the installed coding standards.
phpcs -i
Run CodeSniffer on a project with a selected coding standard.
phpcs --standard=PSR12 ~/dev/laravel/app