PHP › Static Analysis (PHPStan & Psalm)

How do custom PHPStan or Psalm rules and extensions let a team enforce their own project specific coding standards and catch domain specific mistakes beyond the tool's built in checks?

Advanced

Answer

Beyond the extensive built in checks that PHPStan and Psalm already provide, both tools support writing custom rules or extensions tailored to a specific project's own conventions and common mistakes, such as flagging direct calls to a deprecated internal helper function that should no longer be used, enforcing that a certain type of object is always constructed through a designated factory method rather than directly, or ensuring a specific naming convention is consistently followed across an entire team, letting the tool encode institutional knowledge that generic, general purpose checks alone could never capture.
final class NoDirectDatabaseQueryRule implements Rule {
    public function processNode(Node $node, Scope $scope): array {
        // custom rule logic here
    }
}
Real-world example A large engineering organization writes a custom PHPStan rule that flags any code directly instantiating a database connection outside of their designated repository classes, enforcing a consistent architectural pattern automatically across every single pull request submitted by any team.

Common follow-ups: How much ongoing maintenance effort is typically required to keep a set of custom static analysis rules up to date?;Are there community maintained rule sets available for popular frameworks like Laravel or Symfony?