PHPStan Rules Beyond Core

A searchable index of 263 individual PHPStan rules from the most popular community packages. Each entry shows the rule's class, what it does, and (where the package documents it) a wrong/correct code example.

Generated by scanning installed rule classes · last refreshed 7 hours ago

symplify/phpstan-rules 92 rules Packagist

Set of Symplify rules for PHPStan.

symplify/phpstan-rules

AlreadyRegisteredAutodiscoveryServiceRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\AlreadyRegisteredAutodiscoveryServiceRule

Reports: The "%s" service is already registered via autodiscovery ->load(), no need to set it twice

symplify/phpstan-rules

AvoidFeatureSetAttributeInRectorRule

Symplify\PHPStanRules\Rules\Rector\AvoidFeatureSetAttributeInRectorRule

Reports: Instead of using Rector rule to setAttribute("%s") to be used later, create a service extending "DecoratingNodeVisitorInterface". This ensures attribute decoration and node changes are in 2 separated steps.

symplify/phpstan-rules

CheckRequiredInterfaceInContractNamespaceRule

Symplify\PHPStanRules\Rules\CheckRequiredInterfaceInContractNamespaceRule

Reports: Interface must be located in "Contract" or "Contracts" namespace

symplify/phpstan-rules

ClassNameRespectsParentSuffixRule

Symplify\PHPStanRules\Rules\ClassNameRespectsParentSuffixRule

Reports: Class should have suffix "%s" to respect parent type

symplify/phpstan-rules

ExplicitClassPrefixSuffixRule

Symplify\PHPStanRules\Rules\Explicit\ExplicitClassPrefixSuffixRule

symplify/phpstan-rules

ExplicitExpectsMockMethodRule

Symplify\PHPStanRules\Rules\PHPUnit\ExplicitExpectsMockMethodRule

Reports: PHPUnit mock method is missing explicit expects(), e.g. $this->mock->expects($this->once())->...

symplify/phpstan-rules

FileNameMatchesExtensionRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\FileNameMatchesExtensionRule

Reports: The config uses "%s" extension, but the file name is "%s". Sync them to ease discovery

symplify/phpstan-rules

ForbiddenArrayMethodCallRule

Symplify\PHPStanRules\Rules\Complexity\ForbiddenArrayMethodCallRule

Reports: Array method calls [$this, "method"] are not allowed. Use explicit method instead to help PhpStorm, PHPStan and Rector understand your code

symplify/phpstan-rules

ForbiddenExtendOfNonAbstractClassRule

Symplify\PHPStanRules\Rules\ForbiddenExtendOfNonAbstractClassRule

Reports: Only abstract classes can be extended

symplify/phpstan-rules

ForbiddenFuncCallRule

Symplify\PHPStanRules\Rules\ForbiddenFuncCallRule

Reports: Function "%s()" cannot be used/left in the code

symplify/phpstan-rules

ForbiddenMultipleClassLikeInOneFileRule

Symplify\PHPStanRules\Rules\ForbiddenMultipleClassLikeInOneFileRule

Reports: Multiple class/interface/trait is not allowed in single file

symplify/phpstan-rules

ForbiddenNewArgumentRule

Symplify\PHPStanRules\Rules\Complexity\ForbiddenNewArgumentRule

symplify/phpstan-rules

ForbiddenNodeRule

Symplify\PHPStanRules\Rules\ForbiddenNodeRule

Reports: "%s" is forbidden to use

symplify/phpstan-rules

ForbiddenStaticClassConstFetchRule

Symplify\PHPStanRules\Rules\ForbiddenStaticClassConstFetchRule

Reports: Avoid static access of constants, as they can change value. Use interface and contract method instead

symplify/phpstan-rules

ForeachCeptionRule

Symplify\PHPStanRules\Rules\Complexity\ForeachCeptionRule

Reports: There is %d nested foreach nested in each other. Refactor to more flat approach or to collection to avoid high complexity

symplify/phpstan-rules

FormTypeClassNameRule

Symplify\PHPStanRules\Rules\Symfony\FormTypeClassNameRule

Reports: Class extends "%s" must have "FormType" suffix to make form explicit, "%s" given

symplify/phpstan-rules

MaximumIgnoredErrorCountRule

Symplify\PHPStanRules\Rules\MaximumIgnoredErrorCountRule

Reports: Ignored error count %d in phpstan.neon surpassed maximum limit %d.\nInstead of ignoring more errors, fix them to keep your codebase fit.

symplify/phpstan-rules

NoAbstractControllerConstructorRule

Symplify\PHPStanRules\Rules\Symfony\NoAbstractControllerConstructorRule

Check if abstract controller has constructor, as it should use #[Require] instead to avoid parent constructor override

Reports: Abstract controller should not have constructor, to avoid override by child classes. Use #[Require] or @require and autowire() method instead

symplify/phpstan-rules

NoArrayMapWithArrayCallableRule

Symplify\PHPStanRules\Rules\Complexity\NoArrayMapWithArrayCallableRule

Reports: Avoid using array callables in array_map(), as it cripples static analysis on used method

symplify/phpstan-rules

NoAssertFuncCallInTestsRule

Symplify\PHPStanRules\Rules\PHPUnit\NoAssertFuncCallInTestsRule

Reports: Instead of assert() that can miss important checks, use native PHPUnit assert call

symplify/phpstan-rules

NoBareAndSecurityIsGrantedContentsRule

Symplify\PHPStanRules\Rules\Symfony\NoBareAndSecurityIsGrantedContentsRule

Reports: Instead of using one long "and" condition join, split into multiple standalone #[IsGranted] attributes

symplify/phpstan-rules

NoBundleResourceConfigRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoBundleResourceConfigRule

Reports: Avoid using configs in Bundle/Resources directory. Move them to "/config" directory instead

symplify/phpstan-rules

NoClassLevelRouteRule

Symplify\PHPStanRules\Rules\Symfony\NoClassLevelRouteRule

Reports: Avoid class-level route prefixing. Use method route to keep single source of truth and focus

symplify/phpstan-rules

NoClassReflectionStaticReflectionRule

Symplify\PHPStanRules\Rules\Rector\NoClassReflectionStaticReflectionRule

Reports: Instead of "new ClassReflection()" use ReflectionProvider service or "(new PHPStan\Reflection\ClassReflection(<desired_type>))" for static reflection to work

symplify/phpstan-rules

NoConstructorAndRequiredTogetherRule

Symplify\PHPStanRules\Rules\Symfony\NoConstructorAndRequiredTogetherRule

Reports: Avoid using __construct() and @required in the same class. Pick one to keep architecture clean

symplify/phpstan-rules

NoConstructorOverrideRule

Symplify\PHPStanRules\Rules\Complexity\NoConstructorOverrideRule

Reports: Possible __construct() override, this can cause missing dependencies or setup

symplify/phpstan-rules

NoControllerMethodInjectionRule

Symplify\PHPStanRules\Rules\Symfony\NoControllerMethodInjectionRule

Reports: Instead of service "%s" action injection, use __construct() and invokable controller with __invoke() to clearly separate services and parameters

symplify/phpstan-rules

NoDoctrineListenerWithoutContractRule

Symplify\PHPStanRules\Rules\Doctrine\NoDoctrineListenerWithoutContractRule

Based on https://tomasvotruba.com/blog/2019/07/22/how-to-convert-listeners-to-subscribers-and-reduce-your-configs Subscribers have much better PHP support - IDE, PHPStan + Rector - than simple yaml files

Reports: There should be no Doctrine listeners modified in config. Implement "Document\Event\EventSubscriber" to provide events in the class itself

symplify/phpstan-rules

NoDocumentMockingRule

Symplify\PHPStanRules\Rules\Doctrine\NoDocumentMockingRule

Reports: Instead of document mocking, create object directly to get better type support

symplify/phpstan-rules

NoDoubleConsecutiveTestMockRule

Symplify\PHPStanRules\Rules\PHPUnit\NoDoubleConsecutiveTestMockRule

Reports: Do not use "willReturnOnConsecutiveCalls()" and "willReturnCallback()" on the same mock. Use "willReturnCallback() only instead to make test more clear.

symplify/phpstan-rules

NoDuplicateArgAutowireByTypeRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoDuplicateArgAutowireByTypeRule

Spot pointless explicit services:

Reports: Instead of passing "%s" to arg(), remove the line and let autowiring handle it

symplify/phpstan-rules

NoDuplicateArgsAutowireByTypeRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoDuplicateArgsAutowireByTypeRule

Spot pointless explicit services:

Reports: Instead of passing "%s" to args(), remove the line and let autowiring handle it

symplify/phpstan-rules

NoDynamicNameRule

Symplify\PHPStanRules\Rules\NoDynamicNameRule

Reports: Use explicit names over dynamic ones

symplify/phpstan-rules

NoEntityMockingRule

Symplify\PHPStanRules\Rules\Doctrine\NoEntityMockingRule

The ORM entities and ODM documents should never be mocked, as it leads to typeless code. Use them directly instead.

Reports: Instead of entity or document mocking, create object directly to get better type support

symplify/phpstan-rules

NoEntityOutsideEntityNamespaceRule

Symplify\PHPStanRules\Rules\NoEntityOutsideEntityNamespaceRule

Reports: Class with #[Entity] attribute must be located in "Entity" namespace to be loaded by Doctrine

