Download the PHP package mspirkov/yii2-phpstan-rules without Composer
On this page you can find all versions of the php package mspirkov/yii2-phpstan-rules. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download mspirkov/yii2-phpstan-rules
More information about mspirkov/yii2-phpstan-rules
Files in mspirkov/yii2-phpstan-rules
Package yii2-phpstan-rules
Short Description PHPStan rules and type extensions for projects using the Yii2 framework
License MIT
Informations about the package yii2-phpstan-rules
PHPStan rules and type extensions for Yii2. The rules check the config arrays and names that Yii2 only resolves at runtime, and keep business logic and database access out of controllers and views. The type extensions resolve types that Yii only knows at runtime, such as the class behind a DI container ID or the methods of an attached behavior. The rules are my own conventions, not a standard: use what's useful and disable the rest.
Support
If you like this project, give it a ⭐ on GitHub — it helps others discover it.
Installation
[!IMPORTANT]
The newer your PHP, Yii2 and PHPStan, the more accurate the analysis.
With phpstan/extension-installer, the package is enabled automatically. Otherwise, include it in phpstan.neon:
Upgrading
See UPGRADE.md to upgrade between versions or from mspirkov/yii2-phpstan-rules, the package's former name.
Supported extensions
The classes of yiisoft/yii2-mongodb and yiisoft/yii2-redis are treated like those of yii\db, except by activeQueryWithValidation, which skips them. behaviorAttributesValidation also checks DateTimeBehavior from mspirkov/yii2-db.
Configuration
All parameters go under parameters.mspirkovYii2. Relative paths are resolved from the directory PHPStan runs in.
Enabling rules
All rules are on by default. enableAllRules switches all of them, enableValidationRules the validation rules (it defaults to enableAllRules), and enabled a single rule:
Application configs
The yii2-app-advanced:
Yii::$app types
yiiAppTypes sets the type of Yii::$app for the code in the paths of an entry, matched as in applicationConfigs. type is a PHPDoc type, the one Yii declares when omitted, and nullable: false removes null from it. For yii2-app-advanced:
Views
How the view existence rules resolve view names:
Rule options
Type extensions
The type extensions resolve types that Yii only knows at runtime. Those that read the application config are set up in Yii::$app types.
Container::get() return type
Resolves a string ID from container.definitions or container.singletons to the class its definition names. An ID that is a class or an interface keeps that type.
Yii::$app type
Gives Yii::$app the type set in yii2-app-advanced example from there:
Yii::$app components
Resolves Yii::$app->payments and Yii::$app->get('payments') to the class set in components, and the identity of the user component to its identityClass.
Yii::$app->params
Resolves to an array shape of params, with the values generalized to types.
Attached behaviors
Makes the methods and properties of the behaviors attached by attachBehavior() / attachBehaviors() available on the component until detachBehavior() / detachBehaviors().
Environment constants
Types YII_DEBUG, YII_ENV_DEV, YII_ENV_PROD and YII_ENV_TEST as bool and YII_ENV as string instead of the values defined in bootstrapFiles, so code for other environments isn't reported as always true or false.
Rules at a glance
Validation rules
Check the config arrays and names (attributes, relations, actions, views) that Yii2 only resolves at runtime.
| Rule | Catches |
|---|---|
activeFormFieldValidation |
Missing, read-only and write-only attributes in ActiveForm::field() |
activeQueryWithValidation |
Unknown relations in with() / joinWith() / innerJoinWith() |
activeRecordConditionValidation |
Unknown attributes and mistyped values in findOne() / findAll() / deleteAll() / updateAll() / updateAllCounters() conditions |
activeRecordRelationValidation |
Unknown attributes in hasOne() / hasMany() links |
activeRecordUpdateValuesValidation |
Unknown attributes and mistyped values in updateAll() / updateAllCounters() values |
baseObjectInstantiationValidation |
Unknown and mistyped options in the $config of new on a BaseObject |
behaviorAttributesValidation |
Unknown attributes in the options of TimestampBehavior, SluggableBehavior and other attribute behaviors |
componentBehaviorsValidation |
Non-behavior classes and unknown or mistyped options in behaviors() |
controllerActionsValidation |
Non-action classes and unknown or mistyped options in actions() |
controllerBehaviorActionsValidation |
Unknown actions in the filters of controller behaviors() |
controllerViewExistenceValidation |
Missing views in controller render() / renderPartial() / renderAjax() |
htmlActiveAttributeValidation |
Unknown attributes in Html::active*() |
modelAttributeHintsValidation |
Unknown and empty attributes in attributeHints() |
modelAttributeLabelsValidation |
Unknown and empty attributes in attributeLabels() |
modelRulesValidation |
Unknown validators, options and attributes, missing required options and invalid regexes in rules() |
modelScenariosValidation |
Empty names, non-array attribute lists and unknown attributes in scenarios() |
nestedViewExistenceValidation |
Missing views in $this->render() in views |
queryConditionValidation |
Wrong operand counts in where() / andWhere() / orWhere() operator conditions |
uploadedFileInstanceValidation |
Unknown attributes in UploadedFile::getInstance() / getInstances() |
viewRenderExistenceValidation |
Missing views in View::render() outside views |
widgetPropertiesValidation |
Unknown and mistyped options in Widget::begin() / Widget::widget() |
yiiCreateObjectValidation |
Missing class and unknown or mistyped options in Yii::createObject() |
Code quality rules
Keep business logic and database access out of controllers and views, and catch superglobals, dynamic SQL, Yii::$app used as a service locator, and redundant calls.
| Rule | Catches |
|---|---|
noComplexActionClasses |
Action classes with too much branching and looping |
noComplexControllerActions |
Controller actions with too much branching and looping |
noControllerActionCallsViaThis |
$this->actionFoo() in controllers |
noDbQueriesInActions |
Database access in Action classes |
noDbQueriesInControllers |
Database access in controllers |
noDbQueriesInViews |
Database access in views |
noDirectSuperglobals |
$_GET, $_POST, $_SESSION and other superglobals |
noDynamicQueryWhere |
String-built conditions in where() / andWhere() / orWhere() |
noForbiddenYiiAppProperties |
Reads of Yii::$app components |
noRedundantExistenceCheck |
one() and count() checks where exists() suffices |
noRedundantHtmlEncode |
Html::encode() of a numeric-string |
noYiiAppPropertyMutation |
Writes to Yii::$app properties, including setComponents() |
Rule reference
Validation rules
The attribute checks recognize PHPDoc @property tags and skip yii\base\DynamicModel, whose attributes are only defined at runtime.
Active Form field validation
Checks that the attribute in ActiveForm::field() is readable and writable: a property, a @property tag, or a getter and setter.
ActiveQuery with() validation
Checks the relations in with(), joinWith() and innerJoinWith(), including aliases ('orders o') and sub-relations ('orders.items'). A sub-relation is checked when the model of its parent relation is known from @return ActiveQuery<T> or @property-read T.
Active Record condition validation
Checks the attributes and value types in the array conditions of findOne(), findAll(), deleteAll(), updateAll() and updateAllCounters(). An ExpressionInterface value fits any attribute.
Active Record relations validation
Checks that the attributes in hasOne() and hasMany() links exist: the keys on the related model, the values on the current one.
Active Record update values validation
Checks the attributes and value types in the values of updateAll() and updateAllCounters(). Unlike in a condition, an array value is a type mismatch, and an ExpressionInterface value fits any attribute.
BaseObject instantiation validation
Checks the options passed to new on a yii\base\BaseObject subclass against its writable properties and their types, when its last constructor parameter is $config.
Behavior attributes validation
Checks that the attributes in the options of TimestampBehavior, BlameableBehavior, SluggableBehavior, AttributeTypecastBehavior and DateTimeBehavior exist on the model.
The attributes event map of any AttributeBehavior subclass is checked the same way:
Component behaviors validation
Checks behaviors() of yii\base\Component subclasses: classes that aren't behaviors, bad config keys, and unknown or mistyped options.
Controller actions validation
Checks actions() of yii\base\Controller subclasses: classes that aren't actions, empty action IDs, bad config keys, and unknown or mistyped options.
Controller behavior actions validation
Checks that the actions named in controller filters exist, as actionXxx() methods or in actions(): only, except and optional of ActionFilter subclasses, actions in AccessControl rules, and the keys of VerbFilter::$actions. Wildcards are skipped.
Controller view existence validation
Checks that the view in controller render(), renderPartial() and renderAjax() exists, resolving the name the way Yii does with the view settings. The views directory comes from the location of the controller (<module>/controllers/<Name>Controller.php) or from viewPaths. Dynamic names, layouts and controllers that override getViewPath() are skipped.
Html active attribute validation
Checks that the attribute in Html::activeInput(), activeTextInput() and the other active*() methods exists on the model.
Model attribute hints validation
Checks that the keys of attributeHints() are existing attributes and aren't empty. Skip models in skippedClasses.
Model attribute labels validation
Checks that the keys of attributeLabels() are existing attributes and aren't empty. Skip models in skippedClasses.
Model validation rules validation
Checks each entry of rules() against its validator: unknown validators, unknown or mistyped options, missing required options and invalid regexes. Add project validator aliases in customValidators.
It also checks that the attributes of each rule exist on the model:
Model scenarios validation
Checks scenarios() for empty names, attribute lists that aren't arrays, and unknown attributes. An unsafe !attribute is checked without the !.
Nested view existence validation
Checks that the view in $this->render() in a view file (in a views or viewPaths directory) exists. A relative name is resolved against the directory of the file, other names as in controllerViewExistenceValidation.
Query condition validation
Checks the operand count of operator conditions in where(), andWhere() and orWhere() (in, between, like, comparisons, ...), including those nested in and, or and not. Custom operators are skipped.
UploadedFile instance validation
Checks that the attribute in UploadedFile::getInstance() and getInstances() exists on the model.
View::render() existence validation
Checks View::render() outside view files, for @alias/... and //... names only: there is no current view file to resolve the others against.
Widget properties validation
Checks the options of Widget::begin() and Widget::widget() against the writable properties of the widget and their types.
Yii::createObject() validation
Checks that a Yii::createObject() config array has class or __class, and checks its options against the writable properties of the class and their types.
Code quality rules
Complexity limits
Counts if, loops, switch, match, ternaries and try/catch in controller actions and Action::run() against the actionComplexity limits.
No calling actions via $this
No database access outside repositories
Reports ActiveRecord queries and saves, Yii::$app->db, commands, transactions and Query building in controllers, actions and views.
No raw superglobals
No dynamic SQL strings
No forbidden Yii::$app properties
Applies to any yii\base\Application expression. The allowedProperties stay readable.
No redundant existence check
Reports one() compared with null and count() compared with 0 or 1, where exists() runs a lighter query.
No redundant Html::encode()
A numeric-string has nothing to escape:
No Yii::$app property mutation
Applies to any yii\base\Application expression, like noForbiddenYiiAppProperties.