Search by

ptgs / phpstan-rules

rentbetter

PHPStan rules for RentBetter coding conventions — Doctrine, Symfony routes, architecture, and serialization.

Package info

github.com/RentBetter/phpstan-rules

Type:phpstan-extension

pkg:composer/ptgs/phpstan-rules

Statistics

Installs: 1

Dependents: 1

Suggesters: 0

Stars: 1

v0.1.0 2026-11-27 07:00 UTC

This package is auto-updated.

Last update: 2026-11-27 07:27:54 UTC


README

PHPStan rules for Symfony/Doctrine projects, extracted from RentBetter coding conventions.

PHPStan rules covering Doctrine usage, Symfony routing, architecture patterns, JSON serialization, and enum enforcement.

Installation

composer require --dev ptgs/phpstan-rules

With phpstan/extension-installer the rules are auto-discovered — no manual includes needed. Without it, include vendor/ptgs/phpstan-rules/extension.neon in your phpstan.neon.

Rules

Doctrine

Rule Error ID What it detects
NoPublicCollectionReturnRule ptgs.noCollectionReturn Entity public methods returning Collection instead of array
NoDirectFlushRule ptgs.noDirectFlush Calling ->flush() on EntityManagerInterface outside a repository — repositories own persistence, everything else passes $save
EntityTablePrefixRule ptgs.entityTablePrefix Entities missing #[ORM\Table(name: 'tbl_...')] — prefix makes direct table usage searchable
EntityDeferredExplicitRule ptgs.entityDeferredExplicit Entities missing #[ORM\ChangeTrackingPolicy('DEFERRED_EXPLICIT')] — prevents accidental flushes, improves performance, and gives control over batch saving and flush timing
RedundantColumnTypeRule ptgs.redundantColumnType type: Types::STRING on string properties etc. — Doctrine infers these from the PHP type, so specifying them is noise
NoHardcodedValueInQueryRule ptgs.noHardcodedValueInQuery Hardcoded numeric/string values in DQL queries — use bound parameters or $enum->value

The package also ships ReadOnlyEntityPropertiesExtension, which tells PHPStan that the mapped properties of a #[ORM\Entity(readOnly: true)] are written by hydration, so they are not reported as "never written, only read" when the rows only ever arrive by SQL. It reads the attributes directly — no phpstan-doctrine or object-manager bootstrap required — and unlike phpstan-doctrine's own check it applies whether or not the entity declares a constructor. Disable it with ptgs.readOnlyEntityHydration: false.

Symfony Routes

Rule Error ID What it detects
NoGenericIdParameterRule ptgs.noGenericId Route paths containing {id}, or route methods with a param named $id (use {tenancyId} / $tenancyId etc.)
RouteRequiresMethodRule ptgs.routeRequiresMethod #[Route] missing methods: parameter
RouteRequiresUuidRequirementRule ptgs.routeRequiresUuidRequirement Route {fooId} params without requirements: constraint
ActionMethodNamingRule ptgs.actionMethodNaming Public route methods not ending in Action
RouteNameMatchesMethodRule ptgs.routeNameMatchesMethod Route name: doesn't match method minus Action suffix
UniqueRouteNameRule ptgs.uniqueRouteName Two routes registering the same name once class-level name: prefixes are applied — Symfony keeps only the last-registered route and silently 404s the rest. Needs the whole codebase in one run to be authoritative
NoClassLevelRouteRule ptgs.noClassLevelRoute #[Route] on controller classes — class-level prefixes hide the real path
RoutePathCamelCaseRule ptgs.routePathCamelCase Route path segments using snake_case or kebab-case instead of camelCase
RouteIdParamMustBeStringRule ptgs.routeIdParamMustBeString Route ID parameters not typed as string
RouteMethodSignatureRule ptgs.routeMethodSignature Route methods missing ApiRequest first param or ApiResponse return type
RouteRequiresSpecApiRule ptgs.routeRequiresSpecApi Route methods missing #[Spec\Api] attribute
NoJsonDecodeInControllerRule ptgs.noJsonDecodeInController Controllers calling json_decode() — hand-parsing JSON; use the Form component
NoMultipleRequestParamsInControllerRule ptgs.noMultipleRequestParamsInController Controllers accessing 2+ request parameters — use a form type
NoRequestPayloadAccessRule ptgs.noRequestPayloadAccess Any call to Request::toArray(), Request::getPayload(), or Request::getContent() — use the Form component to bind a typed DTO
NoEntityAsFormDataClassRule ptgs.noEntityAsFormDataClass Form types using a #[ORM\Entity] class as data_class instead of a DTO (embeddables and plain models in an Entity namespace are fine)