symplify/phpstan-rules

NoFindTaggedServiceIdsCallRule

Symplify\PHPStanRules\Rules\Symfony\NoFindTaggedServiceIdsCallRule

Reports: Instead of "$this->findTaggedServiceIds()" use more reliable registerForAutoconfiguration() and tagged iterator attribute. Those work outside any configuration and avoid missed tag errors

symplify/phpstan-rules

NoGetDoctrineInControllerRule

Symplify\PHPStanRules\Rules\Symfony\NoGetDoctrineInControllerRule

Reports: Do not use $this->getDoctrine() method in controller. Use __construct(EntityManagerInterface $entityManager) instead

symplify/phpstan-rules

NoGetInCommandRule

Symplify\PHPStanRules\Rules\Symfony\NoGetInCommandRule

Reports: Do not use $this->get(Type::class) method in commands to get services. Use __construct(Type $type) instead

symplify/phpstan-rules

NoGetInControllerRule

Symplify\PHPStanRules\Rules\Symfony\NoGetInControllerRule

Reports: Do not use $this->get(Type::class) method in controller to get services. Use __construct(Type $type) instead

symplify/phpstan-rules

NoGetRepositoryOnServiceRepositoryEntityRule

Symplify\PHPStanRules\Rules\Doctrine\NoGetRepositoryOnServiceRepositoryEntityRule

Reports: Instead of calling "->getRepository(%s::class)" service locator, inject service repository "%s" via constructor and use it directly

symplify/phpstan-rules

NoGetRepositoryOutsideServiceRule

Symplify\PHPStanRules\Rules\Doctrine\NoGetRepositoryOutsideServiceRule

Reports: Instead of getting repository from EntityManager, use constructor injection and service pattern to keep code clean

symplify/phpstan-rules

NoGlobalConstRule

Symplify\PHPStanRules\Rules\NoGlobalConstRule

Reports: Global constants are forbidden. Use enum-like class list instead

symplify/phpstan-rules

NoInstanceOfStaticReflectionRule

Symplify\PHPStanRules\Rules\Rector\NoInstanceOfStaticReflectionRule

Reports: Instead of "instanceof/is_a()" use ReflectionProvider service or "(new ObjectType(<desired_type>))->isSuperTypeOf(<element_type>)" for static reflection to work

symplify/phpstan-rules

NoIntegerRefactorReturnRule

Symplify\PHPStanRules\Rules\Rector\NoIntegerRefactorReturnRule

Reports: Instead of using DONT_TRAVERSE_CHILDREN* or STOP_TRAVERSAL in refactor() method, make use of attributes. Return always node, null or REMOVE_NODE. Using traverser enums might lead to unexpected results

symplify/phpstan-rules

NoJustPropertyAssignRule

Symplify\PHPStanRules\Rules\Complexity\NoJustPropertyAssignRule

Reports: Instead of assigning service property to a variable, use the property directly

symplify/phpstan-rules

NoLeadingBackslashInNameRule

Symplify\PHPStanRules\Rules\Rector\NoLeadingBackslashInNameRule

Reports: Instead of "new Name(\'\\\\Foo\')" use "new FullyQualified(\'Foo\')"

symplify/phpstan-rules

NoListenerWithoutContractRule

Symplify\PHPStanRules\Rules\Symfony\NoListenerWithoutContractRule

Based on https://tomasvotruba.com/blog/2019/07/22/how-to-convert-listeners-to-subscribers-and-reduce-your-configs Subscribers have much better PHP support - IDE, PHPStan + Rector - than simple yaml files

Reports: There should be no listeners modified in config. Use EventSubscriberInterface contract or #[AsEventListener] attribute and native PHP instead

symplify/phpstan-rules

NoMissingVariableDimFetchRule

Symplify\PHPStanRules\Rules\Explicit\NoMissingVariableDimFetchRule

Reports: Dim fetch assign variable is missing, create it first

symplify/phpstan-rules

NoMissnamedDocTagRule

Symplify\PHPStanRules\Rules\NoMissnamedDocTagRule

symplify/phpstan-rules

NoMockObjectAndRealObjectPropertyRule

Symplify\PHPStanRules\Rules\PHPUnit\NoMockObjectAndRealObjectPropertyRule

Reports: Instead of ambiguous mock + object mix, pick single type that is more relevant

symplify/phpstan-rules

NoMockOnlyTestRule

Symplify\PHPStanRules\Rules\PHPUnit\NoMockOnlyTestRule

Reports: Test should have at least one non-mocked property, to test something

symplify/phpstan-rules

NoOnlyNullReturnInRefactorRule

Symplify\PHPStanRules\Rules\Rector\NoOnlyNullReturnInRefactorRule

Reports: The refactor() method returns always null, but it should return at least one modified node

symplify/phpstan-rules

NoParentRepositoryRule

Symplify\PHPStanRules\Rules\Doctrine\NoParentRepositoryRule

Check if class extends repository class, the entity manager should be injected via constructor instead

Reports: Extending EntityRepository is not allowed, use constructor injection and pass entity manager instead

symplify/phpstan-rules

NoPropertyNodeAssignRule

Symplify\PHPStanRules\Rules\Rector\NoPropertyNodeAssignRule

Reports: Avoid assigning a node to property to avoid object juggling, pass it as argument instead

symplify/phpstan-rules

NoProtectedClassStmtRule

Symplify\PHPStanRules\Rules\Explicit\NoProtectedClassStmtRule

Reports: Avoid protected class stmts as they yield unexpected behavior. Use clear interface contract instead

symplify/phpstan-rules

NoReferenceRule

Symplify\PHPStanRules\Rules\NoReferenceRule

Reports: Use explicit return value over magic &reference

symplify/phpstan-rules

NoRepositoryCallInDataFixtureRule

Symplify\PHPStanRules\Rules\Doctrine\NoRepositoryCallInDataFixtureRule

Reports: Refactor read-data fixtures to write-only, make use of references

symplify/phpstan-rules

NoRequiredOutsideClassRule

Symplify\PHPStanRules\Rules\Symfony\NoRequiredOutsideClassRule

Reports: Symfony #[Require]/@required should be used only in classes to avoid misuse

symplify/phpstan-rules

NoReturnSetterMethodRule

Symplify\PHPStanRules\Rules\NoReturnSetterMethodRule

Reports: Setter method cannot return anything, only set value

symplify/phpstan-rules

NoRouteTrailingSlashPathRule

Symplify\PHPStanRules\Rules\Symfony\NoRouteTrailingSlashPathRule

Reports: Avoid trailing slash in route path "%s", to prevent redirects and SEO issues

symplify/phpstan-rules

NoRoutingPrefixRule

Symplify\PHPStanRules\Rules\Symfony\NoRoutingPrefixRule

Reports: Avoid global route prefixing, to use single place for paths and improve static analysis

symplify/phpstan-rules

NoServiceAutowireDuplicateRule

Symplify\PHPStanRules\Rules\Symfony\NoServiceAutowireDuplicateRule

Reports: Service autowire() is called as duplicate of $services->defaults()->autowire(). Remove it on the service

symplify/phpstan-rules

NoServiceSameNameSetClassRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoServiceSameNameSetClassRule

Reports: No need to duplicate service class and name. Use only "$services->set(%s::class)" instead

symplify/phpstan-rules

NoSetClassServiceDuplicationRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoSetClassServiceDuplicationRule

Reports: Instead of "$services->set(%s)->class(%s)" that brings no value, use simple $services->set(%s)

symplify/phpstan-rules

NoStringInGetSubscribedEventsRule

Symplify\PHPStanRules\Rules\Symfony\NoStringInGetSubscribedEventsRule

Reports: Symfony getSubscribedEvents() method must contain only event class references, no strings

symplify/phpstan-rules

NoTestMocksRule

Symplify\PHPStanRules\Rules\PHPUnit\NoTestMocksRule

Reports: Mocking "%s" class is forbidden. Use direct/anonymous class instead for better static analysis

symplify/phpstan-rules

NoValueObjectInServiceConstructorRule

Symplify\PHPStanRules\Rules\NoValueObjectInServiceConstructorRule

Reports: Value object "%s" cannot be passed to constructor of a service. Pass it as a method argument instead

symplify/phpstan-rules

ParamNameToTypeConventionRule

Symplify\PHPStanRules\Rules\Convention\ParamNameToTypeConventionRule

Reports: Parameter name "$%s" should probably have "%s" type

symplify/phpstan-rules

PhpUpgradeDowngradeRegisteredInSetRule

Symplify\PHPStanRules\Rules\Rector\PhpUpgradeDowngradeRegisteredInSetRule

Reports: Register "%s" service to "%s" config set

symplify/phpstan-rules

PhpUpgradeImplementsMinPhpVersionInterfaceRule

Symplify\PHPStanRules\Rules\Rector\PhpUpgradeImplementsMinPhpVersionInterfaceRule

Reports: Rule %s must implements Rector\VersionBonding\Contract\MinPhpVersionInterface

symplify/phpstan-rules

PreferAutowireAttributeOverConfigParamRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\PreferAutowireAttributeOverConfigParamRule

Reports: Instead of parameter reference in config, add #[Autowire(param: ...)] in the "%s" class constructor

symplify/phpstan-rules

PreferDirectIsNameRule

