PHPStan 2.0 升级实战指南:从 1.x 迁移的核心变更与配置适配

原创2026-10-14 18:26:431,715 阅读
文章标签:后端

PHPStan 2.0 升级实战指南:从 1.x 迁移的核心变更与配置适配

本文以 PHPStan 官方升级文档 UPGRADING.md 为主体,结合本仓库(php-text-template)中真实落地的 PHPStan 2.2.17 工具链(phpstan.neon、composer.json、installed.json)逐项解读从 PHPStan 1.x 升级到 2.0 时必经的配置迁移、行为变化与扩展开发兼容性调整。读完本文,你将能独立完成一条可复制的 1.x → 2.0 升级路径:先确定升级前准备清单,再改写 composer.json 依赖、迁移被移除的配置项、按新规范修正 ignoreErrors/excludePaths,并掌握自定义规则与扩展开发者在 2.0 下的全部关键 API 变化,最终让项目在一个绿色无弃用告警的构建上平滑落地 2.0。

一、升级前提:运行时环境要求

PHPStan 2.0 的第一个硬性变化来自运行环境本身:PHPStan 现在要求 PHP 7.4 或更高版本才能运行。这比 1.x 时代的最低版本要求更高,因此升级前应先在 CI 与本地环境中确认 PHP 版本。

对于本仓库而言,这一点毫无压力:根目录 composer.json 声明 "php": ">=8.4",远高于 2.0 的门槛,同时仓库工具链目录 tools/.phpstan 中安装的 PHPStan 也是 2.x 系列(installed.json 显示 phpstan/phpstan 版本为 2.2.17),说明该环境已直接运行在 PHPStan 2.0 之上。

二、端用户升级指南:推荐的渐进式迁移路径

官方文档给出的最佳升级路径不是"一步到位",而是分四步走:

  1. 先升级到最新的 PHPStan 1.12 版本,并开启 Bleeding Edge 模式。Bleeding Edge 是 PHPStan 提供的一组"预览特性"开关,会提前启用那些将在 2.0 中面向所有用户默认开启的新规则与行为。在 1.12 上开启它,相当于提前暴露 2.0 的全部新告警,从而在升级前就把代码清理干净。
  2. 安装并启用 phpstan/phpstan-deprecation-rules 扩展,用来检测代码中对 PHPStan 自身已弃用 API 的使用。
  3. 当你在最新的 1.12.x + Bleeding Edge 组合下拿到一个没有任何弃用告警的绿色构建后,才把 composer.json 中所有相关的 PHPStan 依赖统一升级到 2.0:
"require-dev": {
    "phpstan/phpstan": "^2.0",
    "phpstan/phpstan-deprecation-rules": "^2.0",
    "phpstan/phpstan-doctrine": "^2.0",
    "phpstan/phpstan-nette": "^2.0",
    "phpstan/phpstan-phpunit": "^2.0",
    "phpstan/phpstan-strict-rules": "^2.0",
    "phpstan/phpstan-symfony": "^2.0",
    "phpstan/phpstan-webmozart-assert": "^2.0",
    ...
}
  1. 别忘了同步更新第三方 PHPStan 扩展(官方扩展库中的各扩展)。改完 composer.json 后执行:
composer update 'phpstan/*' -W

-W(即 --with-all-dependencies)会连同传递依赖一起更新,避免因依赖树中残留 1.x 版本导致的不兼容。

至于升级后新冒出来的报错,官方态度很明确:你可以逐个修复,也可以全部塞进 baseline(基线)。只要原本在 1.12 上是绿色的,理论上人人都能平滑升级到 2.0。

值得一提:本仓库的 phpstan.neon 第 40-41 行已经通过 includes: phar://phpstan.phar/conf/bleedingEdge.neon 启用了 Bleeding Edge,这与官方文档"升级前先开 Bleeding Edge"的建议完全一致,属于 2.0 时代的推荐配置形态;仓库工具链中还实际安装了 phpstan/phpstan-strict-rules(2.0.12)与 ergebnis/phpstan-rules(2.14.0),对应上面清单中"第三方扩展同步升到 2.0"的要求。

