Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a linter for PHP that makes all exceptions explicit like Java?

Tags:

exception

php

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?

like image 333
Elliot Chance Avatar asked Nov 10 '22 16:11

Elliot Chance


1 Answers

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
like image 114
DanielM Avatar answered Nov 15 '22 05:11

DanielM