Symplify\PHPStanRules\Rules\Rector\PreferDirectIsNameRule

Reports: Use direct $this->isName() instead of fetching NodeNameResolver service

symplify/phpstan-rules

PreferredClassRule

Symplify\PHPStanRules\Rules\PreferredClassRule

Reports: Instead of "%s" class/interface use "%s"

symplify/phpstan-rules

PreventParentMethodVisibilityOverrideRule

Symplify\PHPStanRules\Rules\PreventParentMethodVisibilityOverrideRule

Reports: Change "%s()" method visibility to "%s" to respect parent method visibility.

symplify/phpstan-rules

PublicStaticDataProviderRule

Symplify\PHPStanRules\Rules\PHPUnit\PublicStaticDataProviderRule

PHPUnit data provider have to be public and static

symplify/phpstan-rules

RequireAttributeNameRule

Symplify\PHPStanRules\Rules\RequireAttributeNameRule

Reports: Attribute must have all names explicitly defined

symplify/phpstan-rules

RequireAttributeNamespaceRule

Symplify\PHPStanRules\Rules\Domain\RequireAttributeNamespaceRule

Reports: Attribute must be located in "Attribute" namespace

symplify/phpstan-rules

RequireExceptionNamespaceRule

Symplify\PHPStanRules\Rules\Domain\RequireExceptionNamespaceRule

Reports: Exception must be located in "Exception" namespace

symplify/phpstan-rules

RequireInvokableControllerRule

Symplify\PHPStanRules\Rules\Symfony\RequireInvokableControllerRule

Reports: Use invokable controller with __invoke() method instead of named action method

symplify/phpstan-rules

RequireIsGrantedEnumRule

Symplify\PHPStanRules\Rules\Symfony\RequireIsGrantedEnumRule

Reports: Instead of "%s" string, use enum constant for #[IsGranted]

symplify/phpstan-rules

RequireQueryBuilderOnRepositoryRule

Symplify\PHPStanRules\Rules\Doctrine\RequireQueryBuilderOnRepositoryRule

Reports: Avoid calling ->createQueryBuilder() directly on EntityManager as it requires select() + from() calls with specific values. Use $repository->createQueryBuilder() to be safe instead

symplify/phpstan-rules

RequireRouteNameToGenerateControllerRouteRule

Symplify\PHPStanRules\Rules\Symfony\RequireRouteNameToGenerateControllerRouteRule

To pass a controller class in $this->router->generate(SomeController::class), the controller must be present #[Route(name:: self::class)

Reports: To pass a controller class to generate() method, the controller must have "#[Route(name: self::class)]" above the __invoke() method

symplify/phpstan-rules

RequireServiceRepositoryParentRule

Symplify\PHPStanRules\Rules\Doctrine\RequireServiceRepositoryParentRule

Reports: Repository must extend "%s", "%s" or implement "%s", so it can be injected as a service

symplify/phpstan-rules

RequireUniqueEnumConstantRule

Symplify\PHPStanRules\Rules\Enum\RequireUniqueEnumConstantRule

Reports: Enum constants "%s" are duplicated. Make them unique instead

symplify/phpstan-rules

RequiredOnlyInAbstractRule

Symplify\PHPStanRules\Rules\Symfony\RequiredOnlyInAbstractRule

Reports: #Symfony @required or #[Required] is reserved exclusively for abstract classes. For the rest of classes, use clean constructor injection

symplify/phpstan-rules

SeeAnnotationToTestRule

Symplify\PHPStanRules\Rules\SeeAnnotationToTestRule

Reports: Class "%s" is missing @see annotation with test case class reference

symplify/phpstan-rules

ServicesExcludedDirectoryMustExistRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\ServicesExcludedDirectoryMustExistRule

Reports: Services excluded path "%s" does not exists. You can remove it

symplify/phpstan-rules

SingleArgEventDispatchRule

Symplify\PHPStanRules\Rules\Symfony\SingleArgEventDispatchRule

Reports: The event dispatch() method can have only 1 arg - the event object

symplify/phpstan-rules

SingleRequiredMethodRule

Symplify\PHPStanRules\Rules\Symfony\SingleRequiredMethodRule

Reports: Found %d @required methods. Use only one method to avoid unexpected behavior.

symplify/phpstan-rules

StringFileAbsolutePathExistsRule

Symplify\PHPStanRules\Rules\StringFileAbsolutePathExistsRule

Reports: File "%s" could not be found. Make sure it exists

symplify/phpstan-rules

TaggedIteratorOverRepeatedServiceCallRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\TaggedIteratorOverRepeatedServiceCallRule

Reports: Instead of repeated "->call(%s, ...)" calls, pass services as tagged iterator argument to the constructor

symplify/phpstan-rules

UppercaseConstantRule

Symplify\PHPStanRules\Rules\UppercaseConstantRule

Reports: Constant "%s" must be uppercase

spaze/phpstan-disallowed-calls 38 rules Packagist

PHPStan rules to detect disallowed method & function calls, constants, namespaces, attributes, properties & superglobal usages, with powerful rules to re-allow a call or a usage in places where it should be allowed.

spaze/phpstan-disallowed-calls

AttributeUsages

Spaze\PHPStan\Rules\Disallowed\Usages\AttributeUsages

spaze/phpstan-disallowed-calls

BreakControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\BreakControlStructure

Reports on using the break control structure.

spaze/phpstan-disallowed-calls

ClassConstantUsages

Spaze\PHPStan\Rules\Disallowed\Usages\ClassConstantUsages

Reports on class constant usage.

spaze/phpstan-disallowed-calls

ConstantUsages

Spaze\PHPStan\Rules\Disallowed\Usages\ConstantUsages

Reports on constant usage.

spaze/phpstan-disallowed-calls

ContinueControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ContinueControlStructure

Reports on using the continue control structure.

spaze/phpstan-disallowed-calls

DeclareControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\DeclareControlStructure

Reports on using the declare control structure.

spaze/phpstan-disallowed-calls

DoWhileControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\DoWhileControlStructure

Reports on using the do-while loop.

spaze/phpstan-disallowed-calls

EchoCalls

Spaze\PHPStan\Rules\Disallowed\Calls\EchoCalls

Reports on dynamically calling echo().

spaze/phpstan-disallowed-calls

ElseControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ElseControlStructure

Reports on using the else control structure.

spaze/phpstan-disallowed-calls

ElseIfControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ElseIfControlStructure

Reports on using the elseif control structure. But not the "else if" as that's parsed as "else" followed by "if".

spaze/phpstan-disallowed-calls

EmptyCalls

Spaze\PHPStan\Rules\Disallowed\Calls\EmptyCalls

Reports on dynamically calling empty().

spaze/phpstan-disallowed-calls

EvalCalls

Spaze\PHPStan\Rules\Disallowed\Calls\EvalCalls

Reports on dynamically calling eval().

spaze/phpstan-disallowed-calls

ExitDieCalls

Spaze\PHPStan\Rules\Disallowed\Calls\ExitDieCalls

Reports on dynamically calling exit() & die().

spaze/phpstan-disallowed-calls

ForControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ForControlStructure

Reports on using the for loop.

spaze/phpstan-disallowed-calls

ForeachControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ForeachControlStructure

Reports on using the foreach loop.

spaze/phpstan-disallowed-calls

FunctionCalls

Spaze\PHPStan\Rules\Disallowed\Calls\FunctionCalls

Reports on dynamically calling a disallowed function.

spaze/phpstan-disallowed-calls

FunctionFirstClassCallables

Spaze\PHPStan\Rules\Disallowed\Calls\FunctionFirstClassCallables

Reports on first class callable syntax for a disallowed method.

spaze/phpstan-disallowed-calls

GlobalKeyword

Spaze\PHPStan\Rules\Disallowed\Keywords\GlobalKeyword

Reports on using the global keyword.

spaze/phpstan-disallowed-calls

GotoControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\GotoControlStructure

Reports on using the goto control structure.

spaze/phpstan-disallowed-calls

IfControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\IfControlStructure

Reports on using the if control structure.

spaze/phpstan-disallowed-calls

InstancePropertyUsages

Spaze\PHPStan\Rules\Disallowed\Usages\InstancePropertyUsages

Reports on an instance property usage.

spaze/phpstan-disallowed-calls

IssetCalls

Spaze\PHPStan\Rules\Disallowed\Calls\IssetCalls

Reports on dynamically calling isset().

spaze/phpstan-disallowed-calls

MatchControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\MatchControlStructure

Reports on using the match control structure.

spaze/phpstan-disallowed-calls

MethodCalls

Spaze\PHPStan\Rules\Disallowed\Calls\MethodCalls

Reports on dynamically calling a disallowed method or two.

spaze/phpstan-disallowed-calls

MethodFirstClassCallables

Spaze\PHPStan\Rules\Disallowed\Calls\MethodFirstClassCallables

Reports on first class callable syntax for a disallowed method.

spaze/phpstan-disallowed-calls

NamespaceUsages

Spaze\PHPStan\Rules\Disallowed\Usages\NamespaceUsages

spaze/phpstan-disallowed-calls

NewCalls

Spaze\PHPStan\Rules\Disallowed\Calls\NewCalls

Reports on creating objects (calling constructors).

spaze/phpstan-disallowed-calls

PrintCalls

Spaze\PHPStan\Rules\Disallowed\Calls\PrintCalls

