tournayrelabs / phpstan-rules
PHPStan rules you can enable one by one through configuration
Package info
github.com/TournayreLabs/phpstan-rules
Language:JavaScript
Type:phpstan-extension
pkg:composer/tournayrelabs/phpstan-rules
Requires
- php: >=8.2
- phpstan/phpstan: ^2.0
Requires (Dev)
- phpunit/phpunit: ^11.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-11-23 16:02:20 UTC
README
Opt-in PHPStan rules: install them anywhere, enable only the ones you want through the project configuration.
Installation
composer require --dev tournayrelabs/phpstan-rules
- With
phpstan/extension-installer:extension.neonis included automatically. - Without it, add this to
phpstan.neon:
includes: - vendor/tournayrelabs/phpstan-rules/extension.neon
Enabling rules
All rules are disabled by default. Enable the ones you need:
parameters: tournayreLabsPhpstanRules: interfaceNameSuffix: true loggerInCatch: true doctrineQueryCall: true doctrineQueryAllowedClasses: ['App\Service\Search\*'] doctrinePersistenceCall: true doctrinePersistenceAllowedClasses: ['App\Service\UnitOfWork'] doctrineAllowObjectRepositories: true doctrineRepositoryNoInheritance: false symfonyAutowireEnv: true symfonyAutowireEnvAllowedClasses: ['App\Config\*'] controllerEntityManager: true controllerEntityManagerControllerClasses: ['*\Controller\*', '*Controller'] namedArguments: true namedArgumentsExcludedPaths: ['/var/www/src/Legacy'] noInstanceofOnForbiddenDependency: true noInstanceofOnForbiddenDependencyRestrictions: - {dependency: 'Vendor\Library\', denyFrom: 'App\Domain\', reason: 'the domain must not know the library'} noInstanceofOnForbiddenDependencyExcludedPaths: [] forbiddenInterfaces: - namespaces: ['App\Domain\*'] interfaces: ['Countable', 'Psr\Log\*'] - namespaces: ['App\Application\*'] preset: clock message: 'Implement your own clock in App\Infrastructure.'
Rules
| Parameter | Identifier | Description |
|---|---|---|
interfaceNameSuffix |
tournayreLabs.interfaceNameSuffix |
Interfaces must end with Interface |
loggerInCatch |
tournayreLabs.loggerInCatch |
A catch without throw must call a Psr\Log\LoggerInterface |
doctrineQueryCall |
tournayreLabs.doctrineQueryCall |
Native Doctrine query methods only in repositories / allowed services |
doctrinePersistenceCall |
tournayreLabs.doctrinePersistenceCall |
Native Doctrine persistence methods only in repositories / allowed services |
doctrineRepositoryNoInheritance |
tournayreLabs.doctrineRepositoryNoInheritance |
Repositories must not extend EntityRepository |
symfonyAutowireEnv |
tournayreLabs.symfonyAutowireEnv |
No #[Autowire(env: ...)]: use configuration objects |
controllerEntityManager |
tournayreLabs.controllerEntityManager |
Controllers must not depend on Doctrine\ORM\EntityManagerInterface |
namedArguments |
tournayreLabs.namedArguments |
A call with 2+ arguments including a positional one must use PHP 8 named arguments |
noInstanceofOnForbiddenDependency |
tournayreLabs.noInstanceofOnForbiddenDependency |
No instanceof \Fully\Qualified on a forbidden dependency namespace |
forbiddenInterfaces |
tournayreLabs.forbiddenInterface |
Forbid given interfaces in given namespaces (configurable any number of times) |
Named arguments
namedArguments(tournayreLabs.namedArguments): a call (function, method, static call,new, nullsafe call) passing at least two arguments with at least one positional must use named arguments. The message suggests the names (name: …).namedArgumentsExcludedPaths: a file whose path starts with one of these entries is skipped.- Skipped: spread, first-class callable syntax, dynamic callee, PHP builtin functions,
@no-named-arguments, magic methods, a positional argument feeding a variadic parameter.
Namespace boundaries
noInstanceofOnForbiddenDependency(tournayreLabs.noInstanceofOnForbiddenDependency): complements namespace-boundary tools that see imports (use) but not aninstanceofwritten with an inline fully qualified name. Reported when the class is written fully qualified, its namespace starts with a restriction'sdependencyand the current namespace starts with itsdenyFrom(both end with\). One error per matching restriction.noInstanceofOnForbiddenDependencyRestrictions: list of{dependency, denyFrom, reason}. Empty by default, so enabling the rule alone reports nothing.noInstanceofOnForbiddenDependencyExcludedPaths: a file whose path starts with one of these entries is skipped.- Not reported: an imported name (
use+instanceof Foo), a file without namespace.
Forbidden interfaces
forbiddenInterfaces is a list: each entry is an independent configuration, add as many as needed. Active as soon as the list is not empty.
namespaces: class name patterns (*wildcard, case-insensitive) matched against the FQCN of the analysed class, enum or interface.interfaces: interface name patterns (*wildcard) forbidden there. Exact name match: forbiddingCollectiondoes not forbidArrayCollection.preset(optional): ready-made interface list, added tointerfaces. Available:clock=Psr\Clock\ClockInterface+Symfony\Component\Clock\ClockInterface. An unknown preset fails at container build.message(optional): shown as a tip under the error.- Detected:
implementsof a class / enum / anonymous class,extendsof an interface. An interface inherited from a parent class is not reported (the parent is responsible). - Not detected: using the interface as a type (constructor parameter, property...). The rule forbids declaring it, not depending on it.
Symfony rules
-
symfonyAutowireEnv(tournayreLabs.symfonyAutowireEnv): a method/constructor parameter must not use#[Autowire(env: '...')](nor#[Autowire('%env(...)%')]/value: '%env(...)%') — controllers, services, actions. Inject a configuration object instead. -
symfonyAutowireEnvAllowedClasses: class name patterns (*wildcard) of the configuration objects allowed to read env variables (e.g.App\Config\*). Without it, no class is exempt. -
Not covered:
#[Autowire(expression: "env('X')")],#[Autowire(param: ...)]pointing to a parameter built from an env variable. -
controllerEntityManager(tournayreLabs.controllerEntityManager): a controller must not useDoctrine\ORM\EntityManagerInterface(or a subtype such asEntityManager) as a constructor / method parameter type (promoted properties and action arguments included) or a property type. Delegate to a service or a repository. -
controllerEntityManagerControllerClasses: class name patterns (*wildcard) identifying controllers. Default['*\Controller\*', '*Controller']. A class extendingSymfony\Bundle\FrameworkBundle\Controller\AbstractControlleror carrying#[Symfony\Component\HttpKernel\Attribute\AsController]is a controller too, whatever its name. -
Not covered:
$this->container->get(EntityManagerInterface::class), types declared only in PHPDoc.
Doctrine rules
Force the rest of the code through business methods (returning a null object or throwing when nothing is found).
doctrineQueryCall(tournayreLabs.doctrineQueryCall):find*,count,createQueryBuilder,getRepository,createQuery, querygetResult()/getOneOrNullResult()... — also on application repositories called from outside.doctrinePersistenceCall(tournayreLabs.doctrinePersistenceCall):persist,remove,flush,refresh,detach,clear, transactions.- Allowed callers: any class implementing
Doctrine\Persistence\ObjectRepository(soEntityRepository/ServiceEntityRepositorysubclasses), plus the class name patterns (*wildcard) ofdoctrineQueryAllowedClasses/doctrinePersistenceAllowedClasses. doctrineAllowObjectRepositories: false(defaulttrue): only the class name patterns define the allowed callers (DDD, e.g.App\Infrastructure\Persistence\*). Applies to both call rules.doctrineRepositoryNoInheritance(tournayreLabs.doctrineRepositoryNoInheritance): a class must not extendDoctrine\ORM\EntityRepository(so neitherServiceEntityRepository); inject theEntityManagerinstead. Use it withdoctrineAllowObjectRepositories: false, otherwise composition-based repositories are not recognised as allowed callers.- Limitation: a repository extending
EntityRepositorykeeps its native methods public (PHP cannot narrow visibility), so withoutdoctrineRepositoryNoInheritancethey are only caught at call sites outside allowed callers.
Adding a rule
- Create a
finalclass insrc/Rules/implementingPHPStan\Rules\Rule, with anidentifier(). - In
extension.neon:- add a parameter defaulting to
falseand its entry inparametersSchema - add the service and a
conditionalTagsentry bound to that parameter
- add a parameter defaulting to
- Add a
RuleTestCasetest intests/Rules/(fixture intests/Rules/data/). - Add a row to the table above.
Development
make install make run-all-tests-php