PHP static code analysis tool, which detects uncau

2019-01-27 00:37发布

问题:

There seems to be quite a lot of static code analysis tools for PHP, could you please suggest the one, which can detect exceptions, which are thrown in the PHP code, but are never caught? (the ones, which can theoretically stop the execution on the PHP script).

I would be happy enough to see only stuff like throw new SomeException(), where SomeException extends Exception.

I am not looking for something too sophisticated - just to warn me that if I run someFunctionThatCanThrow ('cause there is throw statement inside) from index.php (you get the point), I can get in trouble. Even if in the runtime that would never happen.

Thanks.

回答1:

PHPLint seems to be the answer. For example, it parses

<?php

function some()
{
    if (time() == 123) {
        throw new Exception("I can't happen");
    }
}

some();

, which will never throw an exception (unless you're in the past), into:

BEGIN parsing of test-cSdHoW
1:      <?php
2:      
3:      function some()
4:      {
5:       if (time() == 123) {
6:        throw new Exception("I can't happen");

          throw new Exception("I can't happen");
                                                \_ HERE
==== 6: notice: here generating exception(s) Exception

          throw new Exception("I can't happen");
                                                \_ HERE
==== 6: ERROR: exception(s) must be caught or declared to be thrown: Exception
7:       }
8:      }
9:      
10:     some();
==== 3: notice: guessed signature of the function `some()' as void()

        some();
             \_ HERE
==== 10: notice: here generating exception(s) Exception

        some();
             \_ HERE
==== 10: Warning: uncaught exception(s): Exception
END parsing of test-cSdHoW
==== ?: notice: unused package `dummy.php'
==== ?: notice: required module `standard'
Overall test results: 1 errors, 1 warnings.

So that's exactly what I was asking for :) Adding a docblock and catching the exception results in no more errors or warnings from PHPLint.



回答2:

As for 2015, for PhpStorm exists a SCA tool available as plugin Php Inspections (EA Extended) - it does this kind of analysis, including nested calls. Plus it takes context into consideration, e.g. within __toString unhanded exceptions leading to fatals and the plugin reports this.