是否有PHP的linter使所有异常像Java一样显式?

Ell*_*nce 5 php exception

是否有一个PHP的lint /静态分析器,当没有记录或捕获异常时会发出警告?考虑这个例子:

// ERROR: InvalidArgumentException must be documented or caught inside method.
function divide($a, $b)
{
    if (0 == $b) {
        throw new InvalidArgumentException();
    }
    return $a / $b;
}
Run Code Online (Sandbox Code Playgroud)

修理:

/**
 * @throws InvalidArgumentException if $b is zero.
 */
function divide($a, $b)
Run Code Online (Sandbox Code Playgroud)

因为它必须被记录,类似于Java throws在方法原型上的显式.那应该是可能的:

// ERROR: InvalidArgumentException must be documented or caught inside method.
function calc()
{
    print divide(6, 2);
}
Run Code Online (Sandbox Code Playgroud)

PHP有一些明显的警告,但在大多数情况下,应该更早地检测到这些缺陷.有没有这样做的麻烦?

Dan*_*elM 1

您可以使用PHPCS

您需要为 PHPDOC 添加您自己的规则,这是嗅探

我想您将其添加到您的规则中:

<?xml version="1.0"?>
<ruleset name="My rules">
    <rule ref="Squiz.Commenting.FunctionCommentThrowTag" />
</ruleset>
Run Code Online (Sandbox Code Playgroud)

但我还没有测试过。已确认有效...现在我要添加 phpdoc。:/

我的 phpcs.xml:

<?xml version="1.0"?>
<ruleset name="PSR1/2">
    <description>Example</description>

    <file>./api</file>
    <exclude-pattern>*/Database/Proxies/*</exclude-pattern>

    <rule ref="PSR1" />
    <rule ref="PSR2" />
    <rule ref="Squiz.Commenting.FunctionCommentThrowTag" />

</ruleset>
Run Code Online (Sandbox Code Playgroud)
$ bin/phpcs

文件: ...ttpdocs/api/Api/Version1/Software/AbstractSoftwareController.php
-------------------------------------------------- --------------------
发现 1 个影响 1 行的错误
-------------------------------------------------- --------------------
 60| 错误| 缺少“\DomainException”异常的 @throws 标记
-------------------------------------------------- --------------------

时间:5.55秒;内存:19.5Mb