event-sourcing-phpstan-extension

A PHPStan extension for the patchlevel/event-sourcing library. It teaches PHPStan how aggregates work so that static analysis stays accurate on event sourced code, and it catches common mistakes before they ever reach runtime.

Features

  • Property initialization for aggregate roots and child aggregates, so PHPStan does not report false uninitialized property errors.
  • Unused properties are reported when no apply method writes them, because such a property can never receive state from an event.
  • Write only properties are reported when apply methods store state that is never read, because state that is not used to check invariants belongs in a projection.
  • Recording in apply methods is reported as an error, because recording events while replaying them leads to duplicated events.
  • Writing state outside apply methods is reported as an error, because state that is not derived from an event is lost when the aggregate is reloaded.

Installation

composer require --dev patchlevel/event-sourcing-phpstan-extension

If you use phpstan/extension-installer, the extension is registered automatically and you are done. Otherwise register it in your phpstan.neon:

includes:
    - vendor/patchlevel/event-sourcing-phpstan-extension/extension.neon

That is all the configuration the extension needs. All checks are active as soon as the extension is registered, and single rules can be deactivated through the configuration parameters.

Integration

New to the extension? The getting started guide walks you through enabling it and seeing both rules in action.