在 global-state 项目中实战 phpstan-strict-rules:PHP 极致严格静态分析规则全解析
在 global-state 项目中实战 phpstan-strict-rules:PHP 极致严格静态分析规则全解析
phpstan-strict-rules 是 PHPStan 官方推出的"额外严格且带主观意见"(extra strict and opinionated)规则扩展,专门针对 PHP 语言中大量"怎么写都行"的宽松写法施加约束,例如要求条件必须是布尔值、禁止 == 宽松比较、禁止 empty() 与短三元运算符等。本指南以该扩展的官方 README 为核心骨架,结合其完整源码实现与本仓库(global-state)真实接入配置,讲解 21 条严格规则的用途与底层原理、安装方式、全局禁用与逐条启用两种配置策略,以及它在仓库 phpstan.neon 中的实战用法——读完即可在任意 PHP 项目中按需落地这套"防御性编程"级别的静态分析。
一、什么是 phpstan-strict-rules
PHPStan 的核心使命是"在代码中找出 Bug",但 PHP 本身在写法上留有很大余地:同样的逻辑可以用完全不同的宽松写法表达,且行为往往依赖隐式类型转换。phpstan-strict-rules 正是为"想要在极度防御式编程(extremely defensive programming)中获得额外安全保障"的团队而生——它围绕**严格强类型、杜绝松散强制转换(no loose casting)**的原则,向 PHPStan 注入一组额外的自定义规则。
从仓库接入情况看,本项目的开发依赖中固定了该扩展:
- tools/.phpstan/composer.json 中声明
"phpstan/phpstan-strict-rules": "^2.1.0",同时安装了phpstan/extension-installer: ^1.4.3(用于自动加载扩展的 neon 配置); - 实际锁定版本为 2.1.0(见 tools/.phpstan/composer.lock);
- 扩展自身要求 PHP
^7.4 || ^8.0、PHPStan^2.3(见 扩展的 composer.json),并与ergebnis/phpstan-rules一起被 extension-installer 自动注册(见 GeneratedConfig.php)。
二、21 条核心规则全景(配置参数与规则说明)
官方 README 以一张表概括了全部规则。下表完整继承该清单,其中"配置参数"即可以在 strictRules 配置节中独立开关的键名:
| 配置参数 | 规则说明 |
|---|---|
booleansInConditions |
要求 if、elseif、三元运算符、! 之后以及 &&、` |
booleansInLoopConditions |
要求 while 与 do while 循环条件为布尔值 |
uselessCast |
检测无用的强制类型转换——例如对类型本就是 int 的表达式再执行 (int) 转换 |
numericOperandsInArithmeticOperators |
要求 +、-、*、/、%、**、+$var、-$var、$var++、$var--、++$var、--$var 的操作数为数值类型 |
strictFunctionCalls |
下列函数包含用于提升类型安全的 $strict 参数,必须显式设为 true:in_array(第 3 参数)、array_search(第 3 参数)、array_keys(第 3 参数;仅当提供了第 2 参数 $search_value 时)、base64_decode(第 2 参数) |
overwriteVariablesWithLoop |
禁止 foreach 键/值变量覆盖既有变量;禁止 for 循环初始化语句覆盖既有变量 |
switchConditionsMatchingType |
switch 条件与 case 值的类型必须匹配(PHP 默认宽松比较,可能产生意外结果) |
dynamicCallOnStaticMethod |
检查声明为静态的方法必须以静态方式调用 |
disallowedEmpty |
禁止 empty()——它是一种非常宽松的比较,推荐使用更严格的写法 |
disallowedLooseComparison |
禁止通过 == 与 != 做宽松比较 |
disallowedShortTernary |
禁止短三元运算符 ?:(隐含宽松比较),推荐使用空合并运算符 ?? 或条件严格的完整三元 |
noVariableVariables |
禁止可变变量($$foo、$this->$method() 等) |
checkAlwaysTrueInstanceof、checkAlwaysTrueCheckTypeFunctionCall、checkAlwaysTrueStrictComparison |
检测恒为 true 的 instanceof、is_* 类型检查函数与 ===/!== 严格比较。可通过将这三个参数设为 false 关闭 |
| (无参数名) | 被引用与被调用的函数名必须大小写正确 |
matchingInheritedMethodNames |
被继承与被实现的方法名必须大小写正确 |
| (无参数名) | 继承方法中的参数逆变(contravariance)与返回类型协变(covariance),即里氏替换原则(LSP) |
| (无参数名) | 即使对静态方法也检查 LSP |
requireParentConstructorCall |
要求子类构造函数调用父类构造函数 |
disallowedBacktick |
禁止反引号运算符($ls = `ls -la`) |
disallowedImplicitArrayCreation |
禁止在变量尚不存在时通过 $var[] = 隐式创建数组 |
strictArrayFilter |
要求 array_filter() 必须传入回调参数,以避免宽松比较语义 |
illegalConstructorMethodCall |
禁止对已存在的对象调用 __construct(),也禁止在父构造函数之外以静态方式调用它 |
closureUsesThis |
闭包应直接使用 $this,而不是把 $this 间接赋给变量再使用 |
需要说明:checkAlwaysTrue* 系列三项、函数名大小写检查、LSP 检查及"对静态方法也检查 LSP"这几项源自 PHPStan 内置能力,phpstan-strict-rules 仅调整其默认值(详见后文"默认参数调整"一节),因此表中部分行没有对应的 strictRules 开关名。官方同时预告:后续版本还会持续加入更多规则。
2.1 规则的源码组织
从 src/Rules 目录结构可以看到,每条规则都是独立命名的 Rule 类,按功能域分包组织:
BooleansInConditions/:8 个条件类规则 + 共享的 BooleanRuleHelper.php(负责判定表达式是否"可作为布尔值通过");Cast/UselessCastRule.php:无用转换检测;Classes/RequireParentConstructCallRule.php:父构造函数调用要求;DisallowedConstructs/:empty()、==、短三元、反引号、隐式建数组五类禁用构造;ForLoop/与ForeachLoop/:循环变量覆盖检测;Functions/:array_filter严格化与闭包$this;Methods/:构造方法非法调用、继承方法名大小写;Operators/:13 个算术运算操作数类型规则 + OperatorRuleHelper.php;StrictCalls/:严格函数调用与静态方法动态调用;SwitchConditions/、VariableVariables/:分别承载 switch 类型匹配与可变变量系列。
三、安装与接入
3.1 通过 Composer 安装(推荐)
在任意 PHP 项目的根目录执行:
composer require --dev phpstan/phpstan-strict-rules
如果项目同时安装了 phpstan/extension-installer,那么到此即全部完成——extension-installer 会在 Composer 安装时自动读取扩展 composer.json 的 extra.phpstan.includes 声明并生成合并配置,无需手工编辑 PHPStan 配置文件。
本仓库正是走这条路线:tools/.phpstan/composer.json 同时声明了 phpstan/extension-installer: ^1.4.3 与 phpstan/phpstan-strict-rules: ^2.1.0,并在 config.allow-plugins 中放行 "phpstan/extension-installer": true。安装后 GeneratedConfig.php 中记录了该扩展的 install_path 与 relative_install_path('../../phpstan-strict-rules'),并声明其 extra.includes 指向 rules.neon,从而完成自动接入。
注意:从 Composer 2.2.0 起,首次安装该插件时 Composer 会询问是否信任并启用它(会向
allow-plugins写入配置),需要确认允许。
3.2 手动安装(不使用 extension-installer)
如果不希望引入 extension-installer,可在项目 PHPStan 配置文件中手工 include 该扩展的规则文件:
includes:
- vendor/phpstan/phpstan-strict-rules/rules.neon
这条路径以项目根目录为基准,实际文件即 rules.neon。
四、禁用规则:strictRules 参数面板
phpstan-strict-rules 的所有自定义规则都可以通过 strictRules 配置节独立关闭。官方 README 给出的完整禁用配置如下:
parameters:
strictRules:
disallowedLooseComparison: false
booleansInConditions: false
booleansInLoopConditions: false
uselessCast: false
requireParentConstructorCall: false
disallowedBacktick: false
disallowedEmpty: false
disallowedImplicitArrayCreation: false
disallowedShortTernary: false
overwriteVariablesWithLoop: false
closureUsesThis: false
matchingInheritedMethodNames: false
numericOperandsInArithmeticOperators: false
strictFunctionCalls: false
dynamicCallOnStaticMethod: false
switchConditionsMatchingType: false
noVariableVariables: false
strictArrayFilter: false
illegalConstructorMethodCall: false
4.1 开关机制:conditionalTags 映射
从 rules.neon 的源码可以看到每个开关的真实作用方式:扩展通过 conditionalTags 把每一组 Rule 类与对应的 %strictRules.<开关名>% 参数绑定。例如:
%strictRules.booleansInConditions%同时控制BooleanInBooleanAndRule、BooleanInBooleanNotRule、BooleanInBooleanOrRule、BooleanInElseIfConditionRule、BooleanInIfConditionRule、BooleanInTernaryOperatorRule六个规则类;%strictRules.booleansInLoopConditions%控制BooleanInDoWhileConditionRule与BooleanInWhileConditionRule;%strictRules.overwriteVariablesWithLoop%同时控制OverwriteVariablesWithForeachRule与OverwriteVariablesWithForLoopInitRule;%strictRules.numericOperandsInArithmeticOperators%控制加减乘除模幂及前/后缀自增自减共 11 个规则类;%strictRules.noVariableVariables%控制可变变量系列 8 个规则类(VariableVariablesRule、VariableMethodCallRule、VariableStaticPropertyFetchRule等)。
因此把某个参数设为 false,等于整组对应规则被条件化移除,而不是简单地改变报错等级。
4.2 参数合法性校验
rules.neon 还通过 parametersSchema 声明了 strictRules 的合法结构:每个开关都接受 bool() 或 arrayOf(bool())(后者用于按路径/文件粒度精细控制)。若配置中写了不存在的键或非法值类型,PHPStan 会直接报配置错误。
五、逐条启用:allRules 精细控制
如果不想一次性启用全部严格规则、只想先上其中一两项,可以先关闭 allRules,再按需开启:
parameters:
strictRules:
allRules: false
随后逐条重新开启:
parameters:
strictRules:
allRules: false
booleansInConditions: true
allRules 是 rules.neon 定义的主开关:每个自定义规则参数都引用 %strictRules.allRules%,例如 disallowedLooseComparison: %strictRules.allRules%、booleansInConditions: %strictRules.allRules%。此外有两点需要留意:
booleansInLoopConditions与OperandInArithmeticUnaryPlusRule/OperandInArithmeticUnaryMinusRule的取值是[%strictRules.allRules%, %featureToggles.bleedingEdge%]——即它们额外受 PHPStan 的 bleedingEdge 实验特性开关约束,即使allRules: true,未开启 bleedingEdge 时这两组也不会生效;- 即便
allRules: false,该包的一部分效果依然存在(见下一节)。
5.1 "即使 allRules 关闭仍在生效"的真相:默认参数调整
官方 README 特别强调:除了注入自定义规则,phpstan-strict-rules 还会改写 PHPStan 自身部分配置参数的默认值。查看 rules.neon 开头即可确认这一组改动:
parameters:
strictRulesInstalled: true
polluteScopeWithLoopInitialAssignments: false
polluteScopeWithAlwaysIterableForeach: false
polluteScopeWithBlock: false
checkDynamicProperties: true
checkExplicitMixedMissingReturn: true
checkFunctionNameCase: true
checkInternalClassCaseSensitivity: true
reportMaybesInMethodSignatures: true
reportStaticMethodSignatures: true
reportMaybesInPropertyPhpDocTypes: true
reportWrongPhpDocTypeInVarTag: true
checkStrictPrintfPlaceholderTypes: true
reportNonIntStringArrayKey: %featureToggles.bleedingEdge%
这些参数全部属于 PHPStan 核心的分析配置,其语义概括如下:
polluteScopeWithLoopInitialAssignments/polluteScopeWithAlwaysIterableForeach/polluteScopeWithBlock改为false:禁止for循环初始化语句、必然遍历的foreach、代码块内赋值污染外层作用域——这为overwriteVariablesWithLoop等循环变量覆盖检测提供了更干净的变量流信息;checkDynamicProperties改为true:检查在类中动态声明属性;checkExplicitMixedMissingReturn改为true:显式标注mixed的函数若缺少 return 也要报错;checkFunctionNameCase/checkInternalClassCaseSensitivity改为true:对应表中"函数名大小写"与内部类名大小写检查;reportMaybesInMethodSignatures/reportStaticMethodSignatures/reportMaybesInPropertyPhpDocTypes/reportWrongPhpDocTypeInVarTag改为true:强化签名与 PHPDoc 类型声明的严格报告,即 LSP(含静态方法)检查的载体;checkStrictPrintfPlaceholderTypes改为true:严格校验printf系列占位符类型;reportNonIntStringArrayKey跟随 bleedingEdge:报告字符串非整型数组键。
正因如此,只要 include 了 rules.neon(无论自动还是手动、无论 allRules 取值),PHPStan 自身的行为就已按上述"更严格"的默认值运转,这就是"包的部分效果始终生效"的机制来源。
六、本仓库(global-state)的实战配置解析
作为真实落地样本,本项目根目录的 phpstan.neon 展示了如何组合使用上面全部概念:
parameters:
level: 10
paths:
- src
- tests/unit
checkTooWideReturnTypesInProtectedAndPublicMethods: true
reportAlwaysTrueInLastCondition: true
reportPossiblyNonexistentConstantArrayOffset: true
treatPhpDocTypesAsCertain: false
strictRules:
allRules: false
booleansInConditions: true
closureUsesThis: true
disallowedBacktick: true
disallowedEmpty: true
disallowedImplicitArrayCreation: true
disallowedLooseComparison: true
disallowedShortTernary: true
illegalConstructorMethodCall: true
matchingInheritedMethodNames: true
noVariableVariables: true
numericOperandsInArithmeticOperators: true
overwriteVariablesWithLoop: true
requireParentConstructorCall: true
strictArrayFilter: true
strictFunctionCalls: true
switchConditionsMatchingType: true
uselessCast: true
ergebnis:
allRules: false
final:
enabled: true
privateInFinalClass:
enabled: true
includes:
- phar://phpstan.phar/conf/bleedingEdge.neon
这份配置的解读要点:
- 分析级别拉满:
level: 10是 PHPStan 最高严格级别,paths指向src与tests/unit(本项目的核心源码与单元测试); - strictRules 采取"逐条点亮"策略:
allRules: false关闭默认全开,再手工把 17 个自定义开关全部置为true(booleansInLoopConditions依赖的 bleedingEdge 也通过includes引入了bleedingEdge.neon,因此循环条件布尔化同样生效); - 自主决定 PHPStan 内置严格项:开启
checkTooWideReturnTypesInProtectedAndPublicMethods、reportAlwaysTrueInLastCondition、reportPossiblyNonexistentConstantArrayOffset,同时把treatPhpDocTypesAsCertain设为false(即对 PHPDoc 中的类型声明保持审慎,不盲目当作既定事实——uselessCast与strictArrayFilter两个规则会读取该参数调整自身的判断逻辑,见 UselessCastRule.php); - 与第三方扩展共存:
ergebnis节是ergebnis/phpstan-rules的独立配置,同样采用allRules: false后按需开启,与 phpstan-strict-rules 互不干扰。
七、关键规则的源码实现速览
以下结合实现源码,说明几条代表性规则究竟"怎么查、报什么错"(所有路径均以仓库根为基准)。
7.1 strictFunctionCalls:四个内置函数的 $strict 参数
StrictFunctionCallsRule.php 内部维护一张"函数名 → 严格参数下标"的映射表:
private array $functionArguments = [
'in_array' => 2,
'array_search' => 2,
'base64_decode' => 1,
'array_keys' => 2,
];
其处理流程为:先通过 ReflectionProvider 确认函数存在,再用 ArgumentsNormalizer 归一化命名参数顺序;对 array_keys 额外判断"仅当第 2 参数 $search_value 已提供时才要求第 3 参数";随后用 ConstantBooleanType(true) 检查对应参数是否恒为 true(isSuperTypeOf(...)->yes()),否则报 Call to function xxx() requires parameter #n to be true.,错误标识为 function.strict。这解释了为什么 README 要求"必须显式写 true"——把严格参数留空或传变量都不能通过。
7.2 disallowedLooseComparison:拦截 == / !=
DisallowedLooseComparisonRule.php 注册于 BinaryOp 节点,仅对 Equal(==)与 NotEqual(!=)触发,分别报错 Loose comparison via "==" is not allowed. / Loose comparison via "!=" is not allowed.(标识符 equal.notAllowed / notEqual.notAllowed),并附 tip 建议改用 === / !==。它有一个构造参数 includeOperandTypesInErrorMessage:在 bleedingEdge 开启时,错误信息会附带两侧操作数类型(如 Loose comparison via "==" between int and string is not allowed.),便于定位。
7.3 booleansInConditions:8 个规则共享一个判断器
if、elseif、while、do while、!、&&/||、三元运算符各自有独立 Rule 类,但全部复用 BooleanRuleHelper.php 的 passesAsBoolean():隐式 mixed 直接放行,否则要求推导类型 isBoolean()->yes()。以 BooleanInIfConditionRule.php 为例,非布尔条件会报:
Only booleans are allowed in an if condition, string given.
对应标识符 if.condNotBoolean(elseif、while、do while、!、三元条件分别为 elseif.condNotBoolean、while.condNotBoolean、doWhile.condNotBoolean、booleanNot.exprNotBoolean、ternary.condNotBoolean)。也就是说 if ($count) 这种 PHP 惯用法在该规则下必须显式写成 if ($count > 0) 或 if (is_int($count)) 之类。
7.4 strictArrayFilter:必须显式传回调
ArrayFilterStrictRule.php 只针对 array_filter。规则允许两种安全写法:① 只有一个参数,但数组元素类型恒为布尔/数组/联合类型中真值与假值并存(语义明确);② 传入了非 null 的回调参数。否则报 Call to function array_filter() requires parameter #2 to be passed to avoid loose comparison semantics.(标识符 arrayFilter.strict)。其构造参数读取 treatPhpDocTypesAsCertain、checkNullables 决定是否把 PHPDoc 类型当作既定事实、以及 null 回调是否算违规。
7.5 overwriteVariablesWithLoop:禁止循环变量"反客为主"
OverwriteVariablesWithForeachRule.php 与 OverwriteVariablesWithForLoopInitRule.php 都注册于 PHPStan 内部的 VariableWritesNode,利用 getVariableOverwritingLoop() 找出"被循环覆盖且循环后仍被读取"的变量——源码注释明确说明:仅复用已"用完"的循环变量是无害的,只有覆盖了既有变量才算违规。对应错误如 Foreach overwrites $foo with its value variable.(foreach.valueOverwrite / foreach.keyOverwrite)与 For loop initial assignment overwrites variable $bar.(for.variableOverwrite)。
7.6 构造方法两兄弟:illegalConstructorMethodCall
该开关由两个规则类组成:
- IllegalConstructorMethodCallRule.php:拦截
$obj->__construct()形式的调用,报Call to __construct() on an existing object is not allowed.; - IllegalConstructorStaticCallRule.php:拦截
Foo::__construct(),但会放行两类合法场景——当前函数是构造函数且目标是被调类父类(isCollectCallingConstructor()通过解析父类名列表判断),以及 trait 中重命名的构造方法。错误标识符统一为constructor.call。
7.7 其余规则的实现要点
uselessCast:UselessCastRule.php 对转换结果类型做generalize(lessSpecific)后判断是否已是被转换表达式的超类型,命中则报Casting to int something that's already int.(cast.useless);treatPhpDocTypesAsCertain为false时只信原生类型,避免 PHPDoc 误导;switchConditionsMatchingType:MatchingTypeInSwitchCaseConditionRule.php 用conditionType->isSuperTypeOf(caseType)->no()判定不匹配,报Switch condition type (int) does not match case condition 'foo' (string).(switch.type),并精确指向出错的case行;closureUsesThis:ClosureUsesThisRule.php 检查闭包use列表中的变量类型是否为ThisType,例如use ($that)且$that即$this时会提示Anonymous function uses $this assigned to variable $that. Use $this directly in the function body.(closure.useThis);matchingInheritedMethodNames:WrongCaseOfInheritedMethodRule.php 对比子类方法名与父类/接口方法名,例如子类写了getFoo()而父类为getfoo()时会报method.nameCase;requireParentConstructorCall:RequireParentConstructCallRule.php 只针对非抽象、非接口、非匿名类的__construct,递归扫描方法体内(含错误抑制表达式@)是否存在parent::__construct调用,同时会沿继承链向上寻找"真正声明了构造函数的父类"再决定是否报constructor.missingParentCall;disallowedEmpty/disallowedBacktick/disallowedShortTernary:实现极简,分别注册于Empty_、ShellExec、Ternary节点,命中即报,标识符empty.notAllowed、backtick.notAllowed、ternary.shortNotAllowed;disallowedImplicitArrayCreation:DisallowedImplicitArrayCreationRule.php 沿ArrayDimFetch链条向下剥到根变量,再通过hasVariableType()判断变量"不存在"或"可能不存在"两种情形分别报variable.implicitArray;noVariableVariables:VariableVariablesRule.php 检查Variable节点的名称是否为表达式(非字符串字面量),是则报variable.dynamicName;同组的VariableStaticMethodCallRule等还覆盖$class::$method()、$obj->$method()等变体,标识符如staticMethod.dynamicName。
八、错误标识符:稳定的忽略与基线依据
值得单列说明:上述所有规则的报错都带有稳定的 identifier(错误标识符),这是 PHPStan 2.x 的标准错误模型。利用标识符,你可以用 ignoreErrors 按标识符精确忽略特定规则(而不必整条关闭),例如:
parameters:
ignoreErrors:
-
identifier: empty.notAllowed
path: src/LegacyHelper.php
这比"一刀切关闭整个开关"精细得多,也让新代码库可以先跑通基线、再逐步把 strictRules 开关点亮。全文提及的主要标识符速查:if.condNotBoolean、while.condNotBoolean、doWhile.condNotBoolean、elseif.condNotBoolean、ternary.condNotBoolean、booleanNot.exprNotBoolean、cast.useless、equal.notAllowed、notEqual.notAllowed、empty.notAllowed、backtick.notAllowed、ternary.shortNotAllowed、arrayFilter.strict、closure.useThis、constructor.call、constructor.missingParentCall、method.nameCase、foreach.keyOverwrite、foreach.valueOverwrite、for.variableOverwrite、function.strict、staticMethod.dynamicCall、staticMethod.dynamicName、switch.type、variable.dynamicName、variable.implicitArray。
九、适用场景与注意事项
- 何时启用:适合对类型安全有强要求的库/框架项目(如本仓库这种被 PHPUnit 复用的基础组件)、长期维护且测试充分的代码库,以及希望以机器规则固化团队编码规范的场景;对于历史包袱重的遗留代码,建议先用
allRules: false+ 逐条点亮,配合错误标识符做忽略基线,逐步收敛。 - 与 bleedingEdge 的关系:
booleansInLoopConditions与一元正负号操作数规则受 PHPStan 实验特性门控(见 rules.neon 的[%strictRules.allRules%, %featureToggles.bleedingEdge%]写法),本仓库通过includes: - phar://phpstan.phar/conf/bleedingEdge.neon开启后它们才生效。 - 版本前提:该扩展要求 PHPStan
^2.3(PHP^7.4 || ^8.0),且随 PHPStan 2.x 的错误标识符模型设计;升级 PHPStan 大版本前应核对扩展兼容性。运行分析时,可在tools/.phpstan目录下调用 Composer 生成的代理入口tools/phpstan(对应 tools/.phpstan/vendor/phpstan/phpstan/phpstan)。 - 不要依赖"宽松"习惯:开启后
if ($var)、empty($var)、$a == $b、$var ?: $default、array_filter($arr)、$$name等常见写法都会报错——这不是缺陷,而是该扩展的设计意图:让每一次类型判断都显式、可读、可静态验证。
总结来说,phpstan-strict-rules 的完整价值由三部分组成:19 个可直接开关的自定义规则组 + 对 PHPStan 内置严格参数的默认值改写 + 随 bleedingEdge 逐步解锁的新规则。理解 rules.neon 中 allRules、各开关、conditionalTags 与 parametersSchema 的配合关系,再参考本仓库 phpstan.neon 的"全关后逐条点亮"实践,你就能在任何 PHP 项目中获得一套高度可控、可渐进落地的极致严格静态分析策略。