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.
You need to add a "
phpstan.neon" configuration file to the root of your project. Mine looks like this:
parameters: level: 5 scanFiles: - web/index.php fileExtensions: - php - phtml paths: - 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).
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.
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).
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.
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:
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).
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.