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 2 days ago

symplify/phpstan-rules 92 rules Packagist

Set of Symplify rules for PHPStan.

AlreadyRegisteredAutodiscoveryServiceRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\AlreadyRegisteredAutodiscoveryServiceRule

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

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.

CheckRequiredInterfaceInContractNamespaceRule

Symplify\PHPStanRules\Rules\CheckRequiredInterfaceInContractNamespaceRule

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

ClassNameRespectsParentSuffixRule

Symplify\PHPStanRules\Rules\ClassNameRespectsParentSuffixRule

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

ExplicitClassPrefixSuffixRule

Symplify\PHPStanRules\Rules\Explicit\ExplicitClassPrefixSuffixRule

ExplicitExpectsMockMethodRule

Symplify\PHPStanRules\Rules\PHPUnit\ExplicitExpectsMockMethodRule

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

FileNameMatchesExtensionRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\FileNameMatchesExtensionRule

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

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

ForbiddenExtendOfNonAbstractClassRule

Symplify\PHPStanRules\Rules\ForbiddenExtendOfNonAbstractClassRule

Reports: Only abstract classes can be extended

ForbiddenFuncCallRule

Symplify\PHPStanRules\Rules\ForbiddenFuncCallRule

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

ForbiddenMultipleClassLikeInOneFileRule

Symplify\PHPStanRules\Rules\ForbiddenMultipleClassLikeInOneFileRule

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

ForbiddenNewArgumentRule

Symplify\PHPStanRules\Rules\Complexity\ForbiddenNewArgumentRule

ForbiddenNodeRule

Symplify\PHPStanRules\Rules\ForbiddenNodeRule

Reports: "%s" is forbidden to use

ForbiddenStaticClassConstFetchRule

Symplify\PHPStanRules\Rules\ForbiddenStaticClassConstFetchRule

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

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

FormTypeClassNameRule

Symplify\PHPStanRules\Rules\Symfony\FormTypeClassNameRule

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

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.

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

NoArrayMapWithArrayCallableRule

Symplify\PHPStanRules\Rules\Complexity\NoArrayMapWithArrayCallableRule

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

NoAssertFuncCallInTestsRule

Symplify\PHPStanRules\Rules\PHPUnit\NoAssertFuncCallInTestsRule

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

NoBareAndSecurityIsGrantedContentsRule

Symplify\PHPStanRules\Rules\Symfony\NoBareAndSecurityIsGrantedContentsRule

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

NoBundleResourceConfigRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoBundleResourceConfigRule

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

NoClassLevelRouteRule

Symplify\PHPStanRules\Rules\Symfony\NoClassLevelRouteRule

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

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

NoConstructorAndRequiredTogetherRule

Symplify\PHPStanRules\Rules\Symfony\NoConstructorAndRequiredTogetherRule

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

NoConstructorOverrideRule

Symplify\PHPStanRules\Rules\Complexity\NoConstructorOverrideRule

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

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

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

NoDocumentMockingRule

Symplify\PHPStanRules\Rules\Doctrine\NoDocumentMockingRule

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

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.

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

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

NoDynamicNameRule

Symplify\PHPStanRules\Rules\NoDynamicNameRule

Reports: Use explicit names over dynamic ones

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

NoEntityOutsideEntityNamespaceRule

Symplify\PHPStanRules\Rules\NoEntityOutsideEntityNamespaceRule

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

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

NoGetDoctrineInControllerRule

Symplify\PHPStanRules\Rules\Symfony\NoGetDoctrineInControllerRule

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

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

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

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

NoGetRepositoryOutsideServiceRule

Symplify\PHPStanRules\Rules\Doctrine\NoGetRepositoryOutsideServiceRule

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

NoGlobalConstRule

Symplify\PHPStanRules\Rules\NoGlobalConstRule

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

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

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

NoJustPropertyAssignRule

Symplify\PHPStanRules\Rules\Complexity\NoJustPropertyAssignRule

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

NoLeadingBackslashInNameRule

Symplify\PHPStanRules\Rules\Rector\NoLeadingBackslashInNameRule

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

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

NoMissingVariableDimFetchRule

Symplify\PHPStanRules\Rules\Explicit\NoMissingVariableDimFetchRule

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

NoMissnamedDocTagRule

Symplify\PHPStanRules\Rules\NoMissnamedDocTagRule

NoMockObjectAndRealObjectPropertyRule

Symplify\PHPStanRules\Rules\PHPUnit\NoMockObjectAndRealObjectPropertyRule

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

NoMockOnlyTestRule

Symplify\PHPStanRules\Rules\PHPUnit\NoMockOnlyTestRule

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