三、代码分析行为的变化(Noteworthy changes)

2.0 对代码分析本身引入了以下值得注意的增强,升级后你可能看到比 1.x 更多(也更准确)的告警:

  • 按引用传递参数(parameters passed by reference)的处理增强:PHPStan 现在能更精确地跟踪按引用传入的参数在函数调用后类型的变化,减少误报与漏报。
  • 校验内联 PHPDoc @var 标签的类型:对于 /** @var Foo $x */ 这类内联标签,2.0 会校验其类型是否合法,避免"用错误类型标签骗过静态分析"。
  • List 类型强制生效(List type enforced):PHPStan 的 list(从 0 开始连续索引的数组)语义在 2.0 中全面强制执行,list<T> 不再只是一个可选优化。
  • 恒为 true 的条件总是被报告:这是行为上的重要收紧——此前"条件恒为 true"这类告警只在启用 phpstan-strict-rules 时才出现,2.0 起对所有用户默认报告,无需任何额外配置。

四、被移除的配置项及其迁移方案

2.0 移除了一批"可开关"的配置项,把它们对应的检查变成默认行为。以下是端用户最需要处理的四组:

1. 移除 checkMissingIterableValueType

该选项原本控制"是否检查数组缺少值类型标注"。2.0 移除后,强烈建议直接补全数组类型标注(如 array<string, int>)。若暂时想继续忽略这类缺失,可在 ignoreErrors 中按 error identifier 精确忽略:

parameters:
	ignoreErrors:
		-
			identifier: missingType.iterableValue

注意:这里使用的是 2.0 引入的 identifier 机制(按错误标识符忽略,而不是按消息文本忽略),标识符 missingType.iterableValue 对应"可迭代对象缺失值类型"这一具体错误类别。

2. 移除 checkGenericClassInNonGenericObjectType

同理,该选项控制"是否检查非泛型对象类型上使用了泛型"。2.0 移除后建议补全泛型标注;若想继续忽略,使用标识符:

parameters:
	ignoreErrors:
		-
			identifier: missingType.generics

3. 移除 checkAlwaysTrue* 系列选项

以下四个选项在 2.0 中全部移除,因为 PHPStan 现在始终表现得如同它们被设为 true(即无条件检查恒真条件):

  • checkAlwaysTrueCheckTypeFunctionCall
  • checkAlwaysTrueInstanceof
  • checkAlwaysTrueStrictComparison
  • checkAlwaysTrueLooseComparison

如果你的配置里出现过这些键名,直接删除即可——对应的严格检查已经内置。本仓库的 phpstan.neon 中出现的 reportAlwaysTrueInLastCondition: true 正是 2.0 时代的新式参数名,与本文档所述"恒真条件检查默认开启"的方向一致。

4. 移除 excludes_analyse

旧配置 excludes_analyse 已被 excludePaths 完全取代。所有以 excludes_analyse 排除的路径,都需要改写为 excludePaths 语法(见下一节的新路径规则)。

五、excludePaths 与 ignoreErrors 的路径新规

2.0 对路径匹配做了收紧:excludePaths 和 ignoreErrors 中的路径必须是合法的文件路径或 fnmatch 通配模式。两个典型场景:

场景一:要排除的路径可能不存在(如按约定生成的目录),但仍想保留排除规则。 给路径追加 (?) 后缀标记为"可选路径":

