PHPMD是PHP Depend的一个派生项目,目标是成为一个与著名的Java工具PMD相当的PHP。PHPMD可以被看作是一种用户友好的、易于为PHP Depend度量的原始指标配置前端。
PHPMD所做的是:它以给定的PHP源代码为基础,并在源代码中查找几个潜在的问题。
每个规则集中包含的规则集和规则列表。
PHPMD中的所有规则至少都必须实现\PHPMD\规则接口。您还可以扩展抽象规则基类\PHPMD\AbstractRule,它已经提供了所有必需的基础结构方法和应用程序逻辑的实现,因此留给您的惟一任务就是实现规则的具体验证代码。为了实现这个验证代码,PHPMD规则接口声明了apply()方法,该方法将在源分析阶段由应用程序调用。
class Com_Example_Rule_NumberOfPublicMethods
extends \PHPMD\AbstractRule
implements \PHPMD\Rule\ClassAware
{
const MINIMUM = 1,
MAXIMUM = 10;
public function apply(\PHPMD\AbstractNode $node)
{
$npm = $node->getMetric('npm');
if ($npm < self::MINIMUM || $npm > self::MAXIMUM) {
$this->addViolation($node);
}
}
}
这是基于度量的规则的编码部分。现在我们必须将这个类添加到一个规则集文件中。
<ruleset name="example.com rules"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
<!-- ... -->
<rule name="NumberOfPublics"
message = "The context class violates the NPM metric."
class="Com_Example_Rule_NumberOfPublicMethods"
externalInfoUrl="http://example.com/phpmd/rules.html#numberofpublics">
<priority>3</priority>
</rule>
</ruleset>
Run~ $ phpmd /my/source/example.com text /my/rules/example-rule.xml
/my/source/example.com/functions.php:2 Please do not use functions.
参考资料:
https://phpmd.org/