Static code analysis in PHP (and GitLab)

Jan 12, 2020 by Thibault | 1710 views

PHP GitLab Secure Software Development

In the PHP toolbox for testing, you'll often find phpunit for unit testing, PHP_CodeSniffer for code style analysis, and here we present PHPStan for static code analysis.

Static code analysis tries to detect bugs by analyzing the source code of a program, without actually running it. At the opposite of PHPUnit, you don't need to write tests for your app.

In my opinion, static code analysis is particularly useful for an interpreted language like PHP, as it allows to detect "compile" errors in edge cases that are not covered by a unit test.

In the example below, PHPStan will immediately detect the missing \ in front of Exception(...). With PHPUnit this would require an additional test to cover this single line of code:

namespace App;

class Foe
    public function bar() {
        $r = $this->doSomething();
        if ($r == null) {
            throw new Exception("Failed to do something...");

Installation and usage

PHPStan is best installed with composer:

composer require --dev phpstan/phpstan

You can run PHPStan directly from the command line, by using the command analyze and listing the directories to process:

vendor/bin/phpstan analyse src tests

However, it's easier to create a configuration file called phpstan.neon so you can omit the list of directories:

  level: 1
    - src
    - tests
  reportUnmatchedIgnoredErrors: false

The configuration file uses neon syntax, which is actually very similar to YAML.


As you can see in the configuration file, PHPStan has a configurable level for the analysis. In a nutshell, here is what each level will check:

  • level 0 : parse errors
  • level 1 : undefined variables
  • level 2 : correct type hints (but does not enforce the presence of type hints, see level 6)
  • level 3 : correct type of return values
  • level 4 : comparisons
  • level 5 : correct type of method parameters
  • level 6 : presence of type hints
  • level 7 : null returned values

The complete list of tests for each level is available on the GitHub page of PHPStan.

Integration in GitLab

To run phpstan at each push to GitLab, simply add this job to your .gitlab-ci.yml:

  image: cylab/php72
    - COMPOSER_CACHE_DIR=composer-cache composer install
    - vendor/bin/phpstan analyse

Additional rules

It is also possible to run additional rules in PHPStan. For example, to check for deprecated classes and methods, simply install the appropriate package:

composer require --dev phpstan/phpstan-deprecation-rules

Then add the rules to the includes section of your phpstan.neon:

    - vendor/phpstan/phpstan-deprecation-rules/rules.neon

You might also like...