Architecture

Rule Error ID What it detects
ForbiddenDependencyRule ptgs.forbiddenDependency Constructor params that violate a configured group→group dependency boundary (see Dependency Boundaries)
ReadonlyServiceRule ptgs.readonlyService Non-readonly service classes
NoWallClockRule ptgs.noWallClock The current time read off the wall — new DateTimeImmutable() / new DateTime() / new DatePoint() with no argument or one PHP resolves against now ('today', '+1 day', '10:00'), including one built by a constant, concatenation, interpolation or sprintf() ("-{$days} days"); time(); and date(), gmdate(), idate(), localtime(), getdate() without a timestamp — instead of an injected Psr\Clock\ClockInterface or Symfony\Component\Clock\Clock::get()->now(). Explicit values (new DateTimeImmutable('2025-01-15')) and microtime() stopwatches are fine
NamedArgumentForBooleanRule ptgs.namedArgumentForBoolean Boolean literals passed positionally to project methods
SaveParameterDefaultRule ptgs.saveParameterDefault $save/$flush bool params defaulting to false instead of true
MoneyReturnTypeRule ptgs.moneyReturnType Public methods returning MoneyModelV2 instead of MoneyInterface
UseDateFormatterRule ptgs.useDateFormatter Direct ->format() on DateTime objects instead of DateFormatter

Serialization

Rule Error ID What it detects
NoSnakeCaseJsonKeyRule ptgs.noSnakeCaseJsonKey jsonSerialize() returning arrays with snake_case keys — a leading underscore (_debug) is an envelope marker and passes

Enum

Rule Error ID What it detects
StatusColumnMustBeEnumRule ptgs.statusColumnMustBeEnum Doctrine #[Column] on *status properties without enumType: — integer columns (an HTTP status code) are exempt

Configuration

All rules are enabled by default. Disable individual rules in your phpstan.neon:

parameters:
    ptgs:
        readonlyService: false
        noDirectFlush: false

Level-aware rules

By default, all enabled rules fire regardless of the PHPStan analysis level. To suppress custom rules at lower levels, set ruleLevel to the desired threshold:

parameters:
    ptgs:
        ruleLevel: 5   # only architecture rules (level 5+) will fire

Each rule has a minimum level threshold:

Level Category Rules
5 Architecture forbiddenDependency, noDirectFlush, noRequestPayloadAccess, noJsonDecodeInController, noMultipleRequestParamsInController, noClassLevelRoute, noEntityAsFormDataClass
6 Correctness noPublicCollectionReturn, statusColumnMustBeEnum, noHardcodedValueInQuery, entityDeferredExplicit, entityTablePrefix, redundantColumnType, routeRequiresMethod, routeMethodSignature, routeIdParamMustBeString, routeRequiresUuidRequirement, moneyReturnType, saveParameterDefault, useDateFormatter, uniqueRouteName
8 Convention noGenericId, actionMethodNaming, routeNameMatchesMethod, routePathCamelCase, routeRequiresSpecApi, readonlyService, namedArgumentForBoolean, noSnakeCaseJsonKey

When ruleLevel is null (the default), all rules fire — backward compatible.

