← All posts

Testing

PHPStan: Catch PHP Bugs Before You Run the Code

PHPStan is a static analyzer that finds type errors and bugs in your PHP without running it - tunable across levels.

P Testing

PHP's flexibility is also where its bugs hide: a misspelled method, a wrong argument type, a variable that's null on one branch - none of it complains until that exact line runs in production. PHPStan reads your code without executing it and finds those problems ahead of time. It traces types through your whole codebase and reports the calls that can't work, the code that can never run, and the assumptions that don't hold.

Analysis Without Execution

You point PHPStan at a directory and it reports issues statically - no test harness, no running site required:

# Analyze your custom code at level 5 vendor/bin/phpstan analyse web/modules/custom --level=5 # Or drive it from a phpstan.neon config file vendor/bin/phpstan analyse

Levels: Adopt Gradually

PHPStan has rule levels from 0 (loosest) up to max. On an existing codebase you start low, fix what it finds, and ratchet the level up over time - so it's an on-ramp, not a wall of thousands of errors on day one. A baseline file can freeze existing issues so you only gate new ones.

Drupal-Aware With an Extension

The phpstan-drupal extension teaches PHPStan about Drupal's service container, entity API, and dynamic patterns, and a deprecation ruleset flags calls to APIs slated for removal - which is how you find upgrade blockers before an update breaks the site.

Rough Edges and Limitations

  • Dynamic code needs hints. Magic methods and heavy runtime dynamism sometimes require annotations or config to analyze cleanly.
  • Higher levels are strict. Level max is demanding; most projects settle somewhere in the middle deliberately.
  • Drupal needs the extension. Without phpstan-drupal you'll fight false positives on framework patterns.
  • It finds type bugs, not logic bugs. It proves the code is consistent, not that it does the right thing - you still need tests.

Static analysis is the cheapest bug-finding you can add to a PHP project: no runtime, no fixtures, just a command that tells you what can't work before your users do.

Internal link suggestion: link "upgrade blockers" to the Rector post, which can auto-fix many of the deprecations PHPStan flags.