Blog about software development


PHPStan: Find bugs without writing tests

15 Nov 2022 - by 'Maurits van der Schee'

I'm not saying you shouldn't write tests. But you may find bugs without writing tests using PHPStan. At least, that is what they claim on their website. I took a relatively big PHP project I run commercially to see whether or not PHPStan would help me to find and fix bugs. In this post I will explain how this works.

Adding PHPStan config file

You need to add a "phpstan.neon" configuration file to the root of your project. Mine looks like this:

    level: 5
        - web/index.php
        - php
        - phtml
        - lib
        - pages

This is specific for the framework I'm using (MintyPHP). You may need a different configuration or maybe no configuration at all (the defaults are quite good).

Installing PHPStan

PHPStan can be installed using composer. The command that you need is:

composer --dev require phpstan/phpstan

Note that the "--dev" flag means that you don't need the dependency in a production environment.

A PHPStan plugin in VSCode

PHPStan can integrate with many IDEs. I use VSCode to write PHP code. In VSCode I use the following extension for PHPStan:

ext install swordev.phpstan

You can open the "Command Palette" to enter that command (Ctrl-Shift-P or F1 on Linux).

Framework support

It is important to note that PHPStan has official support for Symfony, Doctrine and PHPUnit. There is also a long list of other frameworks that are supported (including Laravel and CakePHP). All officially and unofficially supported frameworks can be found in the PHPStan user guide.

MintyPHP support

I wrote a small script that adds a "docBlock" to every action and view file defining the variables that may be used in that file. The script can be run using the following command:

php vendor/mintyphp/tools/prepare_phpstan.php

The script adds a docBlock to the action file named "login($alias,$returnUrl).php" with the following path variable definitions:

 * @var string|null $alias
 * @var string|null $returnUrl

The view file named "login(login).phtml" will also get a docBlock with the available variables it can use (based on the scanning of both the action and the template action).

Overall opinion

PHPStan is quite easy to setup and to add to a project. By setting the reporting level at an appropriate value (5 for me) I didn't have to add many docBlocks. It helped me find a handful of bugs that I otherwise would have overlooked. That alone is worth the invested time. I was already using "Intelephense" showing syntax errors when files were open, but the fact that I can scan the project for errors provides a lot of value. Since PHPStan can find more than simple syntax errors (also: undefined variables, missing parameters, etc...) it is a sure way to improve the quality of your release... without writing (more) tests.


PS: Liked this article? Please share it on Facebook, Twitter or LinkedIn.