【问题标题】:PHP static code analysis tool, which detects uncaught exceptions?PHP静态代码分析工具,检测未捕获的异常?
【发布时间】:2012-01-06 06:56:12
【问题描述】:

PHP 的静态代码分析工具好像挺多的,能否请您推荐一款,可以检测 PHP 代码中抛出的异常,但从未被捕获的异常? (理论上可以停止PHP脚本的执行)。

我很高兴只看到像 throw new SomeException() 这样的东西,SomeException 扩展了 Exception

我不是在寻找太复杂的东西 - 只是为了警告我,如果我从 index.php 运行 someFunctionThatCanThrow(因为里面有 throw 语句)(你明白了),我会遇到麻烦.即使在运行时这也永远不会发生。

谢谢。

【问题讨论】:

  • 一般情况下不可能——不仅因为eval "$any_string()";$this->$anotherstring()
  • @Piskvor,我很高兴只看到throw new SomeException()。我尽量不在我的代码中使用任何类型的 PHP 魔法。
  • 这样的工具必须经过所有可能的执行路径。这简直是​​太多了(不仅对于 PHP)。
  • @KingCrunch,我很高兴看到一些错误警报。例如。如果方法 a 可以抛出异常(有 throw 语句),并且它没有在任何地方被捕获(例如,从 main() 运行),则该工具将显示,即使设置了一些条件,也会使在运行时是不可能的。
  • @Fluffy,我也是,我正在回答那些说无法完成的人。

标签: php static-code-analysis


【解决方案1】:

PHPLint 似乎是答案。例如,它解析

<?php

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

some();

,它永远不会抛出异常(除非你是过去的),进入:

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.

这正是我所要求的 :) 添加 docblock 并捕获异常不会导致 PHPLint 出现更多错误或警告。

【讨论】:

  • 谢谢,不知道这个工具。到我的 TODO 列表。
  • 不知道 PHPLint 可以做到这一点^^
【解决方案2】:

至于 2015 年,PhpStorm 存在一个 SCA 工具,可用作插件 Php Inspections (EA Extended) - 它进行这种分析,包括嵌套调用。此外,它还考虑了上下文,例如在 __toString 内导致致命的未经处理的异常,并且插件报告了这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多