是否有规则来检查所有函数的类型提示?
/**
* Set the part name.
*
* @param string $name The part name.
*/
public function setName(string $name) : void
{
$this->name = $name;
}
Run Code Online (Sandbox Code Playgroud)
例如,它必须在参数前面有一个类型,而函数必须有一个指定的返回类型。
随着时间的推移,我之前的答案 - TypeHintDeclarationSniff- 已经显示出非常错误。再具体一点:
public function anotherMethod(int $value)
{
// $value is known integer
$this->someMethod($value);
}
/**
* @param string $value
*/
-private function someMethod($value)
+private function someMethod(string $value) // here should be "int"
{
}
Run Code Online (Sandbox Code Playgroud)
遗漏案例:
public function getItems() // here should be "array"
{
return ['Statie', 'EasyCodingStandard', 'Rector'];
}
Run Code Online (Sandbox Code Playgroud)
或者:
public function getResult() // here should be "float"
{
if (true) {
return 5.2;
}
return 5.3;
}
Run Code Online (Sandbox Code Playgroud)
甚至在/vendor. 为什么?因为它基于字符串和令牌,而不是对代码的静态分析。
这让很多人非常生气,在我向他们推荐这个嗅探之后。明显地。
我编写了一个名为 Rector ( https://github.com/rectorphp/rector )的工具,它考虑了其他变量和其他类及其类型。
这样,就可以完成类型声明的代码,而无需任何@param或@return注释。
安装:
composer require vendor/bin/rector
Run Code Online (Sandbox Code Playgroud)
设置rector.yaml配置:
# rector.yaml
services:
Rector\Php\Rector\FunctionLike\ParamTypeDeclarationRector: ~
Rector\Php\Rector\FunctionLike\ReturnTypeDeclarationRector: ~
Run Code Online (Sandbox Code Playgroud)
用:
vendor/bin/rector process src --dry-run # preview
vendor/bin/rector process src # change
Run Code Online (Sandbox Code Playgroud)
就是这样!
初步回答:
为此,您可以使用Slevomat /CodingStandard 的 TypeHintDeclarationSniff。
我用了一年多,效果很好。