NoOnlyNullReturnInRefactorRule

Symplify\PHPStanRules\Rules\Rector\NoOnlyNullReturnInRefactorRule

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

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

NoPropertyNodeAssignRule

Symplify\PHPStanRules\Rules\Rector\NoPropertyNodeAssignRule

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

NoProtectedClassStmtRule

Symplify\PHPStanRules\Rules\Explicit\NoProtectedClassStmtRule

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

NoReferenceRule

Symplify\PHPStanRules\Rules\NoReferenceRule

Reports: Use explicit return value over magic &reference

NoRepositoryCallInDataFixtureRule

Symplify\PHPStanRules\Rules\Doctrine\NoRepositoryCallInDataFixtureRule

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

NoRequiredOutsideClassRule

Symplify\PHPStanRules\Rules\Symfony\NoRequiredOutsideClassRule

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

NoReturnSetterMethodRule

Symplify\PHPStanRules\Rules\NoReturnSetterMethodRule

Reports: Setter method cannot return anything, only set value

NoRouteTrailingSlashPathRule

Symplify\PHPStanRules\Rules\Symfony\NoRouteTrailingSlashPathRule

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

NoRoutingPrefixRule

Symplify\PHPStanRules\Rules\Symfony\NoRoutingPrefixRule

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

NoServiceAutowireDuplicateRule

Symplify\PHPStanRules\Rules\Symfony\NoServiceAutowireDuplicateRule

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

NoServiceSameNameSetClassRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoServiceSameNameSetClassRule

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

NoSetClassServiceDuplicationRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\NoSetClassServiceDuplicationRule

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

NoStringInGetSubscribedEventsRule

Symplify\PHPStanRules\Rules\Symfony\NoStringInGetSubscribedEventsRule

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

NoTestMocksRule

Symplify\PHPStanRules\Rules\PHPUnit\NoTestMocksRule

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

NoValueObjectInServiceConstructorRule

Symplify\PHPStanRules\Rules\NoValueObjectInServiceConstructorRule

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

ParamNameToTypeConventionRule

Symplify\PHPStanRules\Rules\Convention\ParamNameToTypeConventionRule

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

PhpUpgradeDowngradeRegisteredInSetRule

Symplify\PHPStanRules\Rules\Rector\PhpUpgradeDowngradeRegisteredInSetRule

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

PhpUpgradeImplementsMinPhpVersionInterfaceRule

Symplify\PHPStanRules\Rules\Rector\PhpUpgradeImplementsMinPhpVersionInterfaceRule

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

PreferAutowireAttributeOverConfigParamRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\PreferAutowireAttributeOverConfigParamRule

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

PreferDirectIsNameRule

Symplify\PHPStanRules\Rules\Rector\PreferDirectIsNameRule

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

PreferredClassRule

Symplify\PHPStanRules\Rules\PreferredClassRule

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

PreventParentMethodVisibilityOverrideRule

Symplify\PHPStanRules\Rules\PreventParentMethodVisibilityOverrideRule

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

PublicStaticDataProviderRule

Symplify\PHPStanRules\Rules\PHPUnit\PublicStaticDataProviderRule

PHPUnit data provider have to be public and static

RequireAttributeNameRule

Symplify\PHPStanRules\Rules\RequireAttributeNameRule

Reports: Attribute must have all names explicitly defined

RequireAttributeNamespaceRule

Symplify\PHPStanRules\Rules\Domain\RequireAttributeNamespaceRule

Reports: Attribute must be located in "Attribute" namespace

RequireExceptionNamespaceRule

Symplify\PHPStanRules\Rules\Domain\RequireExceptionNamespaceRule

Reports: Exception must be located in "Exception" namespace

RequireInvokableControllerRule

Symplify\PHPStanRules\Rules\Symfony\RequireInvokableControllerRule

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

RequireIsGrantedEnumRule

Symplify\PHPStanRules\Rules\Symfony\RequireIsGrantedEnumRule

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

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

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

RequireServiceRepositoryParentRule

Symplify\PHPStanRules\Rules\Doctrine\RequireServiceRepositoryParentRule

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

RequireUniqueEnumConstantRule

Symplify\PHPStanRules\Rules\Enum\RequireUniqueEnumConstantRule

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

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

SeeAnnotationToTestRule

Symplify\PHPStanRules\Rules\SeeAnnotationToTestRule

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

ServicesExcludedDirectoryMustExistRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\ServicesExcludedDirectoryMustExistRule

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

SingleArgEventDispatchRule

Symplify\PHPStanRules\Rules\Symfony\SingleArgEventDispatchRule

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

SingleRequiredMethodRule