parameters:
	excludePaths:
		- tests/*/data/*
		- src/broken
		- node_modules (?) # optional path, might not exist

场景二:ignoreErrors 中要忽略某个可能不存在的路径中的错误。 注意两点:ignoreErrors 中不支持 (?) 后缀;替代做法是关闭"未匹配忽略项的报错":

parameters:
	reportUnmatchedIgnoredErrors: false

六、官方第一方扩展的配置变更

如果项目依赖 PHPStan 官方扩展,2.0 同时调整了它们的配置参数:

  • phpstan-doctrine:
    • 移除配置参数 searchOtherMethodsForQueryBuilderBeginning(扩展现在始终表现得如同该项为 true);
    • 移除配置参数 queryBuilderFastAlgorithm(扩展现在始终表现得如同该项为 false)。
  • phpstan-symfony:
    • 移除所有名字中带下划线 _ 的旧式选项;
    • container_xml_path → 改用 containerXmlPath;
    • constant_hassers → 改用 constantHassers;
    • console_application_loader → 改用 consoleApplicationLoader。

升级后若遇到"未知配置参数"报错,优先对照这个改名表。

七、端用户视角的次要兼容性破坏(Minor backward compatibility breaks)

这些破坏大多影响的是"冷门配置",但对使用它们的人来说是硬性报错:

  • 移除未使用的配置参数 cache.nodesByFileCountMax;
  • 移除未使用的配置参数 memoryLimitFile;
  • 移除未使用的功能开关 disableRuntimeReflectionProvider;
  • 移除未使用的配置参数 staticReflectionClassNamePatterns;
  • fixerTmpDir 移除,改用 pro.tmpDir;
  • tempResultCachePath 移除,改用 resultCachePath;
  • additionalConfigFiles 配置参数现在必须是列表(list),不能再传单个字符串。

升级脚本思路:全局搜索上述旧键名,逐一替换或删除。

八、扩展开发者升级指南

如果你是 PHPStan 扩展或自定义规则(custom rule)的作者,2.0 的破坏面比端用户大得多。官方给出的总体建议是:在扩展的新大版本中切换 PHPStan 2.0,不要试图用同一套代码同时兼容 1.x 与 2.x。可以先通过"用 PHPStan 1.12 + Bleeding Edge + phpstan-deprecation-rules 分析你自己的扩展代码"来消除弃用告警、无限逼近 2.0 兼容,但最后一步跨越不兼容 API 的方式,是在 composer.json 中要求 "phpstan/phpstan": "^2.0" 并发布新的主版本。

1. 底层解析器的重大升级

  • nikic/php-parser v5:最显著的变化是 throw 语句的 AST 表示方式。过去独立的 throw $e; 语句用 Stmt\Throw_ 类表示,表达式内的 $x ?? throw $e 用 Expr\Throw_ 类表示;现在 throw $e; 被表示为包含 Expr\Throw_ 的 Stmt\Expression,Stmt\Throw_ 类已被删除。凡是遍历 AST 处理 throw 语句的规则都必须改写。
  • phpstan/phpdoc-parser v2:PHPDoc 解析器同步升级到 2.x 大版本,涉及 PHPDoc 解析结果 API 的规则需要跟进其自身的升级说明。

2. 自定义规则必须使用 RuleErrorBuilder 并携带 identifier

返回普通字符串作为错误不再受支持,自定义规则必须使用 RuleErrorBuilder 构造错误对象,并且 identifier(错误标识符)成为必填项:

之前(1.x):

return ['My error'];

之后(2.0):

return [
    RuleErrorBuilder::message('My error')
        ->identifier('my.error')
        ->build(),
];

这正是上一节"按 identifier 忽略错误"能成立的前提——2.0 起每个错误都带上了稳定标识符。

3. 弃用 instanceof *Type,改用 Type 接口上的新方法

2.0 开始系统性地弃用"用 instanceof 判断具体类型类"的做法,鼓励在 Type 接口上直接调用语义化方法(如 isConstantValue()、getArrays() 等)。这一方向贯穿整个 2.0 的类型系统重构,新写的扩展代码应避免对具体 *Type 类做 instanceof 分支。

4. 移除 ParametersAcceptorSelector::selectSingle()

改用 ParametersAcceptorSelector::selectFromArgs(),它在大多数原来用 selectSingle() 的场景(如动态返回类型扩展)中都是正确替代:

之前:

$defaultReturnType = ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType();

之后:

$defaultReturnType = ParametersAcceptorSelector::selectFromArgs(
    $scope,
    $functionCall->getArgs(),
    $functionReflection->getVariants()
)->getReturnType();

此外,如果是在分析函数/方法体本身,应直接在反射对象上取 getParameters() 和 getReturnType(),涉及的节点/接口包括 InClassMethodNode::getMethodReflection()、InFunctionNode::getFunctionReflection()、FunctionReturnStatementsNode::getFunctionReflection()、MethodReturnStatementsNode::getMethodReflection()、Scope::getFunction():

之前:

$function = $node->getFunctionReflection();
$returnType = ParametersAcceptorSelector::selectSingle($function->getVariants())->getReturnType();

之后:

$returnType = $node->getFunctionReflection()->getReturnType();

5. TypeSpecifier::create() 与 SpecifiedTypes 构造参数变更

  • TypeSpecifier::create() 现在接受(且全部必填):Expr $expr、Type $type、TypeSpecifierContext $context、Scope $scope。
  • 若要修改原来的 $overwrite 或 $rootExpr 参数,改为对 TypeSpecifier::create() 返回的 SpecifiedTypes 对象调用 setAlwaysOverwriteTypes() 与 setRootExpr();SpecifiedTypes 是不可变对象,这些方法会返回新对象。
  • SpecifiedTypes 构造函数现在只接受:array $sureTypes、array $sureNotTypes,同样的覆盖/根表达式设置改走 setAlwaysOverwriteTypes() / setRootExpr()。
  • TypeSpecifier::specifyTypesInCondition() 不再接受 Expr $rootExpr,如需修改请对返回的 SpecifiedTypes 调用 setRootExpr()。

6. ConstantArrayType 不再继承 ArrayType

Type::getArrays() 的返回类型变为 list<ArrayType|ConstantArrayType>。由于 instanceof ArrayType 本身也在弃用之列,此改动的影响应可控,但类型判断逻辑需要随之调整。

7. AST 节点属性 parent、previous、next 不再可用

自定义规则中依赖这些节点属性的预处理逻辑(preprocessing AST)需要重写,官方推荐改用新的节点访问/上下文方案。

8. 移除配置参数 scopeClass

替代方案是自行实现 PHPStan\Type\ExpressionTypeResolverExtension 接口并将其注册为 service,用扩展点代替"换 scope 类"的旧做法。

9. 移除 PHPStan\Broker\Broker

统一改用 PHPStan\Reflection\ReflectionProvider。连带变化:

  • BrokerAwareExtension 同步移除,改为在扩展构造函数中请求注入 ReflectionProvider;
  • PHPStanTestCase::createBroker() 改为调用 PHPStanTestCase::createReflectionProvider()。

10. List 类型面向所有人启用

AccessoryArrayListType 类的以下静态方法被移除:isListTypeEnabled()、setListTypeEnabled()、intersectWith()。原来的 AccessoryArrayListType::intersectWith($type) 改写成 TypeCombinator::intersect($type, new AccessoryArrayListType())。

11. 扩展开发者的完整次要兼容性破坏清单

以下为本节全部破坏性变更,按类别整理,供升级时逐一对照(各 API 的替代用法以官方 API 文档为准):

类与可继承性

  • 原本标记 @final 的类现在真正变为 final;
  • PHPStan\Node\ClassMethod(可通过 ClassMethodsNode 访问)不再是 AST 节点,需调用 PHPStan\Node\ClassMethod::getNode() 获取原始 AST 节点;
  • PHPStan\Node\Printer\Printer 不再自动装配为 PhpParser\PrettyPrinter\Standard,类型提示中应直接使用 PHPStan\Node\Printer\Printer。

方法签名与必填参数

  • MutatingScope::enterAnonymousFunction() 与 enterArrowFunction() 的参数 $callableParameters 变为必填;
  • NodeScopeResolver::processStmtNodes() 的参数 StatementContext $context 变为必填;
  • ClassPropertiesNode::getUninitializedProperties() 移除 $extensions 参数;
  • LevelsTestCase::dataTopics() 数据提供器改为静态方法。

类型比较 API

  • Type::getSmallerType()、getSmallerOrEqualType()、getGreaterType()、getGreaterOrEqualType()、isSmallerThan()、isSmallerThanOrEqual() 现在都必须传入 PhpVersion 参数;
  • CompoundType::isGreaterThan()、isGreaterThanOrEqual() 同样必须传入 PhpVersion;
  • Type::acceptsWithReason() 移除,Type::accepts() 返回类型由 TrinaryLogic 改为 AcceptsResult;
  • CompoundType::isAcceptedWithReasonBy() 移除,isAcceptedBy() 返回 AcceptsResult;
  • Type::isSuperTypeOfWithReason() 移除,isSuperTypeOf() 返回 IsSuperTypeOfResult;
  • CompoundType::isSubTypeOfWithReasonBy() 移除,isSubTypeOf() 返回 IsSuperTypeOfResult;
  • TemplateType::isValidVarianceWithReason() 移除,isValidVariance() 返回 IsSuperTypeOfResult;
  • RuleLevelHelper::accepts() 返回类型由 bool 改为 RuleLevelHelperAcceptsResult;
  • acceptsNamedArguments()(FunctionReflection、ExtendedMethodReflection、CallableParametersAcceptor)返回 TrinaryLogic 而非 bool。

ArrayType 相关

  • 移除 ArrayType::generalizeKeys();
  • 移除 ArrayType::count(),改用 Type::getArraySize();
  • 移除 ArrayType::castToArrayKeyType(),改用 Type::toArrayKey();
  • 移除 UnionType::pickTypes(),改用 pickFromTypes();
  • ConstantArrayType::isEmpty() 移除,改用 isIterableAtLeastOnce()->no();
  • 移除 ConstantArrayType::getNextAutoIndex();
  • ConstantArrayType 的 getFirst*Type / getLast*Type 系列移除,改用 getFirstIterable*Type / getLastIterable*Type;
  • 移除 ConstantArrayType::generalizeToArray();
  • 移除 ConstantArrayType::findTypeAndMethodName(),改用 findTypeAndMethodNames();
  • 移除 ConstantArrayType::removeLast() / removeFirst() / reverse() / chunk() / slice(),分别改用 Type::popArray()、Type::shiftArray()、Type::reverseArray()、Type::chunkArray()、Type::sliceArray();
  • ConstantArrayType 构造参数 $isList 只能是 TrinaryLogic(不再是 bool),$nextAutoIndexes 只能是 non-empty-list<int>(不再是 int)。

TypeUtils 瘦身

移除以下方法并给出替代:getArrays()/getAnyArrays() → Type::getArrays();getConstantArrays()/getOldConstantArrays() → Type::getConstantArrays();getConstantStrings() → Type::getConstantStrings();getConstantTypes()/getAnyConstantTypes() → Type::isConstantValue() 或 Type::generalize();generalizeType() → Type::generalize();getDirectClassNames() → Type::getObjectClassNames();getConstantScalars() → Type::isConstantScalarValue() 或 Type::getConstantScalarTypes();getEnumCaseObjects() → Type::getEnumCases();containsCallable() → Type::isCallable()。

反射与作用域 API

  • 移除 ReflectionProvider::supportsAnonymousClasses()(所有反射提供者都支持匿名类);
  • 移除 RegexArrayShapeMatcher::matchType(),改用 matchExpr();
  • 移除未用的 PHPStanTestCase::$useStaticReflectionProvider;
  • 移除 PHPStanTestCase::getReflectors(),改用 getReflector();
  • 移除 ClassReflection::getFileNameWithPhpDocs(),改用 getFileName();
  • 移除 AnalysisResult::getInternalErrors(),改用 getInternalErrorObjects();
  • 移除 ConstantReflection::getValue(),改用 getValueExpr();从 Expr 取 Type 用 Scope::getType() 或 InitializerExprTypeResolver::getType();
  • 移除 PropertyTag::getType(),改用 getReadableType() / getWritableType();
  • 移除 GenericTypeVariableResolver,改用 Type::getTemplateType();
  • Type::isClassStringType() 更名为 Type::isClassString();
  • 移除 Scope::isSpecified(),改用 hasExpressionType();
  • 移除 Scope::doNotTreatPhpDocTypesAsCertain(),改用 getNativeType();
  • Type::getProperty() 现在返回 ExtendedPropertyReflection;
  • TypehintHelper::decideTypeFromReflection() 的参数 $selfClass 不再接受 string;
  • 移除了本不应在缓存中序列化的对象上的 __set_state()。

类常量反射重构

  • 类 ClassConstantReflection 移出 BC 承诺,更名为 RealClassConstantReflection;
  • 接口 ConstantReflection 更名为 ClassConstantReflection,并新增围绕 PHPDoc 类型与原生类型的方法;
  • 接口 GlobalConstantReflection 更名为 ConstantReflection。

*WithPhpDocs → Extended* 改名

  • ParametersAcceptorWithPhpDocs → ExtendedParametersAcceptor;
  • ParameterReflectionWithPhpDocs → ExtendedParameterReflection;
  • FunctionVariantWithPhpDocs → ExtendedFunctionVariant。

其他

  • ClassPropertyNode::getNativeType() 返回类型从 AST 节点改为 Type|null;
  • ConstantType 接口移除,改用 Type::isConstantValue();
  • 移除 FunctionReflection::isFinal()。

九、在本仓库中的落地对照

本仓库(php-text-template)本身就是 PHPStan 2.0 配置形态的一个现成样例,可用来对照本文各项说明:

  • 工具链版本:installed.json 显示已安装 phpstan/phpstan 2.2.17、phpstan/phpstan-strict-rules 2.0.12、phpstan/extension-installer 1.4.3、ergebnis/phpstan-rules 2.14.0——全部是 2.x 系,满足升级文档中"所有相关依赖统一到 ^2.0"的要求。
  • Bleeding Edge 已开启:phpstan.neon 通过 includes: phar://phpstan.phar/conf/bleedingEdge.neon 引入 Bleeding Edge(该文件在仓库内的实体为 conf/bleedingEdge.neon),与文档"升级前开启 Bleeding Edge 提前暴露 2.0 行为"的建议完全对应。
  • 新式参数名:reportAlwaysTrueInLastCondition: true、reportPossiblyNonexistentConstantArrayOffset、reportPossiblyNonexistentGeneralArrayOffset 等均为 2.0 时代的参数命名风格,没有出现本文档列出的任何已移除旧键名(如 checkAlwaysTrue*、excludes_analyse),说明该配置已按 2.0 规范迁移到位。
  • strict-rules 集成:phpstan.neon 中 strictRules: 段(含 booleansInConditions、disallowedEmpty、disallowedLooseComparison 等 15 项开关)与 phpstan-strict-rules/composer.json 中 phpstan/phpstan: ^2.1.52 的约束相互印证——2.0 后严格规则包以独立扩展形式提供,这正是本文档"2.0 中恒真条件等检查默认开启、无需依赖 strict-rules 也能触发"这一变化的直接体现。
  • 命令入口:仓库通过 Composer 生成的代理脚本 tools/phpstan 包装 ../phpstan/phpstan/phpstan 可执行文件(其本体 phpstan 加载同目录的 phpstan.phar)。升级后建议先用 php tools/phpstan --version 确认运行版本,再执行 php tools/phpstan analyse 观察新告警。

综上,从 1.x 升级到 2.0 并非推倒重来:端用户的重点是"先开 Bleeding Edge 清债、再批量升依赖、最后迁移被移除的配置项与路径规则";扩展开发者的重点是"新大版本切换 + 解析器/类型系统/错误对象三大 API 族的系统改写"。对照本文的清单逐项处理,即可让升级过程可预期、可回滚、可验证。

登录后查看全文
php-text-template