PHPStan baseline: adopt static analysis on a legacy project without fixing everything first
Generate a PHPStan baseline, stop new errors from getting in, then raise the level step by step. A tested routine for old PHP codebases.
On this page
Running PHPStan on an old codebase for the first time often reports hundreds or thousands of errors. A baseline records today’s errors and ignores them, so the build passes and PHPStan only fails on new problems. You then pay down the old ones over time.
1. Install and choose a starting level
composer require --dev phpstan/phpstan
Create phpstan.neon (or phpstan.dist.neon to commit, letting developers override locally):
parameters:
level: 5
paths:
- src
- tests
phpVersion: 80400 # the PHP version you deploy to
Levels go from 0 (basic checks) to 10 (strictest, including treating mixed strictly). Level 5 checks argument types and is a good first target; start at 2 if the codebase is very loose. If you use a framework, add its extension (for example larastan/larastan for Laravel or phpstan/phpstan-symfony) so magic methods are understood.
2. Generate the baseline
vendor/bin/phpstan analyse --generate-baseline
This writes phpstan-baseline.neon. Include it:
includes:
- phpstan-baseline.neon
Run vendor/bin/phpstan analyse again: it should report no errors. Commit both files and add the command to CI.
3. Keep the baseline honest
- Unmatched entries fail the build. When someone fixes a baselined error, PHPStan reports “Ignored error pattern … was not matched”. Regenerate the baseline in that pull request, which makes it shrink over time.
- Never regenerate to hide a new error. In review, a growing baseline file is a red flag.
- Use
--error-format=githubin GitHub Actions to get inline annotations.
4. Raise the level gradually
- Bump
levelby one. - Run
--generate-baselineagain so only the new level’s errors are recorded. - Fix the cheapest category first.
vendor/bin/phpstan analyse --error-format=tablegroups by file; many errors share one root cause, such as a missing return type on a widely used method.
Add types at the boundaries first: return types on repositories and services, and @param array shapes such as array{id: int, email: string} on functions that pass arrays around.
5. Pair it with an upgrade
PHPStan with phpVersion set to your target release catches calls to removed functions and changed signatures before you upgrade. Combine it with Rector for automatic fixes, and use the upgrade checklist for the changes neither tool can prove.
Baseline or ignoreErrors?
Use ignoreErrors with a comment for errors you have decided to accept permanently, such as a known false positive in generated code. Use the baseline for debt you intend to fix. Keeping them separate makes the intent obvious.