Note: PHPStan's --level CLI flag does not update the %level% parameter, so ruleLevel must be set to a fixed integer, not %level%.

Namespace Groups

Several rules ask "is this class a controller? a service? an entity?". That's answered centrally via the groups parameter. Each group is a list of patterns; a class belongs to a group if its FQCN matches any of them.

Pattern syntax:

  • A regex bracketed by ~ delimiters — string-matched against the FQCN (e.g. ~\\Service\\~ matches anything in a \Service\ namespace segment). Using ~ lets / appear unescaped if you need it.
  • Anything else — a literal FQCN, exact match.

Defaults shipped in extension.neon:

parameters:
    ptgs:
        groups:
            controller: ['~\\Controller\\~']
            service:    ['~\\Services?\\~', '~\\Helpers?\\~']
            repository: ['~\\Repository\\~']
            entity:     ['~\\Entity\\~']
            command:    ['~\\Command\\~']
            migration:  ['~\\Migrations?\\~']
            project:    ['~^App\\\\~', '~^PTGS\\\\~']
            dbAccess:
                - 'Doctrine\ORM\EntityManagerInterface'
                - 'Doctrine\DBAL\Connection'
                - 'PDO'

Override any group in your phpstan.neon to fit your project's namespace layout (NEON replaces the entry rather than merging, so include the full list):

parameters:
    ptgs:
        groups:
            project: ['~^Acme\\\\~']

Dependency Boundaries

ForbiddenDependencyRule enforces that classes in one group must not inject constructor dependencies from another. Configure it as a map of from-group → list of {group, reason}. The reason is included verbatim in the error message so violators understand the why, not just the what.

Defaults:

parameters:
    ptgs:
        forbiddenDependencies:
            controller:
                - group: dbAccess
                  reason: 'Controllers must remain thin — push DB access into a service.'
                - group: repository
                  reason: 'Controllers should depend on services, not repositories directly.'
            service:
                - group: dbAccess
                  reason: 'Services must use repositories — repositories own all DB access.'

Example error:

Service PTGS\PropertyApi\Portal\Help\Service\HelpArticleSyncService may NOT depend on Doctrine\DBAL\Connection (group: dbAccess). Services must use repositories — repositories own all DB access.

To add a new boundary, append to the map:

parameters:
    ptgs:
        forbiddenDependencies:
            command:
                - group: dbAccess
                  reason: 'Console commands should orchestrate via services, not touch the DB directly.'

Matching is by FQCN string. Subtype detection is not supported — list every class you want forbidden in the group, including each concrete implementation of an interface if those are also injected directly.

Examples

Before

// ptgs.forbiddenDependency (controller → dbAccess)
class UserController {
    public function __construct(
        private EntityManagerInterface $em,
    ) {}
}

// ptgs.noGenericId
#[Route('/users/{id}', methods: 'GET')]
public function getUserAction(string $id) {}

// ptgs.routeRequiresMethod
#[Route('/users')]
public function listUsersAction() {}

// ptgs.namedArgumentForBoolean
$service->save($entity, true);

// ptgs.noSnakeCaseJsonKey
public function jsonSerialize(): array {
    return ['first_name' => $this->firstName];
}

After

// Inject a service, not the EntityManager
class UserController {
    public function __construct(
        private UserService $userService,
    ) {}
}

// Use descriptive parameter names
#[Route('/users/{userId}', methods: 'GET', requirements: ['userId' => Uuid::REGEX])]
public function getUserAction(string $userId) {}

// Always specify HTTP methods
#[Route('/users', methods: 'GET')]
public function listUsersAction() {}

// Use named arguments for booleans
$service->save($entity, flush: true);

// Use camelCase for JSON keys
public function jsonSerialize(): array {
    return ['firstName' => $this->firstName];
}

Requirements

  • PHP >= 8.4
  • PHPStan >= 2.0

License

MIT - see LICENSE.