Reports on dynamically calling print().

spaze/phpstan-disallowed-calls

RequireIncludeControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\RequireIncludeControlStructure

Reports on using the foreach loop.

spaze/phpstan-disallowed-calls

ReturnControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ReturnControlStructure

Reports on using the return control structure.

spaze/phpstan-disallowed-calls

ShellExecCalls

Spaze\PHPStan\Rules\Disallowed\Calls\ShellExecCalls

Reports on dynamically using the execution backtick operator (<code>`ls`</code>).

spaze/phpstan-disallowed-calls

StaticCalls

Spaze\PHPStan\Rules\Disallowed\Calls\StaticCalls

Reports on statically calling a disallowed method or two.

spaze/phpstan-disallowed-calls

StaticFirstClassCallables

Spaze\PHPStan\Rules\Disallowed\Calls\StaticFirstClassCallables

Reports on first class callable syntax for a disallowed static method.

spaze/phpstan-disallowed-calls

StaticPropertyUsages

Spaze\PHPStan\Rules\Disallowed\Usages\StaticPropertyUsages

Reports on a static property usage.

spaze/phpstan-disallowed-calls

SwitchControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\SwitchControlStructure

Reports on using the switch control structure.

spaze/phpstan-disallowed-calls

UnsetCalls

Spaze\PHPStan\Rules\Disallowed\Calls\UnsetCalls

Reports on dynamically calling unset().

spaze/phpstan-disallowed-calls

VariableUsages

Spaze\PHPStan\Rules\Disallowed\Usages\VariableUsages

Reports on a variable name usage.

spaze/phpstan-disallowed-calls

WhileControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\WhileControlStructure

Reports on using the while loop.

shipmonk/phpstan-rules 37 rules Packagist

Various extra strict PHPStan rules we found useful at ShipMonk.

shipmonk/phpstan-rules

AllowComparingOnlyComparableTypesRule

ShipMonk\PHPStan\Rule\AllowComparingOnlyComparableTypesRule

- Denies using comparison operators >,<,<=,>=,<=> over anything other than int|string|float|DateTimeInterface|BcMath\Number or same size tuples containing comparable types. Null is not allowed. - Mixing different types in those operators is also forbidden, only exception is comparing floats with integers and integers with BcMath\Number - Mainly targets to accidental comparisons of objects, enums or arrays which is valid in PHP, but very tricky

Reports: Comparison {$leftTypeDescribed} {$node->getOperatorSigil()} {$rightTypeDescribed} contains non-comparable type, only int|float|string|DateTimeInterface or comparable tuple is allowed.

✗ Wrong
function example1(Money $fee1, Money $fee2) {
    if ($fee1 > $fee2) {} // comparing objects is denied
}

new DateTime() > '2040-01-02'; // comparing different types is denied
200 > '1e2'; // comparing different types is denied
shipmonk/phpstan-rules

BackedEnumGenericsRule

ShipMonk\PHPStan\Rule\BackedEnumGenericsRule

- Ensures that every BackedEnum child defines generic type - This rule makes sense only when BackedEnum was hacked to be generic by stub as described in this article - This rule does nothing if BackedEnum is not set to be generic, which is a default setup. Use following config to really start using it:

Reports: Class {$classReflection->getName()} extends generic BackedEnum, but does not specify its type. Use @implements $expectedTag

✗ Wrong
enum MyEnum: string { // missing @implements tag
    case MyCase = 'case1';
}
shipmonk/phpstan-rules

ClassSuffixNamingRule

ShipMonk\PHPStan\Rule\ClassSuffixNamingRule

- Allows you to enforce class name suffix for subclasses of configured superclass - Checks nothing by default, configure it by passing superclass => suffix mapping - Passed superclass is not expected to have such suffix, only subclasses are - You can use interface as superclass

Reports: Class name $className should end with $suffix suffix

shipmonk/phpstan-rules

EnforceClosureParamNativeTypehintRule

ShipMonk\PHPStan\Rule\EnforceClosureParamNativeTypehintRule

- Enforces usage of native typehints for closure & arrow function parameters - Does nothing on PHP 7.4 and below as native mixed is not available there - Can be configured by allowMissingTypeWhenInferred: true to allow missing typehint when it can be inferred from the context

Reports: Missing parameter typehint for {$type} parameter \${$param->var->name}.

✗ Wrong
/**
 * @param list<Entity> $entities
 * @return list<Uuid>
 */
public function getIds(array $entities): array {
    return array_map(
        function ($entity) { // missing native typehint; not reported with allowMissingTypeWhenInferred: true
            return $entity->id;
        },
        $entities
    );
}
shipmonk/phpstan-rules

EnforceEnumMatchRule

ShipMonk\PHPStan\Rule\EnforceEnumMatchRule

- Enforces usage of match ($enum) instead of exhaustive conditions like if ($enum === Enum::One) elseif ($enum === Enum::Two) - This rule aims to "fix" a bit problematic behaviour of PHPStan (introduced at 1.10.0 and fixed in 1.10.34). It understands enum cases very well and forces you to adjust following code:

Reports: This condition contains always-$trueFalse enum comparison of $enumCases[0]. Use match expression instead, PHPStan will report unhandled enum cases

✗ Wrong
enum MyEnum {
    case Foo;
    case Bar;
}

if ($enum === MyEnum::Foo) {
    // ...
} elseif ($enum === MyEnum::Bar) { // always true reported by phpstan (for versions 1.10.0 - 1.10.34)
    // ...
} else {
    throw new LogicException('Unknown case'); // phpstan knows it cannot happen
}
✓ Correct
if ($enum === MyEnum::Foo) {
    // ...
} elseif ($enum === MyEnum::Bar) {
    // ...
}
shipmonk/phpstan-rules

EnforceIteratorToArrayPreserveKeysRule

ShipMonk\PHPStan\Rule\EnforceIteratorToArrayPreserveKeysRule

- Enforces presence of second parameter in iterator_to_array call ($preserve_keys) as the default value true is generally dangerous (risk of data loss / failure) - You can use both true and false there, but doing so is intentional choice now

Reports: Calling iterator_to_array without 2nd parameter $preserve_keys. Default value true might cause failures or data loss.

✗ Wrong
$fn = function () {
    yield new stdClass => 1;
};

iterator_to_array($fn()); // denied, would fail
shipmonk/phpstan-rules

EnforceListReturnRule

ShipMonk\PHPStan\Rule\EnforceListReturnRule

- Enforces usage of list<T> when list is always returned from a class method or function - When only single return with empty array is present in the method, it is not considered as list - Does nothing when list types are disabled in PHPStan - Consider enabling also reportAnyTypeWideningInVarTag in native PHPStan as it mostly affects lists

Reports: {$callLikeType} {$methodReflection->getName()} always return list, but is marked as {$returnTypeString}

✗ Wrong
/**
 * @return array<string>
 */
public function returnList(): array // error, return phpdoc is generic array, but list is always returned
{
    return ['item'];
}
shipmonk/phpstan-rules

EnforceNativeReturnTypehintRule

ShipMonk\PHPStan\Rule\EnforceNativeReturnTypehintRule

- Enforces usage of native return typehints if supported by your PHP version - If PHPDoc is present, it deduces needed typehint from that, if not, deduction is performed based on real types returned - Applies to class methods, closures and functions - Is disabled, if you have PHPStan set up with treatPhpDocTypesAsCertain: false - Limitations: - Does not suggest parent typehint - Ignores trait methods

Reports: Missing native return typehint %s

✗ Wrong
class NoNativeReturnTypehint {
    /**
     * @return list<string>
     */
    public function returnList() // error, missing array typehint
    {
        return ['item'];
    }
}
shipmonk/phpstan-rules

EnforceReadonlyPublicPropertyRule

ShipMonk\PHPStan\Rule\EnforceReadonlyPublicPropertyRule

- Ensures immutability of all public properties by enforcing readonly modifier - No modifier needed for readonly classes in PHP 8.2 - Does nothing if PHP version does not support readonly properties (PHP 8.0 and below) - Can be configured to exclude properties with a default value

Reports: Public property `{$node->getName()}` not marked as readonly.

✗ Wrong
class EnforceReadonlyPublicPropertyRule {
    public int $foo; // fails, no readonly modifier
    public readonly int $bar;
}
shipmonk/phpstan-rules

ForbidArithmeticOperationOnNonNumberRule

ShipMonk\PHPStan\Rule\ForbidArithmeticOperationOnNonNumberRule

- Disallows using arithmetic operators with non-numeric types (only float, int and BcMath\Number is allowed) - You can allow numeric-string by using allowNumericString: true configuration - Modulo operator (%) allows only integers as it emits deprecation otherwise - Plus operator is allowed for merging arrays - float and BcMath\Number cannot be combined as it emits deprecations

✗ Wrong
function add(string $a, string $b) {
    return $a + $b; // denied, non-numeric types are allowed
}
shipmonk/phpstan-rules

ForbidCastRule

ShipMonk\PHPStan\Rule\ForbidCastRule

- Deny casting you configure - Possible values to use: - (array) - denied by default - (object) - denied by default - (unset) - denied by default - (bool) - (int) - (string) - (float) - forbids using also (double) and (real)

Reports: Using $castString is discouraged, please avoid using that.

