Setting up PHPStan
04. Juni 2025
04. Juni 2025
composer req -dev phpstan/phpstan
echo '/.cache' >> .gitignore
includes:
- phpstan-baseline.neon
parameters:
# Use local .cache dir instead of /tmp
tmpDir: .cache/phpstan
level: 8
paths:
- Classes/
- Tests/
excludePaths:
- .Build
# @todo recheck rules.
inferPrivatePropertyTypeFromConstructor: true
reportUnmatchedIgnoredErrors: false
treatPhpDocTypesAsCertain: false
parameters:
ignoreErrors:
Some explanations:
the file “phpstan.neon” is the main configuration file for PHPStan. PHPStan searches for this file in the folder you execute the tool in, or expects you to point the tool to the phpstan.neon file with the “-c” parameter.
It is recommended that the phpstan.neon holds all necessary defaults for your project.
The file “phpstan-baseline.neon” is basically empty at this point. This file is usually not created by hand, but generated with the -b option to PHPStan. It holds all ignored errors, as in the errors reported which you cannot or will not fix at this point.
It is considered good practice to mark errors to be ignored here centrally in this file rather than using the annotation in each individual source-code file in order to give a complete overview on what has been ignored in one place.
./vendor/bin/phpstan analyze
this will report all errors up to level 8 (as defined in the phpstan.neon configuration)
it is good practice to step up to this level by first fixing the lower levels issues, like this:
./vendor/bin/phpstan analyze -l 0
./vendor/bin/phpstan analyze -l 1
./vendor/bin/phpstan analyze -l 2
this way one can gradually work towards the final level. The goal here is that your set level defined in phpstan.neon will report no problems.
Once you are at a comfortable level, but you can't get rid of problems from other libraries, interfaces or api's you can do the following command:
./vendor/bin/phpstan analyze -b
this will save the remaining errors to the baseline file, and will be ignored on further runs. This should be the last step.
Both files, phpstan.neon and phpstan-baseline.neon should be added to the repository, of course. They can be used to run automatically on commit or push.
Here are more information about the levels in PHPStan.