phpcs:检测旧式构造函数

phpcs: detecting old style constructors

我必须使用一个非常大的代码库,该代码库在过去 11 年中一直在不断开发,维护级别各不相同。

正如人们所期望的那样,较旧的代码有些混乱。还有大量的 PHP4 构造函数:

class Foo {
    private $thing;
    public function Foo($thing) {
       $this->thing = $thing;
    }
 }

此外,还有多个文件,每个文件都声明了一个以上 class。当然,其中只有程序代码的文件(许多有定义,和 有些在其中进行实际工作)。

我想使用 phpcs 到 运行 仅关于这些事情的报告:

并忽略其他一切。

是否有一些标准的 sniffs 我可以用来做这个?或者声明一个自定义规则集来检查这个的方法?

一个额外的奖励点:检测那些定义了 class 并且代码位于 class 之外的文件。

终于发现 here 我可以使用这个寻找旧式构造函数:

phpcs --standard=Squiz --extensions=php --sniffs=Generic.NamingConventions.ConstructorName .

另外,我找到了一个标准的 PhpCS 生成器 here

您还可以使用来自 "no_php4_constructor" 的修复器 PHP-CS-Fixer

如何使用?

安装包

composer require friendsofphp/php-cs-fixer

运行 src 目录

上带有 --dry-run --diff 的预览命令
vendor/bin/php-cs-fixer fix src --rules=no_php4_constructor --allow-risky=yes --dry-run --diff

运行 src 目录上的命令

vendor/bin/php-cs-fixer fix src --rules=no_php4_constructor --allow-risky=yes

就是这样。祝你今天愉快!