✗ Wrong
$empty = (array) null; // denied cast
$notEmpty = (array) 0; // denied cast
shipmonk/phpstan-rules

ForbidCheckedExceptionInCallableRule

ShipMonk\PHPStan\Rule\ForbidCheckedExceptionInCallableRule

- Denies throwing checked exception in callables (Closures, Arrow functions and First class callables) as those cannot be tracked as checked by PHPStan analysis, because it is unknown when the callable is about to be called - It is allowed to throw checked exceptions in immediately called callables (e.g. params marked by @param-immediately-invoked-callable, see docs) - It allows configuration of functions/methods, where the callable is handling all thrown exceptions and it is safe to throw anything from there; this basically makes such calls ignored by this rule - It ignores implicitly thrown Throwable - Learn more in 🇨🇿 talk about checked exceptions in general (🇺🇸 slides)

Reports: Throwing checked exception $exceptionClass in $where!

💡 If this callable is immediately called within '$usedAsArgumentOfMethodName', you should add @param-immediately-invoked-callable there. Then this error disappears and the exception will be properly propagated.

✗ Wrong
class TransactionManager {
    /**
     * @param-immediately-invoked-callable $callback
     */
    public function transactional(callable $callback): void {
        // ...
        $callback();
        // ...
    }
}

class UserEditFacade
{
    /**
     * @throws UserNotFoundException
     */
    public function updateUserEmail(UserId $userId, Email $email): void
    {
        $this->transactionManager->transactional(function () use ($userId, $email) {
            $user = $this->userRepository->get($userId); // can throw checked UserNotFoundException
            $user->updateEmail($email);
        })
    }

    public function getUpdateEmailCallback(UserId $userId, Email $email): callable
    {
        return function () use ($userId, $email) {
            $user = $this->userRepository->get($userId); // this usage is denied, it throws checked exception, but you don't know when, thus it cannot be tracked by phpstan
            $user->updateEmail($email);
        };
    }
}
shipmonk/phpstan-rules

ForbidCheckedExceptionInYieldingMethodRule

ShipMonk\PHPStan\Rule\ForbidCheckedExceptionInYieldingMethodRule

- Denies throwing checked exception within yielding methods as those exceptions are not throw upon method call, but when generator gets iterated. - This behaviour cannot be easily reflected within PHPStan exception analysis and may cause false negatives. - Make sure you have enabled checked exceptions, otherwise, this rule does nothing

Reports: Throwing checked exception $exceptionClass in yielding $functionName is denied as it gets thrown upon Generator iteration

✗ Wrong
class Provider {
    /** @throws CheckedException */
    public static function generate(): iterable
    {
        yield 1;
        throw new CheckedException(); // denied, gets thrown once iterated
    }
}
shipmonk/phpstan-rules

ForbidCustomFunctionsRule

ShipMonk\PHPStan\Rule\ForbidCustomFunctionsRule

- Allows you to easily deny some approaches within your codebase by denying classes, methods and functions - Configuration syntax is array where key is method name and value is reason used in error message - Works even with interfaces, constructors and some dynamic class/method names like $fn = 'sleep'; $fn();

✗ Wrong
new SomeClass(); // Class SomeClass is forbidden. Please use different class
(new AnotherClass())->someMethod(); // Method AnotherClass::someMethod() is forbidden. Please use anotherMethod
shipmonk/phpstan-rules

ForbidEnumInFunctionArgumentsRule

ShipMonk\PHPStan\Rule\ForbidEnumInFunctionArgumentsRule

- Guards passing native enums to native functions where it fails / produces warning or does unexpected behaviour - Most of the array manipulation functions does not work with enums as they do implicit __toString conversion inside, but that is not possible to do with enums - See test for all functions and their problems

Reports: Argument{$plural} {$wrongArgumentsString} in {$node->name->toString()}() cannot contain enum {$reason}

✗ Wrong
enum MyEnum: string {
    case MyCase = 'case1';
}

implode('', [MyEnum::MyCase]); // denied, would fail on implicit toString conversion
shipmonk/phpstan-rules

ForbidFetchOnMixedRule

ShipMonk\PHPStan\Rule\ForbidFetchOnMixedRule

- Denies constant/property fetch on unknown type. - Any property fetch assumes the caller is an object with such property and therefore, the typehint/phpdoc should be fixed. - Similar to forbidMethodCallOnMixed - Makes sense only on PHPStan level 8 or below, gets autodisabled on level 9

✗ Wrong
function example($unknown) {
    $unknown->property; // cannot fetch property on mixed
}
shipmonk/phpstan-rules

ForbidIdenticalClassComparisonRule

ShipMonk\PHPStan\Rule\ForbidIdenticalClassComparisonRule

- Denies comparing configured classes by === or !== - Default configuration contains only DateTimeInterface - You may want to add more classes from your codebase or vendor

Reports: Using {$node->getOperatorSigil()} with {$forbiddenObjectType->describe(VerbosityLevel::typeOnly())} is denied

✗ Wrong
function isEqual(DateTimeImmutable $a, DateTimeImmutable $b): bool {
    return $a === $b;  // comparing denied classes
}
shipmonk/phpstan-rules

ForbidIncrementDecrementOnNonIntegerRule

ShipMonk\PHPStan\Rule\ForbidIncrementDecrementOnNonIntegerRule

- Denies using $i++, $i--, ++$i, --$i with any non-integer - PHP itself is leading towards stricter behaviour here and soft-deprecated **some** non-integer usages in 8.3, see RFC

✗ Wrong
$value = '2e0';
$value++; // would be float(3), denied
shipmonk/phpstan-rules

ForbidMatchDefaultArmForEnumsRule

ShipMonk\PHPStan\Rule\ForbidMatchDefaultArmForEnumsRule

- Denies using default arm in match() construct when native enum is passed as subject - This rules makes sense only as a complement of native phpstan rule that guards that all enum cases are handled in match arms - As a result, you are forced to add new arm when new enum case is added. That brings up all the places in your codebase that needs new handling.

Reports: Default arm is denied for enums in match, list all values so that this case is raised when new enum case is added.

✗ Wrong
match ($enum) {
    MyEnum::Case: 1;
    default: 2; // default arm forbidden
}
shipmonk/phpstan-rules

ForbidMethodCallOnMixedRule

ShipMonk\PHPStan\Rule\ForbidMethodCallOnMixedRule

- Denies calling methods on unknown type. - Any method call assumes the caller is an object with such method and therefore, the typehint/phpdoc should be fixed. - Similar to forbidFetchOnMixed - Makes sense only on PHPStan level 8 or below, gets autodisabled on level 9

✗ Wrong
function example($unknown) {
    $unknown->call(); // cannot call method on mixed
}
shipmonk/phpstan-rules

ForbidNotNormalizedTypeRule

ShipMonk\PHPStan\Rule\ForbidNotNormalizedTypeRule

- Reports PhpDoc or native type that is not normalized, which can be: - when child and parent appears in its union or intersection - when same type appears multiple times in its union or intersection - when DNF is not used - configurable by checkDisjunctiveNormalForm - supports: - parameter typehints & @param phpdoc - return typehint & @return phpdoc - property typehint & @var phpdoc - inline @var phpdoc - @throws phpdoc - multi-catch statements - Main motivation here is that PHPStan normalizes all types before analysis, so it is better to see it in codebase the same way PHPStan does

Reports: Found non-normalized type {$multiTypeNodeString} for {$identification}: {$typeNodeBString} is a subtype of {$typeNodeAString}.

✗ Wrong
/**
 * @return mixed|false   // denied, this is still just mixed
 */
public function getAttribute(string $name)
{
    return $this->attributes[$name] ?? false;
}
shipmonk/phpstan-rules

ForbidNullInAssignOperationsRule

ShipMonk\PHPStan\Rule\ForbidNullInAssignOperationsRule

- Denies using assign operators if null is involved on right side - You can configure which operators are ignored, by default only ??= is excluded

Reports: Null value involved in {$operator} assignment on the right side.

✗ Wrong
function getCost(int $cost, ?int $surcharge): int {
    $cost += $surcharge;  // denied, adding possibly-null value
    return $cost;
}
shipmonk/phpstan-rules

ForbidNullInBinaryOperationsRule

ShipMonk\PHPStan\Rule\ForbidNullInBinaryOperationsRule

- Denies using binary operators if null is involved on either side - You can configure which operators are ignored. Default ignore is excluding only ===, !==, ?? - Following custom setup is recommended when using latest phpstan-strict-rules and allowComparingOnlyComparableTypes is enabled

Reports: Null value involved in binary operation: {$leftTypeDescribed} {$node->getOperatorSigil()} {$rightTypeDescribed}

✗ Wrong
function getFullName(?string $firstName, string $lastName): string {
    return $firstName . ' ' . $lastName; // denied, null involved in binary operation
}
shipmonk/phpstan-rules

ForbidNullInInterpolatedStringRule

ShipMonk\PHPStan\Rule\ForbidNullInInterpolatedStringRule

- Disallows using nullable expressions within double-quoted strings - This should probably comply with setup of concat operator (.) in forbidNullInBinaryOperations so if you blacklisted it there, you might want to disable this rule

Reports: Null value involved in string interpolation with

✗ Wrong
public function output(?string $name) {
    echo "Hello $name!"; // denied, possibly null value
}
shipmonk/phpstan-rules

