重复的代码是不好的,每个人都知道。有时我们错误地创建了这样的代码,我们从来没有注意到它。有时我们这样做是因为我们懒惰。最好是配备一个工具,它可以在构建时提示这个问题。PHPCPD - PHP复制/粘贴检测器。
通过运行以下命令来安装它:$ php composer.phar require --dev sebastian/phpcpd
然后将目标添加到build.xml:
...
在vendor目录上运行的重复代码检查的示例输出:phpcpd 4.0.0 by Sebastian Bergmann.
Found 74 clones with 2929 duplicated lines in 97 files:- /home/maciej/workspace/php-testing/vendor/phpspec/phpspec/src/PhpSpec/Matcher/TriggerMatcher.php:81-102
/home/maciej/workspace/php-testing/vendor/phpspec/phpspec/src/PhpSpec/Matcher/TriggerMatcher.php:114-135- /home/maciej/workspace/php-testing/vendor/squizlabs/php_codesniffer/src/Reports/Full.php:81-114
/home/maciej/workspace/php-testing/vendor/squizlabs/php_codesniffer/src/Reports/Code.php:162-195(...)6
想要真正深入的代码分析?如果你从头开始你的项目,你应该看看Phan - 它是一个非常强大的代码分析器,它会让你的代码变得漂亮。在https://github.com/phan/phan上查看。安装非常简单 - 只需安装php-ast扩展(在Ubuntu中,您可以尝试运行sudo apt-get install php-ast)并运行:$ php composer.phar require --dev phan/phan
然后创建一个配置文件 .phan/config.php 内容为:<?phpreturn [ 'target_php_version' => '7.1', 'directory_list' => [ 'src', 'vendor/symfony/console',
], "exclude_analysis_directory_list" => [ 'vendor/'
],
];
在build.xml文件中也创建phan目标:
...
现在,您可以运行您的代码分析,如果您犯了错误(例如……为类属性声明错误的phpdoc类型),您应该看到这样的消息:MyProject > phan:src/Domain/PriceComparator.php:17 PhanTypeMismatchProperty Assigning \Domain\PriceConverter to property but \Domain\PriceComparator::priceConverter is intsrc/Domain/PriceComparator.php:35 PhanNonClassMethodCall Call to method convert on non-class type int
Phan很神奇 - 它读取你的整个代码并对它执行多次检查,包括将phpdoc声明与实际使用变量、方法、类等进行比较,你可以查看https://github.com/phan/phan#features的所有特征列表。