PHPCS规则类型提示

问题描述 投票:1回答:1

是否有规则检查类型提示的所有函数?

/**
 * Set the part name.
 *
 * @param   string    $name   The part name.
 */
public function setName(string $name) : void
{
    $this->name = $name;
}

因此,例如,它必须在参数前面有一个类型,并且函数必须具有指定的返回类型。

php-7.1 phpcs
1个回答
4
投票

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中使用父类型中断代码。为什么?因为它基于字符串和令牌,而不是代码的静态分析。

在我向他们推荐这个嗅闻之后,这让很多人非常生气。明显。


How to do it Better?

我写了一个名为Rector(https://github.com/rectorphp/rector)的工具,它考虑了其他变量和其他类及其类型。

这样,您可以在没有任何@param@return注释的情况下完成对代码的类型声明。


How to use It?

安装:

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

而已!

阅读幕后故事


初步答案:

你可以使用TypeHintDeclarationSniffSlevomat/CodingStandard

我使用它超过一年,它的工作完美。

© www.soinside.com 2019 - 2024. All rights reserved.