ForbidPhpDocNullabilityMismatchWithNativeTypehintRule

ShipMonk\PHPStan\Rule\ForbidPhpDocNullabilityMismatchWithNativeTypehintRule

- Disallows having nullable native typehint while using non-nullable phpdoc - Checks @return and @param over methods and @var over properties - PHPStan itself allows using subtype of native type in phpdoc, but resolves overall type as union of those types making such phpdoc actually invalid

Reports: The $phpDocIdentification phpdoc does not contain null, but native return type does

✗ Wrong
/**
 * @param string $param
 */
public function sayHello(?string $param) {} // invalid phpdoc not containing null
shipmonk/phpstan-rules

ForbidProtectedEnumMethodRule

ShipMonk\PHPStan\Rule\ForbidProtectedEnumMethodRule

- Disallows protected method within enums as those are not extendable anyway - Ignore method declared in traits as those might be reused in regular classes

Reports: Protected methods within enum makes no sense as you cannot extend them anyway.

✗ Wrong
enum MyEnum {
    protected function isOpen(): bool {} // protected enum method denied
}
shipmonk/phpstan-rules

ForbidReturnInConstructorRule

ShipMonk\PHPStan\Rule\ForbidReturnInConstructorRule

Reports: Using return statement in constructor is forbidden to be able to check useless default values. Either create static constructors of use if-else.

shipmonk/phpstan-rules

ForbidReturnValueInYieldingMethodRule

ShipMonk\PHPStan\Rule\ForbidReturnValueInYieldingMethodRule

- Disallows returning values in yielding methods unless marked to return Generator as the value is accessible only via Generator::getReturn - To prevent misuse, this rule can be configured to even stricter mode where it reports such returns regardless of return type declared

Reports: Returned value from yielding $callType can be accessed only via Generator::getReturn, $suffix.

✗ Wrong
class Get {
    public static function oneTwoThree(): iterable { // marked as iterable, caller cannot access the return value by Generator::getReturn
        yield 1;
        yield 2;
        return 3;
    }
}

iterator_to_array(Get::oneTwoThree()); // [1, 2] - see https://3v4l.org/Leu9j
shipmonk/phpstan-rules

ForbidUnsafeArrayKeyRule

ShipMonk\PHPStan\Rule\ForbidUnsafeArrayKeyRule

- Denies non-int non-string array keys - PHP casts null, float and bool to some nearest int/string - You should rather do that intentionally and explicitly - Those types are the main difference to default PHPStan behaviour which allows using them as array keys - You can exclude reporting mixed keys via reportMixed configuration - You can exclude reporting isset($array[$invalid]) and $array[$invalid] ?? null via reportInsideIsset configuration

Reports: Array key must be integer or string, but

✗ Wrong
$taxRates = [ // denied, float key gets casted to int (causing $taxRates to contain one item)
    1.15 => 'reduced',
    1.21 => 'standard',
];
shipmonk/phpstan-rules

ForbidUnsetClassFieldRule

ShipMonk\PHPStan\Rule\ForbidUnsetClassFieldRule

- Denies calling unset over class field as it causes un-initialization, see https://3v4l.org/V8uuP - Null assignment should be used instead

Reports: Unsetting class field is forbidden as it causes un-initialization, assign null instead

✗ Wrong
function example(MyClass $class) {
    unset($class->field); // denied
}
shipmonk/phpstan-rules

ForbidUnusedClosureParametersRule

ShipMonk\PHPStan\Rule\ForbidUnusedClosureParametersRule

- Reports unused parameters in closures and arrow functions - Only reports trailing unused parameters (parameters that are unused and all parameters after them are also unused)

Reports: {$functionType} parameter \${$parameterName} is unused

✗ Wrong
fn (int $key, Item $item, string $unused) => $item->ok(); // unused parameter $unused is reported, $key not
shipmonk/phpstan-rules

ForbidUnusedExceptionRule

ShipMonk\PHPStan\Rule\ForbidUnusedExceptionRule

- Reports forgotten exception throw (created or returned from function, but not used in any way)

Reports: Method {$this->printer->prettyPrintExpr($node)} returns exception that was not used in any way.

✗ Wrong
function validate(): void {
    new Exception(); // forgotten throw
}
shipmonk/phpstan-rules

ForbidUnusedMatchResultRule

ShipMonk\PHPStan\Rule\ForbidUnusedMatchResultRule

- Reports forgotten usage of match result - Any match with at least one arm returning a value is checked

Reports: Unused match result detected, possible returns:

✗ Wrong
match ($foo) { // unused match result
    case 'foo' => 1;
}
shipmonk/phpstan-rules

ForbidUselessNullableReturnRule

ShipMonk\PHPStan\Rule\ForbidUselessNullableReturnRule

- Denies marking closure/function/method return type as nullable when null is never returned - Recommended to be used together with uselessPrivatePropertyDefaultValue

Reports: Declared return type {$declaredType->describe($verbosity)} contains null, but it is never returned. Returned types: {$returnTypeUnion->describe($verbosity)}.

✗ Wrong
public function example(int $foo): ?int { // null never returned
    if ($foo < 0) {
        return 0;
    }
    return $foo;
}
shipmonk/phpstan-rules

ForbidVariableTypeOverwritingRule

ShipMonk\PHPStan\Rule\ForbidVariableTypeOverwritingRule

- Restricts variable assignment to those that does not change its type - Array append $array[] = 1; not yet supported - Null and mixed are not taken into account, advanced phpstan types like non-empty-X are trimmed before comparison - Rule allows type generalization and type narrowing (parent <-> child)

Reports: Overwriting variable \$$variableName while changing its type from {$previousVariableType->describe(VerbosityLevel::precise())} to {$newVariableType->describe(VerbosityLevel::precise())}

✗ Wrong
function example(OrderId $id) {
    $id = $id->getStringValue(); // denied, type changed from object to string
}
shipmonk/phpstan-rules

RequirePreviousExceptionPassRule

ShipMonk\PHPStan\Rule\RequirePreviousExceptionPassRule

- Detects forgotten exception pass-as-previous when re-throwing - Checks if caught exception can be passed as argument to the call (including constructor call) in throw node inside the catch block - You may encounter false-positives in some edge-cases, where you do not want to pass exception as previous, feel free to ignore those

Reports: Exception {$exceptionName} not passed as previous to {$this->printer->prettyPrintExpr($node)}

✗ Wrong
try {
    // some code
} catch (RuntimeException $e) {
    throw new LogicException('Cannot happen'); // $e not passed as previous
}
✓ Correct
class MyException extends RuntimeException {
    public function __construct() {
        parent::__construct('My error');
    }
}

try {
    // some code
} catch (RuntimeException $e) {
    throw new MyException(); // reported even though MyException cannot accept it yet
}
shipmonk/phpstan-rules

UselessPrivatePropertyDefaultValueRule

ShipMonk\PHPStan\Rule\UselessPrivatePropertyDefaultValueRule

Reports: Property {$className}::{$propertyName} has useless default value (overwritten in constructor)

ergebnis/phpstan-rules 31 rules Packagist

Provides rules for phpstan/phpstan.

ergebnis/phpstan-rules

DeclareStrictTypesRule

Ergebnis\PHPStan\Rules\Files\DeclareStrictTypesRule

This rule reports an error when a non-empty file does not contain a declare(strict_types=1) declaration.

Reports: File is missing a "declare(strict_types=1)" declaration.

ergebnis/phpstan-rules

FinalInAbstractClassRule

Ergebnis\PHPStan\Rules\Methods\FinalInAbstractClassRule

This rule reports an error when a concrete public or protected method in an abstract class is not final.

ergebnis/phpstan-rules

FinalRule

Ergebnis\PHPStan\Rules\Classes\FinalRule

This rule reports an error when a non-anonymous class is not final.

ergebnis/phpstan-rules

InvokeParentHookMethodRule

Ergebnis\PHPStan\Rules\Methods\InvokeParentHookMethodRule

This rule reports an error when a hook method that overrides a hook method in a parent class does not invoke the overridden hook method in the expected order.

ergebnis/phpstan-rules

NoAssignByReferenceRule

Ergebnis\PHPStan\Rules\Expressions\NoAssignByReferenceRule

This rule reports an error when a variable is assigned by reference.

Reports: Assign by reference should not be used.

ergebnis/phpstan-rules

NoCompactRule

Ergebnis\PHPStan\Rules\Expressions\NoCompactRule

This rule reports an error when the function compact() is used.

Reports: Function compact() should not be used.

ergebnis/phpstan-rules

NoConstructorParameterWithDefaultValueRule

Ergebnis\PHPStan\Rules\Methods\NoConstructorParameterWithDefaultValueRule

This rule reports an error when a constructor declared in

ergebnis/phpstan-rules

NoErrorSuppressionRule

Ergebnis\PHPStan\Rules\Expressions\NoErrorSuppressionRule

This rule reports an error when @ is used to suppress errors.

Reports: Error suppression via "@" should not be used.

ergebnis/phpstan-rules

NoEvalRule

Ergebnis\PHPStan\Rules\Expressions\NoEvalRule

This rule reports an error when the language construct eval() is used.

Reports: Language construct eval() should not be used.

ergebnis/phpstan-rules

NoExtendsRule

Ergebnis\PHPStan\Rules\Classes\NoExtendsRule

