PHPStan

PHPStan is a static analysis tool for PHP that examines your code for errors without executing it. It provides early feedback on potential issues and helps enforce best practices to improve overall code quality.

Using PHPStan helps catch errors and potential bugs before runtime, reducing debugging time and increasing overall code stability. It enforces coding standards and best practices, which leads to more maintainable and robust PHP applications.

Target level

  • Minimum level: 5
  • Target level: 9

Foster Commerce Package

We don't maintain a Foster Commerce specific package anymore.

Example config

TODO setup and link to a repo that has code quality tooling

User guide

https://phpstan.org/user-guide/getting-started

Stubs

In CraftCMS sites, we're able to add custom fields to elements. So that IDE's know about those fields, Craft includes a CustomFieldBehavior php class in storage/runtime/compiled_classes.

PHPStan has a config called scanFiles that lets us include some extra files where PHPStan can find type definitions. However, during CI, the CustomFieldBehavior file isn't present.

Therefore, we need to explicitly generate a copy of that file. To support this, generally a generate_stubs.php file exists in a projects scripts directory.

Generating stubs

ddev composer run generate-stubs

Usage

In a PHP app/website

We typically use DDEV for local development of PHP apps or websites. As such, PHPStan should be run from within ddev.

To check for potential issues, run:

ddev composer run-script phpstan

In a PHP package

When working on a PHP package, such as a Craft plugin, we typically use composer directly, not from inside ddev. PHPStan can be run directly, instead of from within ddev.

To check for potential issues, run:

composer run-script phpstan

Ignoring errors

Whenever a PHPStan error is ignored, i.e. by using /* @phpstan-ignore-next-line */ comments or similar, a valid reason should be added as to why, or a TODO comment should be included to revisit the issue.

However, you should prefer not to use phpstan-ignore-line or phpstan-ignore-next-line to get checks passing. Oftentimes what phpstan is reporting might be something that could catch us out later on.