【问题标题】:PHPCS rule for type hinting用于类型提示的 PHPCS 规则
【发布时间】:2017-04-06 08:38:49
【问题描述】:

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

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

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

【问题讨论】:

  • 请接受下面给出的答案。这是您问题的正确答案。

标签: php-7.1 phpcs


【解决方案1】:

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 中父类型的代码。为什么?因为它是基于字符串和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

就是这样!

阅读幕后花絮


初步回答

您可以为此使用Slevomat/CodingStandard 中的TypeHintDeclarationSniff

我用了一年多了,效果很好。

【讨论】:

  • 我看了看,它最符合我的要求。但是您如何处理长行,例如:public function getUrlForRoute(string $routeName, array $parameters = []) : string,它们比允许的 80 个字符长?
  • PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineLengthSniff 。我将其设置为 120 个字符。 80 对我和今天屏幕的屏幕宽度来说是严格的 :)
  • @Pascal,在这种情况下,您应该使用多行方法签名。所以不会让我在这里添加多行代码示例作为注释。
猜你喜欢
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
相关资源
最近更新 更多