Is there a lint/static analyser for PHP that will warn when exceptions are not documented or caught? Consider the example:
// ERROR: InvalidArgumentException must be documented or caught inside method.
function divide($a, $b)
{
if (0 == $b) {
throw new InvalidArgumentException();
}
return $a / $b;
}
To fix:
/**
* @throws InvalidArgumentException if $b is zero.
*/
function divide($a, $b)
Since it must be documented, similar to Java's explicit throws
on the method prototype. Then this should be possible:
// ERROR: InvalidArgumentException must be documented or caught inside method.
function calc()
{
print divide(6, 2);
}
There are some obvious caveats with PHP, but in most cases these defects should be detected earlier. Is there any linters that do this?
You can use PHPCS
You'll need to add your own rules for PHPDOC, the here's the Sniff
I guess you add it to your rules with:
<?xml version="1.0"?>
<ruleset name="My rules">
<rule ref="Squiz.Commenting.FunctionCommentThrowTag" />
</ruleset>
But I haven't tested that. Confirmed works... now I have phpdoc to add. :/
My 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With