Finding bugs using PHPStan as a Static Analyzer

With PHP being an interpreted language it has a downside when it comes to finding bugs in your code. It will not show you errors in your software until you actually run it. PHPStan tries to solve this problem by doing static analysis on your code. It was recently created by Ondrej Mirtes.

Running PHPStan will tell you about bugs in your codebase almost instantly (yes, it’s very fast). At the time of writing this article, PHPStan currently checks your code on:

  • The existence of classes and interfaces in an instance of, catch type hints, other language constructs, and even annotations. PHP does not do this and just stays silent instead.
  • Existence of variables while respecting scopes of branches and loops.
  • Existence and visibility of called methods and functions.
  • Existence and visibility of accessed properties and constants.
  • Correct types assigned to properties.
  • The correct number and types of parameters are passed to constructors, methods, and functions.
  • Correct types returned from methods and functions.
  • The correct number of parameters passed to sprintf/printf calls is based on format strings.
  • Useless casts like (string) ‘foo’.
  • Unused constructor parameters – they can either be deleted or the author forgot to use them in the class code.
  • That only objects are passed to the clone keyword.

As you can see, it contains a lot of useful checks which will warn you of potential bugs before you even run your code.

Installing PHPStan

Installing PHPStan is as easy as including it in your project through composer:

$ composer require --dev phpstan/phpstan

We can now run PHPStan from the base directory of our project:

$ vendor/bin/phpstan analyze -l 4 src

A breakdown of this command:

  • vendor/bin/phpstan is the executable
  • analyze tells PHPStan to analyze all files in the given directories
  • -l 4 means that we want to analyse on the most strict level
  • src is the directory we want to analyse

Try running this in your own project and see what kind of potential errors are living in your codebase.

Integrating PHPStan into CI

It’s super easy to use PHPStan in Continuous Integration. For most of my personal projects, I use TravisCI. Since we’ve included PHPStan as a dev-dependency in our composer.json file we just have to add the PHPStan executable to the scripts that the CI-software needs to run.

For TravisCI, this means just changing the default script in a .travis.yml like this:

language: php
php:
  - '8.0'
install: composer install

# Simply add these lines
script:
    - vendor/bin/phpunit
    - vendor/bin/phpstan analyse src tests --level=4

The default script that TravisCI runs for PHP projects is simply phpunit. Now we’ve added PHPStan to it. If PHPStan finds any errors within your project, the build will fail.