PHP Mess Detector 给出误报

PHP Mess Detector giving false positives

我正在与一个开源项目合作,我认为使用 phpmd.

实现自动代码修订是个好主意

它向我展示了许多我已经修复的编码错误。但是其中一个让我很好奇。

考虑以下方法:

/**
 * 
 * @param string $pluginName
 */
public static function loadPlugin($pluginName){
    $path = self::getPath()."plugins/$pluginName/";
    $bootPath = $path.'boot.php';
    if(\is_dir($path)){

        //Autoload classes
        self::$classloader->add("", $path);

        //If theres a "boot.php", run it
        if(is_file($bootPath)){
            require $bootPath;
        }

    }else{
        throw new \Exception("Plugin not found: $pluginName");
    }
}

在这里,phpmd 说 Else is never necessary

...An if expression with an else branch is never necessary. You can rewrite the conditions in a way that the else is not necessary and the code becomes simpler to read. ...

is_dir 将 return false 只要给定路径是文件或根本不存在,因此,在我看来,此测试根本无效。

有没有办法解决这个问题,或者干脆忽略这种情况?

结构的替代方案是这样的:

public static function loadPlugin( $pluginName ) {
    $path = self::getPath() . "plugins/$pluginName/";
    $bootPath = $path . 'boot.php';
    if( \is_dir( $path ) ) {
        // Autoload classes
        self::$classloader->add( "", $path );
        // If theres a "boot.php", run it
        if ( is_file( $bootPath ) ) {
            require $bootPath;
        }
        // A return here gets us out of the function, removing the need for an "else" statement
        return;
    }

    throw new \Exception( "Plugin not found: $pluginName" );
}

虽然我不确定这是解决方案,但它是一种避免else 情况的技术。 Else 条件会在尝试阅读代码时增加复杂性,允许函数在没有 else 条件的情况下 "flow" 可以使它们更具可读性。

我不使用phpmd,但很明显你的if声明是一个保护条款。保护子句不需要 else 分支,您可以像这样安全地重构您的代码:

/**
 * @param string $pluginName
 * @throws \Exception if plugin cannot be found
 */
public static function loadPlugin($pluginName)
{
    $path = self::getPath() . "plugins/$pluginName/";
    if (!\is_dir($path)) {
        throw new \Exception("Plugin not found: $pluginName");
    }

    // Autoload classes
    self::$classloader->add("", $path);

    // If there is a "boot.php", run it
    $bootPath = $path . 'boot.php';
    if (is_file($bootPath)) {
        require $bootPath;
    }
}

进一步阅读: