Let’s clean up our PHP code using PHP_CodeSniffer

Image for post

PHP is one of the most popular languages for application development, and it enjoys widespread use. With a history of 20 years, many libraries and frameworks have been developed for use with PHP.

These libraries and frameworks have been created in various coding cultures, so a variety of naming conventions have been used, with both CamelCase and lower-case being popular.

For example, the CodeIgniter style guide recommends using CamelCase, and FuelPHP’s coding standards advocate the use of lower case.

In proceeding with a project using a language with a background of various writing styles, it is a good idea to pre-define coding standards to create more readable and searchable code.

Determining whether or not code is in line with coding standards during code reviews is a burdensome process. To avoid this, one can use a source code analysis tool.

PHP has a variety of source code analysis tools. This time I will introduce PHP_CodeSniffer, also known as phpcs, to analyze a PHP project.

Installing PHP_CodeSniffer

There are several methods for installing PHP_CodeSniffer. To install using Composer, type the following command.

$ composer global require "squizlabs/php_codesniffer=*"

Using this method it will be installed under  so it’s a good idea to pass in a path.

The second method is to use Pear.

$ pear install PHP_CodeSniffer

This will install it under.

The last method is to download the file directly.

$ curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
php phpcs.phar -h
 
$ curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar
php phpcbf.phar -h

It can be run using the commands  and .

Usage

Basically, you specify the directory of the PHP project that you would like to analyze as an argument. The command is . The following is an example use case.

$ phpcs .
 
FILE: /path/to/your/code.php
--------------------------------------------------------------------------------------------------
FOUND 61 ERRORS AFFECTING 38 LINES
--------------------------------------------------------------------------------------------------
   2 | ERROR | [ ] Missing file doc comment
   7 | ERROR | [ ] Missing @category tag in class comment
      :
  34 | ERROR | [x] Tag value indented incorrectly; expected 2 spaces but found 1
  35 | ERROR | [ ] Tag cannot be grouped with parameter tags in a doc comment

Problems discovered by PHP_CodeSniffer are displayed as a list of file names and line numbers. Add  to the command if you’d like to have more detailed information and code displayed. Doing this will display the problem and the associated code like this:

$ ~/.composer/vendor/bin/phpcs --report=code . | more
 
FILE: /path/to/your/code.php
---------------------------------------------------------------------------------------------------
FOUND 61 ERRORS AFFECTING 38 LINES
---------------------------------------------------------------------------------------------------
LINE   2: ERROR [ ] Missing file doc comment
---------------------------------------------------------------------------------------------------
     1:  <?php
>>   2:   
     3:  namespace·Ncmb;
     4:
---------------------------------------------------------------------------------------------------
LINE   7: ERROR [ ] Missing @category tag in class comment
LINE   7: ERROR [ ] Missing @package tag in class comment
LINE   7: ERROR [ ] Missing @author tag in class comment
LINE   7: ERROR [ ] Missing @license tag in class comment
LINE   7: ERROR [ ] Missing @link tag in class comment
---------------------------------------------------------------------------------------------------
     5:  /**
     6:  ·*·Acl·class
>>   7:  ·*/
     8:  class·Acl·implements·Encodable
     9:  {
---------------------------------------------------------------------------------------------------
LINE  10: ERROR [x] The open comment tag must be the only content on the line
LINE  10: ERROR [ ] Missing short description in doc comment
LINE  10: ERROR [x] The close comment tag must be the only content on the line
:

Clean up code with PHPCBF

One could go through code line-by-line to clean it up by hand, but an easier method is to use the phpcbf command. Using this command will clean up the code instantaneously.

$ phpcbf .
 
PHPCBF RESULT SUMMARY
---------------------------------------------------------------------------------------------------
FILE                                                                               FIXED  REMAINING
---------------------------------------------------------------------------------------------------
/path/to/your/code.php                                                               23     38

For example it will clean up the way in which classes are described.

-    /** @var public ACL */
+    /**
+     * @var public ACL 
+    */

It also corrects the passing of arguments based on the number of characters per line.

-        if (strncmp($headers['Content-Type'][0], $validContent,
-                    strlen($validContent)) !== 0) {
+        if (strncmp(
+            $headers['Content-Type'][0], $validContent,
+            strlen($validContent)
+        ) !== 0
+        ) {

Unfortunately, PHP_CodeSniffer isn’t able to fix 100% of the problems that it uncovers automatically. For example, it can’t automatically add an  tag to a document. In such cases the error will remain. That being said, having most errors fixed automatically is still much more efficient that fixing all errors by hand. There is some concern that having errors fixed automatically reduces opportunities to learn how to write code properly. To avoid this, I recommend comparing code before and after PHPCBF has been run so that you will learn how to write better code the next time.

By default, PHP_CodeSniffer uses the PEAR coding standard. However, one can also choose from PSR2, Zend, Generic, and Squiz. One can also add standards, with frameworks such as cakephp-codesniffer making their standards public. Please select a standard that matches the standards in use at your workplace.

Sider uses PHP_CodeSniffer to automatically conduct code reviews on PHP projects. ESLint is convenient for use by individuals on their personal machines, but as an automatic review that works together with the GitHub PullRequest used by Sider it can be shared by all project members and is hugely convenient. Every time that code is pushed to GitHub, PHP_CodeSniffer does an automatic review, and it’s also convenient when multiple people are developing Sider using a cloud service. By all means, please give it a try.

squizlabs/PHP_CodeSniffer: PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.

More articles about PHP (PHPMD, PHP_CodeSniffer)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.