如何让PHPStan检测参数为纯int/string数组而非混合类型?
解决PHPStan无法检测混合类型数组的问题
先看用户定义的PHP类:
readonly class Identifier extends Regexp { /** * @param array<int,int>|array<int,string> $possibleValues */ public function __construct(array $possibleValues = []) { $regexp = implode('|', $possibleValues); parent::__construct('' !== $regexp ? $regexp : null); } }
当前问题:传入包含float的数组时PHPStan能检测错误,但传入[1, 2, "test"]这类int与string混合的数组时,PHPStan无法识别错误,需要让PHPStan强制校验$possibleValues只能是纯int数组或纯string数组。
解决方法:
调整PHPStan配置,启用严格数组类型检查
在你的phpstan.neon(或phpstan.neon.dist)配置文件中,开启全局严格规则或单独启用数组类型校验:parameters: strictRules: true # 若不想全局严格,可单独启用数组检查 checkArrayTypes: true checkListTypes: true开启后PHPStan会严格校验联合数组类型,拒绝混合类型的数组传入。
优化PHPDoc类型标注(可选)
如果$possibleValues是连续索引的列表数组,将类型标注改为list<int>|list<string>,能让PHPStan的同质性检查更精准:/** * @param list<int>|list<string> $possibleValues */ public function __construct(array $possibleValues = [])PHP 8.1+ 运行时类型断言(进阶)
若项目使用PHP 8.1及以上,可添加运行时断言逻辑,同时覆盖静态分析和运行时的类型校验:/** * @param array<int,int>|array<int,string> $possibleValues */ public function __construct(array $possibleValues = []) { $valueType = null; foreach ($possibleValues as $value) { $currentType = gettype($value); if ($valueType === null) { $valueType = $currentType; } elseif ($currentType !== $valueType) { throw new InvalidArgumentException('Possible values must be all integers or all strings'); } } $regexp = implode('|', $possibleValues); parent::__construct('' !== $regexp ? $regexp : null); }
内容的提问来源于stack exchange,提问作者Floxblah
相关产品推荐
相关产品推荐