Symplify\PHPStanRules\Rules\Symfony\SingleRequiredMethodRule

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

StringFileAbsolutePathExistsRule

Symplify\PHPStanRules\Rules\StringFileAbsolutePathExistsRule

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

TaggedIteratorOverRepeatedServiceCallRule

Symplify\PHPStanRules\Rules\Symfony\ConfigClosure\TaggedIteratorOverRepeatedServiceCallRule

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

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.

AttributeUsages

Spaze\PHPStan\Rules\Disallowed\Usages\AttributeUsages

BreakControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\BreakControlStructure

Reports on using the break control structure.

ClassConstantUsages

Spaze\PHPStan\Rules\Disallowed\Usages\ClassConstantUsages

Reports on class constant usage.

ConstantUsages

Spaze\PHPStan\Rules\Disallowed\Usages\ConstantUsages

Reports on constant usage.

ContinueControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ContinueControlStructure

Reports on using the continue control structure.

DeclareControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\DeclareControlStructure

Reports on using the declare control structure.

DoWhileControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\DoWhileControlStructure

Reports on using the do-while loop.

EchoCalls

Spaze\PHPStan\Rules\Disallowed\Calls\EchoCalls

Reports on dynamically calling echo().

ElseControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ElseControlStructure

Reports on using the else control structure.

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".

EmptyCalls

Spaze\PHPStan\Rules\Disallowed\Calls\EmptyCalls

Reports on dynamically calling empty().

EvalCalls

Spaze\PHPStan\Rules\Disallowed\Calls\EvalCalls

Reports on dynamically calling eval().

ExitDieCalls

Spaze\PHPStan\Rules\Disallowed\Calls\ExitDieCalls

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

ForControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ForControlStructure

Reports on using the for loop.

ForeachControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ForeachControlStructure

Reports on using the foreach loop.

FunctionCalls

Spaze\PHPStan\Rules\Disallowed\Calls\FunctionCalls

Reports on dynamically calling a disallowed function.

FunctionFirstClassCallables

Spaze\PHPStan\Rules\Disallowed\Calls\FunctionFirstClassCallables

Reports on first class callable syntax for a disallowed method.

GlobalKeyword

Spaze\PHPStan\Rules\Disallowed\Keywords\GlobalKeyword

Reports on using the global keyword.

GotoControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\GotoControlStructure

Reports on using the goto control structure.

IfControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\IfControlStructure

Reports on using the if control structure.

InstancePropertyUsages

Spaze\PHPStan\Rules\Disallowed\Usages\InstancePropertyUsages

Reports on an instance property usage.

IssetCalls

Spaze\PHPStan\Rules\Disallowed\Calls\IssetCalls

Reports on dynamically calling isset().

MatchControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\MatchControlStructure

Reports on using the match control structure.

MethodCalls

Spaze\PHPStan\Rules\Disallowed\Calls\MethodCalls

Reports on dynamically calling a disallowed method or two.

MethodFirstClassCallables

Spaze\PHPStan\Rules\Disallowed\Calls\MethodFirstClassCallables

Reports on first class callable syntax for a disallowed method.

NamespaceUsages

Spaze\PHPStan\Rules\Disallowed\Usages\NamespaceUsages

NewCalls

Spaze\PHPStan\Rules\Disallowed\Calls\NewCalls

Reports on creating objects (calling constructors).

PrintCalls

Spaze\PHPStan\Rules\Disallowed\Calls\PrintCalls

Reports on dynamically calling print().

RequireIncludeControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\RequireIncludeControlStructure

Reports on using the foreach loop.

ReturnControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\ReturnControlStructure

Reports on using the return control structure.

ShellExecCalls

Spaze\PHPStan\Rules\Disallowed\Calls\ShellExecCalls

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

StaticCalls

Spaze\PHPStan\Rules\Disallowed\Calls\StaticCalls

Reports on statically calling a disallowed method or two.

StaticFirstClassCallables

Spaze\PHPStan\Rules\Disallowed\Calls\StaticFirstClassCallables

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

StaticPropertyUsages

Spaze\PHPStan\Rules\Disallowed\Usages\StaticPropertyUsages

Reports on a static property usage.

SwitchControlStructure

Spaze\PHPStan\Rules\Disallowed\ControlStructures\SwitchControlStructure

Reports on using the switch control structure.

UnsetCalls

Spaze\PHPStan\Rules\Disallowed\Calls\UnsetCalls

Reports on dynamically calling unset().

VariableUsages

Spaze\PHPStan\Rules\Disallowed\Usages\VariableUsages

