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

时间:2015-04-13 01:57:06

标签: php exception

是否有PHP的lint / static分析器会在未记录或捕获异常时发出警告?考虑一下这个例子:

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

修复:

/**
 * @throws InvalidArgumentException if $b is zero.
 */
function divide($a, $b)

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

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

PHP有一些明显的警告,但在大多数情况下,应该提前检测到这些缺陷。有没有做过这样的短信?

1 个答案:

答案 0 :(得分:1)

您可以使用PHPCS

您需要为PHPDOC添加自己的规则,here's the Sniff

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

<?xml version="1.0"?>
<ruleset name="My rules">
    <rule ref="Squiz.Commenting.FunctionCommentThrowTag" />
</ruleset>

但我还没有测试过。确认工作......现在我要添加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>
$ bin/phpcs

FILE: ...ttpdocs/api/Api/Version1/Software/AbstractSoftwareController.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 60 | ERROR | Missing @throws tag for "\DomainException" exception
----------------------------------------------------------------------

Time: 5.55 secs; Memory: 19.5Mb