PHP Static Analysis Tools

Code quality analysis means Static Code Analysis for PHP. This method helps you to check the quality of your code and it is a part of software testing in PHP or web applications.

Therefore, it is a security measure. This code checking tool checks your code for common bugs and security loopholes including better coding conventions, inconsistent usage of programming elements, using methods that have no return values, misusing API calls and common coding mistakes.

Static Code Analysis Tools

  • PHPStan is the most commonly used tool and also one of the youngest. It has been rapidly adopted since it’s release in 2016. It’ll discover bugs in your code without running the code.
  • Phan isn’t used by many of the projects I reviewed but is popular and well supported. It was created at Etsy and appears to be the primary tool used by Wikipedia’s MediaWiki project. The advertised upside of using Phan is that it has a focus on minimizing false-positives. This makes it trivial to use but it might catch fewer issues compared to the other options.

Style Tools

  • PHPCS is the original code standards tool for PHP and dates back to 2006. It’s primary use is to establish standards and identify violations. It does however also provide a package phpcbf which can sometimes automatically fix violations. PHPCS is extremely mature and very flexible and comes with a massive selection of pre-written “Sniffs” available to use.
  • PhpCsFixer is supported by the popular Symfony framework. This tool automatically applies any defined code styles to code when it’s run. e.g. php-cs-fixer fix src. This seems to be the leading choice for a majority of projects.
  • StyleCI is Laravel’s answer to code style. This is a hosted commercial solution which is free for open-source projects. It takes a similar approach to PhpCsFixer and can automatically apply a selected style to code. It’s different though in that it modifies code after it’s been merged into a git repository. It fixes styles quietly in the background as developers make changes by pulling the code, restyling it, and pushing it back to the main repository.

 PHP Copy/Paste Detector

PHPCPD is a small tool created by Sebastian Bergmann to detect clones in your project. Here is a short example:

$phpcpd .
phpcpd 2.0.1 by Sebastian Bergmann.
Found 1 exact clones with 19 duplicated lines in 2 files:
- foo.php:9-28
    bar.php:18-37
1.32% duplicated lines out of 1439 total lines of code.

Time: 21 ms, Memory: 2.50Mb You can control the verbosity of the output and the minimum number of lines/tokens that are considered a clone.

Repeated code hides repeated bugs, therefore you should keep the percentage of duplicated lines as low as possible by refactoring the clones into a single method or class.

Code Sniffer

Code Sniffer is arguably the most popular tool to enforce a strict style guide in your PHP code. It ships with support for popular coding standards such as PSR2ZendPEAR among others. The PSR standard family is used by most people nowadays because it was created by the FIG group so if you are looking for a standard to adopt, PSR2 is a good option. Code Sniffer also allows you to create your own coding standard. In most cases this won’t be necessary, but if you are feeling adventurous you can take a look at the documentation.

Here is an example of the output generated by Code Sniffer

$ phpcs tests.php --report-full --standard=PSR2
FILE: tests.php
--------------------------------------------------------------------------
FOUND 7 ERRORS AND 2 WARNINGS AFFECTING 6 LINES
--------------------------------------------------------------------------
  2 | WARNING | [ ] Line exceeds 120 characters; contains 128 characters
  3 | WARNING | [ ] Line exceeds 120 characters; contains 139 characters
  8 | ERROR   | [ ] Each class must be in a namespace of at least one leve
  8 | ERROR   | [ ] Class name "foo_foo" is not in camel caps format
 16 | ERROR   | [ ] Method name "foo_foo::bar_bar" is not in camel caps
 23 | ERROR   | [ ] Each class must be in a file by itself
 23 | ERROR   | [ ] Each class must be in a namespace of at least one leve
 33 | ERROR   | [x] Expected 1 newline at end of file; 0 found
 33 | ERROR   | [x] A closing tag is not permitted at the end of a file
--------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
--------------------------------------------------------------------------

As you can see, Code Sniffer shows you a detailed summary of the detected code violations. There are several output formats, so if you want a less human-readable report for parsing purposes you can output XML or CSV data. Recently they even introduced an option to output a blame report showing the percentage of errors introduced by each developer.

Although Code Sniffer can also prevent some common semantic errors, its main focus is enforcing code standards. There are other tools out there with better support for semantic error detection, but none can beat Code Sniffer when it comes to strictly following a code standard.

Automatic code fix

Some tools go beyond error detection and try to automatically patch the code for you.

PHP Coding Standards Fixer suggests fixes according to the coding standard you specified. The following example lists the problems found in two files:

$ php-cs-fixer fix --dry-run . --level=psr2
    1) foo.php (php_closing_tag, eof_ending)
    2) bar.php (braces, function_declaration, eof_ending)
PHPCBF is a script that can also fix some errors automatically for you. It ships with the latest version of Code Sniffer and you can run it simply like this:

$ phpcbf –standard=PSR2 tests.php Patched 2 files

 PHPMD

PHP Mess Detector is a multi faceted static analysis PHP Tool based on PHP Depend. The kind of problems detected by PHPMD are divided into 5 main categories:

  • Code SizeAnalyses code complexity and warns you if your project is starting to become unmanageable. You can define thresholds for maximum class length, method length, cyclomatic complexity, etc.
  • DesignDetects software design related issues, such as the use of eval, goto, exit, excessive coupling, etc.
  • NamingEnsures that your variables, class names and method names are appropriate (not too long, nor too short). Using good names is crucial for the person reading your code, so you should not underestimate this analysis.
  • ControversialA few rules about naming conventions and other best practices that do not apply to every project
  • UnusedDetects blocks of unused code that should be cleaned

Here is an example of PHPMD’s output:

$ phpmd tests.php text ruleset
tests.php:8 The class foo_foo is not named in CamelCase.
tests.php:8 The property $my_property is not named in camelCase.
tests.php:16    Avoid unused parameters such as '$arg1'.
tests.php:16    Avoid unused parameters such as '$arg2'.
tests.php:16    bar_bar accesses the super-global variable $_POST.
tests.php:16    The method bar_bar is not named in camelCase.
tests.php:19    Avoid unused local variables such as '$some_name'.
tests.php:27    The method barBar has 11 parameters. Consider to reduce parameter number under 10.
tests.php:29    Avoid unused local variables such as '$someName'.

ruleset is a XML file which contains a list of inspections that you want to enable. You can include any of the 5 main categories and even specify which rules should be used within these categories. For more information about how to create this file you can check the documentation.

Overall, PHPMD is a highly customisable static analyser. Although it does not enforce a specific code standard, you can use it to clean your code, detect possible bugs and manage the complexity of your project.

Honourable Mentions

  • Pslam was also released in 2016 and has grown in popularity a little more slowly. It claims more features out of the box and has a focus is on type-related bugs.
  • Scrutinizer is the most popular commercial option in use by open-source projects and has been around longer then it’s open-source counterparts. It’s free for open-source projects but is only available as a hosted solution.
  • Semgrep is a fast, open-source, static analysis tool for finding bugs and enforcing code standards at editor, commit, and CI time. Its rules look like the code you already write; no abstract syntax trees or regex wrestling. Supports 17+ languages.

Conclusion

When you write code, the smaller the file size, the faster it runs. That’s because big files need to be parsed numerous times before they can be used. And if you run your software on a shared hosting, suboptimal code size can lead to frequent timeouts or crashed sites. This is why static analysis tools are so useful for PHP developers.

Leave a Comment