PHPStan is a tool used to identify issues relating to how code is written ensuring code is of high quality by scanning for dead code, ensuring type checking, identifying unknown method calls, etc. It prevents bugs and adheres to more object-oriented programming.
There is a PHPStan Laravel library available called Larastan which will integrate more easily with your Laravel project.
How to use
Open up the terminal and change the directory to your existing Laravel project.
Use the composer command to add Larastan.
composer require --dev "larastan/larastan:^2.0"
Create a new file called phpstan.neon inside the root folder of your project.
Add the following basic setup code to it.
includes:
- vendor/larastan/larastan/extension.neon
parameters:
universalObjectCratesClasses:
- Illuminate\Http\Resources\Json\JsonResource
paths:
- app/
level: 5
ignoreErrors:
excludePaths:
More options for the config file can be found at https://phpstan.org/config-reference.
The above rule level was set to the default which is usually level 5. To view the checks for each level check the PHPstan rule levels page at https://phpstan.org/user-guide/rule-levels.
To run PHPstan use the following command.
./vendor/bin/phpstan analyse
If you run the command for the first time on an existing project you’ve worked on you will likely encounter errors.
Here is an example below of the above command being run on one of the projects I’m working on at the time of writing.
Fix them and re-run the command until you get to a point where the majority if not all are fixed.
To make it easier to run the command add a new script value inside of the composer.json file similar to the following.
"scripts": {
"phpstan": "./vendor/bin/phpstan analyse"
},