用于类型提示的 PHPCS 规则
PHPCS rule for type hinting
是否有检查所有函数类型提示的规则?
/**
* Set the part name.
*
* @param string $name The part name.
*/
public function setName(string $name) : void
{
$this->name = $name;
}
因此,例如它必须在参数前面有一个类型,函数必须有一个指定的 return 类型。
2019 更新 - 更聪明
及时,我之前的回答 - 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"
{
}
漏例:
public function getItems() // here should be "array"
{
return ['Statie', 'EasyCodingStandard', 'Rector'];
}
或:
public function getResult() // here should be "float"
{
if (true) {
return 5.2;
}
return 5.3;
}
甚至在 /vendor
中破坏父类型的代码。为什么?因为是基于strings和token的,不是静态分析代码。
这让很多人很生气,在我向他们推荐了这款嗅探器之后。很明显。
如何做得更好?
我写了一个名为 Rector (https://github.com/rectorphp/rector) 的工具,它考虑了其他变量和其他 类 及其类型。
这样你就可以在没有任何 @param
或 @return
注释的情况下完成对代码的类型声明.
如何使用?
安装:
composer require vendor/bin/rector
设置rector.yaml
配置:
# rector.yaml
services:
Rector\Php\Rector\FunctionLike\ParamTypeDeclarationRector: ~
Rector\Php\Rector\FunctionLike\ReturnTypeDeclarationRector: ~
使用:
vendor/bin/rector process src --dry-run # preview
vendor/bin/rector process src # change
就是这样!
阅读幕后花絮
- How to Complete Type Declarations without Docblocks with Rector
- The Rocket Science Behind Migration of Docblock Types to PHP Typehints
初步回答:
你可以使用TypeHintDeclarationSniff from Slevomat/CodingStandard。
我用了一年多,效果很好。
是否有检查所有函数类型提示的规则?
/**
* Set the part name.
*
* @param string $name The part name.
*/
public function setName(string $name) : void
{
$this->name = $name;
}
因此,例如它必须在参数前面有一个类型,函数必须有一个指定的 return 类型。
2019 更新 - 更聪明
及时,我之前的回答 - 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"
{
}
漏例:
public function getItems() // here should be "array"
{
return ['Statie', 'EasyCodingStandard', 'Rector'];
}
或:
public function getResult() // here should be "float"
{
if (true) {
return 5.2;
}
return 5.3;
}
甚至在 /vendor
中破坏父类型的代码。为什么?因为是基于strings和token的,不是静态分析代码。
这让很多人很生气,在我向他们推荐了这款嗅探器之后。很明显。
如何做得更好?
我写了一个名为 Rector (https://github.com/rectorphp/rector) 的工具,它考虑了其他变量和其他 类 及其类型。
这样你就可以在没有任何 @param
或 @return
注释的情况下完成对代码的类型声明.
如何使用?
安装:
composer require vendor/bin/rector
设置rector.yaml
配置:
# rector.yaml
services:
Rector\Php\Rector\FunctionLike\ParamTypeDeclarationRector: ~
Rector\Php\Rector\FunctionLike\ReturnTypeDeclarationRector: ~
使用:
vendor/bin/rector process src --dry-run # preview
vendor/bin/rector process src # change
就是这样!
阅读幕后花絮
- How to Complete Type Declarations without Docblocks with Rector
- The Rocket Science Behind Migration of Docblock Types to PHP Typehints
初步回答:
你可以使用TypeHintDeclarationSniff from Slevomat/CodingStandard。
我用了一年多,效果很好。