Reports on a variable name usage.

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.

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

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';
}

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

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
    );
}

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) {
    // ...
}

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

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'];
}

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'];
    }
}

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;
}

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
}

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

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);
        };
    }
}

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
    }
}

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

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

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
}

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
}

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

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
}

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
}

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;
}

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;
}

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
}

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
}

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

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
}

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.

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

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',
];

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
}

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

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
}

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;
}

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;
}

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
}

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
}

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.

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.

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.

FinalRule

Ergebnis\PHPStan\Rules\Classes\FinalRule

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

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.

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.

NoCompactRule

Ergebnis\PHPStan\Rules\Expressions\NoCompactRule

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

Reports: Function compact() should not be used.

NoConstructorParameterWithDefaultValueRule

Ergebnis\PHPStan\Rules\Methods\NoConstructorParameterWithDefaultValueRule

This rule reports an error when a constructor declared in

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.

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.

NoExtendsRule

Ergebnis\PHPStan\Rules\Classes\NoExtendsRule

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

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.

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.

NoNullableReturnTypeDeclarationRule

Ergebnis\PHPStan\Rules\Closures\NoNullableReturnTypeDeclarationRule

This rule reports an error when a method declared in

Reports: Closure has a nullable return type declaration.

NoNullableReturnTypeDeclarationRule

Ergebnis\PHPStan\Rules\Functions\NoNullableReturnTypeDeclarationRule

This rule reports an error when a method declared in

NoNullableReturnTypeDeclarationRule

Ergebnis\PHPStan\Rules\Methods\NoNullableReturnTypeDeclarationRule

This rule reports an error when a method declared in

NoParameterPassedByReferenceRule

Ergebnis\PHPStan\Rules\Closures\NoParameterPassedByReferenceRule

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

NoParameterPassedByReferenceRule

Ergebnis\PHPStan\Rules\Functions\NoParameterPassedByReferenceRule

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

NoParameterPassedByReferenceRule

Ergebnis\PHPStan\Rules\Methods\NoParameterPassedByReferenceRule

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

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.

NoParameterWithNullDefaultValueRule

Ergebnis\PHPStan\Rules\Closures\NoParameterWithNullDefaultValueRule

This rule reports an error when a method declared in

NoParameterWithNullDefaultValueRule

Ergebnis\PHPStan\Rules\Functions\NoParameterWithNullDefaultValueRule

This rule reports an error when a method declared in

NoParameterWithNullDefaultValueRule

Ergebnis\PHPStan\Rules\Methods\NoParameterWithNullDefaultValueRule

This rule reports an error when a method declared in

NoParameterWithNullableTypeDeclarationRule

Ergebnis\PHPStan\Rules\Closures\NoParameterWithNullableTypeDeclarationRule

This rule reports an error when a method declared in

NoParameterWithNullableTypeDeclarationRule

Ergebnis\PHPStan\Rules\Functions\NoParameterWithNullableTypeDeclarationRule

This rule reports an error when a method declared in

NoParameterWithNullableTypeDeclarationRule

Ergebnis\PHPStan\Rules\Methods\NoParameterWithNullableTypeDeclarationRule

This rule reports an error when a method declared in

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.

NoReturnByReferenceRule

Ergebnis\PHPStan\Rules\Functions\NoReturnByReferenceRule

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

NoReturnByReferenceRule

Ergebnis\PHPStan\Rules\Methods\NoReturnByReferenceRule

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

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.

PrivateInFinalClassRule

Ergebnis\PHPStan\Rules\Methods\PrivateInFinalClassRule

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

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.

CheckDispatchArgumentTypesCompatibleWithClassConstructorRule

Larastan\Larastan\Rules\CheckDispatchArgumentTypesCompatibleWithClassConstructorRule

ConfigCollectionRule

Larastan\Larastan\Rules\ConfigCollectionRule

Reports: Config key \

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

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.

NoAuthFacadeInRequestScopeRule

Larastan\Larastan\Rules\NoAuthFacadeInRequestScopeRule

NoAuthHelperInRequestScopeRule

Larastan\Larastan\Rules\NoAuthHelperInRequestScopeRule

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'.

NoMissingTranslationsRule

Larastan\Larastan\Rules\NoMissingTranslationsRule

Reports: Translation "

NoModelMakeRule

Larastan\Larastan\Rules\NoModelMakeRule

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

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

NoPublicModelScopeAndAccessorRule

Larastan\Larastan\Rules\NoPublicModelScopeAndAccessorRule

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

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.

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.

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

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

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

RelationExistenceRule

Larastan\Larastan\Rules\RelationExistenceRule

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

UndefinedArgumentOrOptionRule