This rule reports an error when a class extends another class.

ergebnis/phpstan-rules

NoIssetRule

Ergebnis\PHPStan\Rules\Expressions\NoIssetRule

This rule reports an error when the language construct isset() is used.

Reports: Language construct isset() should not be used.

ergebnis/phpstan-rules

NoNamedArgumentRule

Ergebnis\PHPStan\Rules\CallLikes\NoNamedArgumentRule

This rule reports an error when an anonymous function, a function, or a method is invoked using a named argument.

ergebnis/phpstan-rules

NoNullableReturnTypeDeclarationRule

Ergebnis\PHPStan\Rules\Closures\NoNullableReturnTypeDeclarationRule

This rule reports an error when a method declared in

Reports: Closure has a nullable return type declaration.

ergebnis/phpstan-rules

NoNullableReturnTypeDeclarationRule

Ergebnis\PHPStan\Rules\Functions\NoNullableReturnTypeDeclarationRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoNullableReturnTypeDeclarationRule

Ergebnis\PHPStan\Rules\Methods\NoNullableReturnTypeDeclarationRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoParameterPassedByReferenceRule

Ergebnis\PHPStan\Rules\Closures\NoParameterPassedByReferenceRule

This rule reports an error when a method has a parameter that is passed by reference.

ergebnis/phpstan-rules

NoParameterPassedByReferenceRule

Ergebnis\PHPStan\Rules\Functions\NoParameterPassedByReferenceRule

This rule reports an error when a method has a parameter that is passed by reference.

ergebnis/phpstan-rules

NoParameterPassedByReferenceRule

Ergebnis\PHPStan\Rules\Methods\NoParameterPassedByReferenceRule

This rule reports an error when a method has a parameter that is passed by reference.

ergebnis/phpstan-rules

NoParameterWithContainerTypeDeclarationRule

Ergebnis\PHPStan\Rules\Methods\NoParameterWithContainerTypeDeclarationRule

This rule reports an error when a method has a type declaration for a known dependency injection container or service locator.

ergebnis/phpstan-rules

NoParameterWithNullDefaultValueRule

Ergebnis\PHPStan\Rules\Closures\NoParameterWithNullDefaultValueRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoParameterWithNullDefaultValueRule

Ergebnis\PHPStan\Rules\Functions\NoParameterWithNullDefaultValueRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoParameterWithNullDefaultValueRule

Ergebnis\PHPStan\Rules\Methods\NoParameterWithNullDefaultValueRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoParameterWithNullableTypeDeclarationRule

Ergebnis\PHPStan\Rules\Closures\NoParameterWithNullableTypeDeclarationRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoParameterWithNullableTypeDeclarationRule

Ergebnis\PHPStan\Rules\Functions\NoParameterWithNullableTypeDeclarationRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoParameterWithNullableTypeDeclarationRule

Ergebnis\PHPStan\Rules\Methods\NoParameterWithNullableTypeDeclarationRule

This rule reports an error when a method declared in

ergebnis/phpstan-rules

NoPhpstanIgnoreRule

Ergebnis\PHPStan\Rules\Files\NoPhpstanIgnoreRule

This rule reports an error when a @phpstan-ignore, @phpstan-ignore-line, or @phpstan-ignore-next-line tag is used to ignore errors reported by phpstan/phpstan.

ergebnis/phpstan-rules

NoReturnByReferenceRule

Ergebnis\PHPStan\Rules\Functions\NoReturnByReferenceRule

This rule reports an error when a method returns by reference.

ergebnis/phpstan-rules

NoReturnByReferenceRule

Ergebnis\PHPStan\Rules\Methods\NoReturnByReferenceRule

This rule reports an error when a method returns by reference.

ergebnis/phpstan-rules

NoSwitchRule

Ergebnis\PHPStan\Rules\Statements\NoSwitchRule

This rule reports an error when the statement switch() is used.

Reports: Control structures using switch should not be used.

ergebnis/phpstan-rules

PrivateInFinalClassRule

Ergebnis\PHPStan\Rules\Methods\PrivateInFinalClassRule

This rule reports an error when a method in a final class is protected but could be private.

ergebnis/phpstan-rules

TestCaseWithSuffixRule

Ergebnis\PHPStan\Rules\Classes\PHPUnit\Framework\TestCaseWithSuffixRule

This rule reports an error when a concrete class is a sub-class of PHPUnit\Framework\TestCase but does not have a Test suffix.

larastan/larastan 18 rules Packagist

Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel.

larastan/larastan

CheckDispatchArgumentTypesCompatibleWithClassConstructorRule

Larastan\Larastan\Rules\CheckDispatchArgumentTypesCompatibleWithClassConstructorRule

larastan/larastan

ConfigCollectionRule

Larastan\Larastan\Rules\ConfigCollectionRule

Reports: Config key \

larastan/larastan

DeferrableServiceProviderMissingProvidesRule

Larastan\Larastan\Rules\DeferrableServiceProviderMissingProvidesRule

Reports: ServiceProviders that implement the "DeferrableProvider" interface should implement the "provides" method that returns an array of strings or class-strings

larastan/larastan

ModelAppendsRule

Larastan\Larastan\Rules\ModelAppendsRule

This rule validates that properties in the $appends array both exist in the model and are computed properties.

Reports: Property '%s' is not a computed property, remove from \$appends.

larastan/larastan

NoAuthFacadeInRequestScopeRule

Larastan\Larastan\Rules\NoAuthFacadeInRequestScopeRule

larastan/larastan

NoAuthHelperInRequestScopeRule

Larastan\Larastan\Rules\NoAuthHelperInRequestScopeRule

larastan/larastan

NoEnvCallsOutsideOfConfigRule

Larastan\Larastan\Rules\NoEnvCallsOutsideOfConfigRule

Catches `env()` calls outside of the config directory.

Reports: Called 'env' outside of the config directory which returns null when the config is cached, use 'config'.

larastan/larastan

NoMissingTranslationsRule

Larastan\Larastan\Rules\NoMissingTranslationsRule

Reports: Translation "

larastan/larastan

NoModelMakeRule

Larastan\Larastan\Rules\NoModelMakeRule

Catches inefficient instantiation of models using Model::make().

Reports: Called 'Model::make()' which performs unnecessary work, use 'new Model()'.

larastan/larastan

NoPublicModelScopeAndAccessorRule

Larastan\Larastan\Rules\NoPublicModelScopeAndAccessorRule

Reports: Local query scope method '%s' should be declared as protected.

larastan/larastan

NoUnnecessaryCollectionCallRule

Larastan\Larastan\Rules\NoUnnecessaryCollectionCallRule

This rule checks for unnecessary heavy operations on the Collection class that could have instead been performed on the Builder class.

Reports: Called '%s' on Laravel collection, but could have been retrieved as a query.

larastan/larastan

NoUnnecessaryEnumerableToArrayCallsRule

Larastan\Larastan\Rules\NoUnnecessaryEnumerableToArrayCallsRule

This rule checks for unnecessary calls `Enumerable::toArray()` that could have used `all()` instead. The `toArray()` method recursively converts all Arrayable items in the Enumerable to an array and if none of the items are Arrayable, it is unnecessary map call.

Reports: Called [toArray()] on an Enumerable which does not contain any Arrayables.

💡 Use [all()] to get the items as an array.

larastan/larastan

NoUselessValueFunctionCallsRule

Larastan\Larastan\Rules\UselessConstructs\NoUselessValueFunctionCallsRule

Reports: Calling the helper function 'value()' without a closure as the first argument simply returns the first argument without doing anything

larastan/larastan

NoUselessWithFunctionCallsRule

Larastan\Larastan\Rules\UselessConstructs\NoUselessWithFunctionCallsRule

Reports: Calling the helper function 'with()' with only one argument simply returns the value itself. If you want to chain methods on a construct, use '(new ClassName())->foo()' instead

larastan/larastan

OctaneCompatibilityRule

Larastan\Larastan\Rules\OctaneCompatibilityRule

Reports: Consider using bind method instead or pass a closure.

💡 See: https://laravel.com/docs/octane#dependency-injection-and-octane

larastan/larastan

RelationExistenceRule

Larastan\Larastan\Rules\RelationExistenceRule

Reports: Relation '%s' is not found in %s model.

larastan/larastan

UndefinedArgumentOrOptionRule

Larastan\Larastan\Rules\ConsoleCommand\UndefinedArgumentOrOptionRule

Reports: Command "%s" does not have argument "%s".

larastan/larastan

UnusedViewsRule

Larastan\Larastan\Rules\UnusedViewsRule

Reports: This view is not used in the project.

slam/phpstan-extensions 14 rules Packagist

Slam extension of phpstan.

slam/phpstan-extensions

AccessGlobalVariableWithinContextRule

SlamPhpStan\AccessGlobalVariableWithinContextRule

Reports: Class %s %s %s and uses $%s: accessing globals in this context is considered an anti-pattern

slam/phpstan-extensions

AccessStaticPropertyWithinModelContextRule

SlamPhpStan\AccessStaticPropertyWithinModelContextRule

Reports: Class %s %s %s and uses %s::$%s: accessing a singleton in this context is considered an anti-pattern

slam/phpstan-extensions

ClassNotationRule

SlamPhpStan\ClassNotationRule

slam/phpstan-extensions

GotoRule

SlamPhpStan\GotoRule

Reports: No goto, cmon!

slam/phpstan-extensions

MissingClosureParameterTypehintRule

SlamPhpStan\MissingClosureParameterTypehintRule

Reports: Parameter #%d $%s of anonymous function has no typehint.

slam/phpstan-extensions

NoDateWithoutSecondArgumentRule

SlamPhpStan\NotNow\NoDateWithoutSecondArgumentRule

Reports: Calling date() without the second parameter is forbidden, rely on a clock abstraction like lcobucci/clock

slam/phpstan-extensions

NoRelativeDateTimeInterfaceRule

SlamPhpStan\NotNow\NoRelativeDateTimeInterfaceRule

Reports: Instantiating %s without the first argument is forbidden, rely on a clock abstraction like lcobucci/clock

slam/phpstan-extensions

NoRelativeStrtotimeRule

SlamPhpStan\NotNow\NoRelativeStrtotimeRule

Reports: Calling strtotime() with relative datetime "%s" without the second argument is forbidden, rely on a clock abstraction like lcobucci/clock

slam/phpstan-extensions

NoTimeRule

SlamPhpStan\NotNow\NoTimeRule

Reports: Calling %s() directly is forbidden, rely on a clock abstraction like lcobucci/clock

slam/phpstan-extensions

PhpUnitFqcnAnnotationRule

SlamPhpStan\PhpUnitFqcnAnnotationRule

Reports: Class %s does not exist.

slam/phpstan-extensions

StringToClassRule

SlamPhpStan\StringToClassRule

Reports: Class %s should be written with ::class notation, string found.

slam/phpstan-extensions

SymfonyFilesystemRule

SlamPhpStan\SymfonyFilesystemRule

Reports: Function %s is unsafe to use, rely on Symfony component Filesystem::%s instead.

slam/phpstan-extensions

SymfonyProcessRule

SlamPhpStan\SymfonyProcessRule

Reports: Function %s is unsafe to use, rely on Symfony\Process component instead.

slam/phpstan-extensions

UnusedVariableRule

SlamPhpStan\UnusedVariableRule

Reports: %s has an unused variable $%s.

voku/phpstan-rules 13 rules Packagist

Provides additional rules for phpstan/phpstan.

voku/phpstan-rules

DisallowedCallMethodOnNullRule

voku\PHPStan\Rules\DisallowedCallMethodOnNullRule

This code is copy&pasted from [phpstan/phpstan-src] and I used it to prevent Call to a member function on null errors while I wasn't already on level 8 where all kind of "NULL" checks are already covered by default.

Reports: Call to %s %s::%s() on NULL.

voku/phpstan-rules

ElseIfConditionBasicRule

voku\PHPStan\Rules\ElseIfConditionBasicRule

voku/phpstan-rules

ExtendedAssignOpRule

voku\PHPStan\Rules\ExtendedAssignOpRule

voku/phpstan-rules

ExtendedBinaryOpRule

voku\PHPStan\Rules\ExtendedBinaryOpRule

This rule will check "+", "*", "/", "-", ... (operators) and "." (concatenation) for compatible types.

voku/phpstan-rules

IfConditionBasicRule

voku\PHPStan\Rules\IfConditionBasicRule

voku/phpstan-rules

IfConditionBooleanAndRule

voku\PHPStan\Rules\IfConditionBooleanAndRule

voku/phpstan-rules

IfConditionBooleanNotRule

voku\PHPStan\Rules\IfConditionBooleanNotRule

voku/phpstan-rules

IfConditionBooleanOrRule

voku\PHPStan\Rules\IfConditionBooleanOrRule

voku/phpstan-rules

IfConditionMatchRule

voku\PHPStan\Rules\IfConditionMatchRule

voku/phpstan-rules

IfConditionRule

voku\PHPStan\Rules\IfConditionRule

voku/phpstan-rules

IfConditionSwitchCaseRule

voku\PHPStan\Rules\IfConditionSwitchCaseRule

voku/phpstan-rules

IfConditionTernaryOperatorRule

voku\PHPStan\Rules\IfConditionTernaryOperatorRule

voku/phpstan-rules

WrongCastRule

voku\PHPStan\Rules\WrongCastRule

Reports: Casting to %s something that\

staabm/phpstan-dba 7 rules Packagist

PHPStan based SQL static analysis and type inference for the database access layer.

staabm/phpstan-dba

DoctrineKeyValueStyleRule

staabm\PHPStanDba\Rules\DoctrineKeyValueStyleRule

Reports: Argument #0 expects a constant string, got

staabm/phpstan-dba

PdoStatementExecuteMethodRule

staabm\PHPStanDba\Rules\PdoStatementExecuteMethodRule

staabm/phpstan-dba

QueryPlanAnalyzerRule

staabm\PHPStanDba\Rules\QueryPlanAnalyzerRule

Reports: Query is not using an index on table '%s'.

💡 see Mysql Docs https://dev.mysql.com/doc/refman/8.0/en/select-optimization.html

staabm/phpstan-dba

SyntaxErrorInDibiPreparedStatementMethodRule

staabm\PHPStanDba\Rules\SyntaxErrorInDibiPreparedStatementMethodRule

Reports: fetchPairs requires exactly 2 selected columns, got

staabm/phpstan-dba

SyntaxErrorInPreparedStatementMethodRule

staabm\PHPStanDba\Rules\SyntaxErrorInPreparedStatementMethodRule

staabm/phpstan-dba

SyntaxErrorInQueryFunctionRule

staabm\PHPStanDba\Rules\SyntaxErrorInQueryFunctionRule

staabm/phpstan-dba

SyntaxErrorInQueryMethodRule

staabm\PHPStanDba\Rules\SyntaxErrorInQueryMethodRule

tomasvotruba/type-coverage 5 rules Packagist

Measure type coverage of your project.

tomasvotruba/type-coverage

ConstantTypeCoverageRule

TomasVotruba\TypeCoverage\Rules\ConstantTypeCoverageRule

Reports: Out of %d possible constant types, only %d - %.1f %% actually have it. Add more constant types to get over %s %%

tomasvotruba/type-coverage

DeclareCoverageRule

TomasVotruba\TypeCoverage\Rules\DeclareCoverageRule

Reports: Out of %d possible declare(strict_types=1), only %d - %.1f %% actually have it. Add more declares to get over %s %%

tomasvotruba/type-coverage

ParamTypeCoverageRule

TomasVotruba\TypeCoverage\Rules\ParamTypeCoverageRule

Reports: Out of %d possible param types, only %d - %.1f %% actually have it. Add more param types to get over %s %%

tomasvotruba/type-coverage

PropertyTypeCoverageRule

TomasVotruba\TypeCoverage\Rules\PropertyTypeCoverageRule

Reports: Out of %d possible property types, only %d - %.1f %% actually have it. Add more property types to get over %s %%

tomasvotruba/type-coverage

ReturnTypeCoverageRule

TomasVotruba\TypeCoverage\Rules\ReturnTypeCoverageRule

Reports: Out of %d possible return types, only %d - %.1f %% actually have it. Add more return types to get over %s %%

tomasvotruba/unused-public 5 rules Packagist

Detect unused public properties, constants and methods in your code.

tomasvotruba/unused-public

LocalOnlyPublicClassMethodRule

TomasVotruba\UnusedPublic\Rules\LocalOnlyPublicClassMethodRule

Reports: Public method "%s::%s()" is used only locally and should be turned protected/private

tomasvotruba/unused-public

RelativeUnusedPublicClassMethodRule

TomasVotruba\UnusedPublic\Rules\RelativeUnusedPublicClassMethodRule

Reports: Found %.1f %% of public methods as unused. Reduce it under %.1f %%

tomasvotruba/unused-public

UnusedPublicClassConstRule

TomasVotruba\UnusedPublic\Rules\UnusedPublicClassConstRule

Reports: Public constant "%s::%s" is never used

tomasvotruba/unused-public

UnusedPublicClassMethodRule

TomasVotruba\UnusedPublic\Rules\UnusedPublicClassMethodRule

Reports: Public method "%s::%s()" is never used

tomasvotruba/unused-public

UnusedPublicPropertyRule

TomasVotruba\UnusedPublic\Rules\UnusedPublicPropertyRule

Reports: Public property "%s::$%s" is never used

tomasvotruba/cognitive-complexity 3 rules Packagist

PHPStan rules to measure cognitive complexity of your classes and methods.

tomasvotruba/cognitive-complexity

ClassDependencyTreeRule

TomasVotruba\CognitiveComplexity\Rules\ClassDependencyTreeRule

Find classes with complex constructor dependency tree = current class complexity + complexity of all __construct() dependencies.

Reports: Dependency tree complexity %d is over %d. Refactor __construct() dependencies or split up.

tomasvotruba/cognitive-complexity

ClassLikeCognitiveComplexityRule

TomasVotruba\CognitiveComplexity\Rules\ClassLikeCognitiveComplexityRule

Reports: Class cognitive complexity is %d, keep it under %d

tomasvotruba/cognitive-complexity

FunctionLikeCognitiveComplexityRule

TomasVotruba\CognitiveComplexity\Rules\FunctionLikeCognitiveComplexityRule

Based on https://www.sonarsource.com/docs/CognitiveComplexity.pdf

Reports: Cognitive complexity for "%s" is %d, keep it under %d