How to install and use Codesniffer (phpcs)
Hello! In this article we are going to learn how to install the Coder and Codesniffer (phpcs) libraries through composer on our machine, with the Drupal and DrupalPractice standard codings to use it globally in all projects.
Depending on our operating system and version, the instructions may be different. This guide will detail how to perform the download, installation and use for the Ubuntu 24.04 LTS (Linux) operating system .
Install Coder and Codesniffer
The recommended way to install these libraries is through Composer, to keep a correct control of the necessary versions and dependencies; this will avoid problems in the future and will make it easier for us to obtain the libraries.
Not sure if you have composer installed? Run the following command:
which composer
If you can't find the installation path, you'll need to install Composer. If you have the latest stable version of Ubuntu (as of today, 24.04 LTS) and updated local repositories, just run the command:
sudo apt install composer
If you have an older version or are having trouble getting Composer this way, follow the installation instructions on the official Composer page for alternatives.
Once we have Composer correctly installed on our machine, we move on to the next step: downloading and installing Coder and its dependencies through Composer.
composer global require drupal/coder
If you notice carefully, we are using the "global" parameter. This means that we are going to install the package on our local machine, for global use in all projects . It is important to differentiate the version of Composer that we have installed globally on our host machine and the version of Composer installed in each of our projects.
In our case, we are using version 8.3.x of Coder and version 3.11.x of php_codesniffer.
You can use the following command to determine the installation path of each of the libraries downloaded by Composer global:
composer global show -P
Ok! We have Coder and Codesniffer installed on our machine, but we are missing something. In order to avoid typing the full path to the binary, we are going to add the path to our PATH variable, with the following command (check first that the Composer binaries are actually located in this path):
export PATH="$PATH:$HOME/.config/composer/vendor/bin"
Once done, we can use the tool with:
phpcs
If you can't find the file or directory, restart the terminal. If it still doesn't work, the path to the binary is different.
The next step is to check if the coding standards we need for our code to be validated have been installed. We can check the coding standards with the command:
phpcs -i
The coding standards used to follow good coding practices in Drupal are the Drupal Profiles and DrupalPractice . You should see a message like this:
The installed coding standards are MySource, PEAR, PSR1, PSR2, PSR12, Squiz, Zend, Drupal, DrupalPractice, VariableAnalysis and SlevomatCodingStandard
If you do not have the mentioned conding standards, you will need to perform an additional configuration with the following command:
phpcs --config-set installed_paths ~/.config/composer/vendor/drupal/coder/coder_sniffer,~/.config/composer/vendor/sirbrillig/phpcs-variable-analysis,~/.config/composer/vendor/slevomat/coding-standard
How to use Codesniffer to clean and validate code
There are different ways to use Codesniffer on a daily basis. In this guide we will explain how to use it via the command line console; you can see here how to integrate it into your IDE.
Code analysis
To use Codesniffer we must specify 3 parameters:
- The code standards we want to apply for automatic review.
- File extensions to determine which ones will be checked against the defined standard.
- The path of the file or directory of files to be checked.
An example would be the following:
phpcs --standard=Drupal,DrupalPractice --extensions=php,module,inc,install,profile,theme /modules/custom/my_custom_module
For this specific case, Codesniffer would automatically check all files in the /modules/custom/my_custom_module path whose extensions are "*.php", "*.module", "*.inc", "*.install", "*.profile", "*.theme" with the DrupalPractice standard coding.
Each coding standard has a specific function for code analysis:
- Drupal : Check the formatting and style of your code, such as indentation, variable names, spaces, control structures...
- DrupalPractice - Review Drupal best practices, such as correct API usage, deprecated code, dependency injection...
Ideally, you should use both standards to perform a complete code analysis of your projects. Take a look at PHP code standards in Drupal .
When you run the command, the code in the specified directory or file will be parsed. If you get errors or warnings, you'll get a message like this:
FILE: /modules/custom/my_custom_module/src/Controller/MyControllerSample.php
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
FOUND 7 ERRORS AND 2 WARNINGS AFFECTING 17 LINES
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
8 | WARNING | [x] Unused use statement
9 | WARNING | [x] Unused use statement
56 | ERROR | [x] Expected 1 space after IF keyword; 0 found
115 | ERROR | [ ] unserialize() is insecure unless allowed classes are limited. Use a safe format like JSON or use the allowed_classes option.
119 | ERROR | [x] Missing function doc comment
121 | ERROR | [x] Line indented incorrectly; expected 6 spaces, found 4
121 | ERROR | [x] Object operator not indented correctly; expected 6 spaces but found 4
122 | ERROR | [x] Line indented incorrectly; expected 6 spaces, found 4
123 | ERROR | [x] Line indented incorrectly; expected 6 spaces, found 4
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 18 MARKED SNIFF VIOLATIONS AUTOMATICALLY
Now let's explain each part of code analysis:
- First, the file that has been analyzed is indicated, with the complete path.
- Below is a summary of the errors and warnings encountered.
- The errors and warnings found are then displayed for each line, indicating:
- The line of code, on the far left.
- Whether it is an error or a warning.
- An "X" check that, if selected, can be automatically corrected with phpcbf (in the next point we detail what this is)
- A short description indicating why the configured coding standard is violated.
- A message showing how many errors or warnings phpcbf can fix.
As you can see, the code analysis is very detailed and it is easy to find the place and correct each of the points indicated. The recommendation here is to correct each of the points, by file, and to launch the command to re-run the analysis and clean the errors and warnings as we solve them.
This is the best way to learn best practices and improve your coding skills in the future!
Auto-correction with phpcbf
There are times when very simple or easy-to-fix errors or warnings are flagged, such as a missing space, a tab, or a period at the end of a comment; these can be fixed automatically with phpcbf, the tool included in Codesniffer!
To run phpcbf we can do it in a similar way to phpcs, as follows:
phpcbf --standard=Drupal,DrupalPractice --extensions=php,module,inc,install,profile,theme /modules/custom/my_custom_module/src/Controller/MyControllerSample.php
This way, all points with an "X" marked in the code analysis will be automatically fixed in the file specified in the path. It is important not to get confused with the path and file extensions!
Conclusion
Using these tools not only improves the usability and readability of your projects' code, it goes much further. It helps you follow a standard and grow as a programmer, keeping your code orderly and clean, and helping your project partners and the community make code readable and easy to understand.