Larastan\Larastan\Rules\ConsoleCommand\UndefinedArgumentOrOptionRule

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

UnusedViewsRule

Larastan\Larastan\Rules\UnusedViewsRule

Reports: This view is not used in the project.

slam/phpstan-extensions 14 rules Packagist

Slam extension of phpstan.

AccessGlobalVariableWithinContextRule

SlamPhpStan\AccessGlobalVariableWithinContextRule

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

AccessStaticPropertyWithinModelContextRule

SlamPhpStan\AccessStaticPropertyWithinModelContextRule

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

ClassNotationRule

SlamPhpStan\ClassNotationRule

GotoRule

SlamPhpStan\GotoRule

Reports: No goto, cmon!

MissingClosureParameterTypehintRule

SlamPhpStan\MissingClosureParameterTypehintRule

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

NoDateWithoutSecondArgumentRule

SlamPhpStan\NotNow\NoDateWithoutSecondArgumentRule

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

NoRelativeDateTimeInterfaceRule

SlamPhpStan\NotNow\NoRelativeDateTimeInterfaceRule

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

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

NoTimeRule

SlamPhpStan\NotNow\NoTimeRule

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

PhpUnitFqcnAnnotationRule

SlamPhpStan\PhpUnitFqcnAnnotationRule

Reports: Class %s does not exist.

StringToClassRule

SlamPhpStan\StringToClassRule

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

SymfonyFilesystemRule

SlamPhpStan\SymfonyFilesystemRule

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

SymfonyProcessRule

SlamPhpStan\SymfonyProcessRule

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

UnusedVariableRule

SlamPhpStan\UnusedVariableRule

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

voku/phpstan-rules 13 rules Packagist

Provides additional rules for phpstan/phpstan.

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.

ElseIfConditionBasicRule

voku\PHPStan\Rules\ElseIfConditionBasicRule

ExtendedAssignOpRule

voku\PHPStan\Rules\ExtendedAssignOpRule

ExtendedBinaryOpRule

voku\PHPStan\Rules\ExtendedBinaryOpRule

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

IfConditionBasicRule

voku\PHPStan\Rules\IfConditionBasicRule

IfConditionBooleanAndRule

voku\PHPStan\Rules\IfConditionBooleanAndRule

IfConditionBooleanNotRule

voku\PHPStan\Rules\IfConditionBooleanNotRule

IfConditionBooleanOrRule

voku\PHPStan\Rules\IfConditionBooleanOrRule

IfConditionMatchRule

voku\PHPStan\Rules\IfConditionMatchRule

IfConditionRule

voku\PHPStan\Rules\IfConditionRule

IfConditionSwitchCaseRule

voku\PHPStan\Rules\IfConditionSwitchCaseRule

IfConditionTernaryOperatorRule

voku\PHPStan\Rules\IfConditionTernaryOperatorRule

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.

DoctrineKeyValueStyleRule

staabm\PHPStanDba\Rules\DoctrineKeyValueStyleRule

Reports: Argument #0 expects a constant string, got

PdoStatementExecuteMethodRule

staabm\PHPStanDba\Rules\PdoStatementExecuteMethodRule

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

SyntaxErrorInDibiPreparedStatementMethodRule

staabm\PHPStanDba\Rules\SyntaxErrorInDibiPreparedStatementMethodRule

Reports: fetchPairs requires exactly 2 selected columns, got

SyntaxErrorInPreparedStatementMethodRule

staabm\PHPStanDba\Rules\SyntaxErrorInPreparedStatementMethodRule

SyntaxErrorInQueryFunctionRule

staabm\PHPStanDba\Rules\SyntaxErrorInQueryFunctionRule

SyntaxErrorInQueryMethodRule

staabm\PHPStanDba\Rules\SyntaxErrorInQueryMethodRule

tomasvotruba/type-coverage 5 rules Packagist

Measure type coverage of your project.

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 %%

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 %%

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 %%

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 %%

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.

LocalOnlyPublicClassMethodRule

TomasVotruba\UnusedPublic\Rules\LocalOnlyPublicClassMethodRule

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

RelativeUnusedPublicClassMethodRule

TomasVotruba\UnusedPublic\Rules\RelativeUnusedPublicClassMethodRule

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

UnusedPublicClassConstRule

TomasVotruba\UnusedPublic\Rules\UnusedPublicClassConstRule

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

UnusedPublicClassMethodRule

TomasVotruba\UnusedPublic\Rules\UnusedPublicClassMethodRule

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

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.

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.

ClassLikeCognitiveComplexityRule

TomasVotruba\CognitiveComplexity\Rules\ClassLikeCognitiveComplexityRule

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

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