Skip to content

Repository files navigation

PHPNomad PHPStan Rules

Custom PHPStan rules that enforce PHPNomad framework conventions.

These rules catch architectural anti-patterns at static analysis time, including models with inline serialization, service locator usage, raw SQL, singleton abuse, missing interface implementations, database scope violations, cache misuse, and more.

Installation

composer require --dev phpnomad/phpstan-rules

If you use phpstan/extension-installer, the rules activate automatically.

Otherwise, add to your phpstan.neon:

includes:- vendor/phpnomad/phpstan-rules/extension.neon

Rules

Models

IdentifierDescription
phpnomad.model.notFinalModels implementing DataModel must be declared final.
phpnomad.model.setterModels must not have setter methods (set*). Models are immutable.
phpnomad.model.arrayMethodModels must not have toArray() or fromArray(). Use a separate adapter class.

Adapters

IdentifierDescription
phpnomad.adapter.notImplementingClasses named *Adapter or in Adapters namespaces must implement ModelAdapter. Exempts MutationAdapter implementations.

Events

IdentifierDescription
phpnomad.event.notImplementingClasses in Events namespaces or named *Event must implement PHPNomad\Events\Interfaces\Event.
phpnomad.event.notFinalEvent classes should be declared final.
phpnomad.event.notReadonlyEvent properties and promoted constructor parameters should be readonly.
phpnomad.listener.notImplementingClasses in Listeners namespaces or named *Listener must implement CanHandle.

DI / Container

IdentifierDescription
phpnomad.di.serviceLocatorInstanceProvider::get() must not be called inside business classes. Use constructor injection. Calls inside initializers and bootstrappers are allowed.
phpnomad.di.missingTraitClasses implementing CanSetContainer must use the HasSettableContainer trait.

Initializers

IdentifierDescription
phpnomad.initializer.useInterfaceInitializers should use Has* interfaces (e.g., HasListeners, HasTaskHandlers) instead of manually calling registration methods like EventStrategy::attach().

Facades

IdentifierDescription
phpnomad.facade.notExtendingClasses in Facades namespaces or named *Facade must extend PHPNomad\Facade\Abstracts\Facade.
phpnomad.facade.noAbstractInstanceConcrete Facade subclasses must implement abstractInstance().

Database

IdentifierDescription
phpnomad.database.rawSqlRaw SQL strings (SELECT ... FROM, INSERT INTO, etc.) must not appear in code. Use PHPNomad datastore patterns.
phpnomad.database.scopeQueryBuilder, ClauseBuilder, and QueryStrategy must only be used inside Datastore classes.
phpnomad.database.concreteTableHintConstructor parameters should type-hint the Datastore interface, not concrete Table subclasses.

Controllers

IdentifierDescription
phpnomad.controller.noStatusController getResponse() must explicitly set an HTTP status code via setStatus() or setError().

Console

IdentifierDescription
phpnomad.command.notImplementingClasses in Commands namespaces or named *Command must implement PHPNomad\Console\Interfaces\Command.
phpnomad.command.handleReturnTypeCommand handle() methods must declare an int return type.

Tasks

IdentifierDescription
phpnomad.task.notImplementingClasses in Tasks namespaces or named *Task must implement PHPNomad\Tasks\Interfaces\Task.
phpnomad.taskHandler.notImplementingTask handler classes must implement PHPNomad\Tasks\Interfaces\CanHandleTask.
phpnomad.task.directHandleTask handlers must be dispatched via TaskStrategy::dispatch(), not by calling handle() directly.

Cache

IdentifierDescription
phpnomad.cache.directStrategyBusiness classes should not inject CacheStrategy directly. Use CacheableService or a Facade.
phpnomad.cache.uncaughtExceptionCacheStrategy::get() throws CachedItemNotFoundException. Ensure the call is wrapped in a try/catch.
phpnomad.cache.hardcodedTtlDo not hardcode TTL values as integer literals. Use a CachePolicy or configuration constant.
phpnomad.cache.stringConcatKeyUse the HasCacheKey interface for cache key generation instead of string concatenation.

General

IdentifierDescription
phpnomad.general.singletonInBusiness::instance() singleton calls must not be used outside of Facade classes. Use dependency injection.
phpnomad.general.globalKeywordThe global keyword must not be used. Use dependency injection.

Stack Elevator (layer purity)

Enforces the Stack Elevator doctrine (Novatorius coding standards KB: initiatives-nomadic-development-coding-standards-the-stack-elevator): code is layered Core (pure business concepts) → Service (implementation logic) → Platform (system integration), and dependencies only point upward (Platform → Service → Core). Layers are marked by namespace segments; because a layer name can also appear as a domain name (e.g. Novatorius\Quartermaster\Platform\Core\...), the last matching segment in a namespace determines its layer.

IdentifierDescription
phpnomad.stackElevator.coreDependsOnServiceCore-layer code must not import or reference Service-layer symbols.
phpnomad.stackElevator.coreDependsOnPlatformCore-layer code must not import or reference Platform-layer symbols.
phpnomad.stackElevator.coreDenylistCore-layer code must not reference denylisted third-party namespaces.
phpnomad.stackElevator.serviceDependsOnPlatformService-layer code must not import or reference Platform-layer symbols.
phpnomad.stackElevator.serviceDenylistService-layer code must not reference denylisted third-party namespaces.

Checked references: use statements, extends/implements, trait uses, property/parameter/return types, instantiations, static calls and constant fetches, instanceof, catch types, attributes, and fully qualified function calls. Doc-block-only references are not checked.

Adopting layer purity on its own

The Stack Elevator rules live in a self-contained stack-elevator.neon. To enforce layer purity without the rest of the convention ruleset (useful when first onboarding an existing codebase), disable the auto-loaded extension for this package and include only the layer-purity file:

"extra": {
"phpstan/extension-installer": {
"ignore": ["phpnomad/phpstan-rules"]
}
}
includes:- vendor/phpnomad/phpstan-rules/stack-elevator.neon

The full extension.neon already includes stack-elevator.neon, so the default (all rules) behavior is unchanged.

All settings are configurable via phpstan.neon (defaults shown):

parameters:phpNomadStackElevator:checkCoreLayer:truecheckServiceLayer:truenamespaceRoots:# vendor roots the convention applies to- Novatorius- PHPNomadcoreSegments: [Core] # namespace segments marking each layerserviceSegments: [Service]
platformSegments: [Platform, WordPress, Integration]
excludeNamespaces: [] # grandfathered namespace prefixes ("*" wildcards allowed)coreDenylist: [] # third-party prefixes Core may never referenceserviceDenylist: [] # third-party prefixes Service may never reference

Existing repos will have violations when first enabling these rules. Grandfather them with excludeNamespaces (e.g. a composition root such as Novatorius\Quartermaster\Service, whose job is to wire all layers together) or a PHPStan baseline, then shrink the list over time.

Suppressing Rules

Use PHPStan's built-in ignore syntax:

// @phpstan-ignore phpnomad.model.notFinalclass User implements DataModel
{
// ...
}

Or suppress in phpstan.neon via baseline:

vendor/bin/phpstan --generate-baseline

Requirements

  • PHP 8.2+
  • PHPStan 2.0+

License

MIT

About

PHPStan rules for PHPNomad framework conventions

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages