You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义PHPCS中PEAR.Commenting.ClassComment规则的检查标签

自定义PHPCS规则:修改PEAR类注释检查仅指定标签

核心思路很直接:继承PEAR自带的PEAR_Sniffs_Commenting_ClassCommentSniff类,重写它的protected $tags属性,只保留你需要检查的@description和@since标签即可,不需要从零写一套检查逻辑。

具体步骤:

  1. 创建自定义Sniff文件
    在你的项目里新建一个自定义标准目录,比如src/Standards/Custom/Sniffs/Commenting/ClassCommentSniff.php,代码如下:
<?php
namespace Custom\Sniffs\Commenting;

// 引入PEAR的原Sniff类
use PEAR_Sniffs_Commenting_ClassCommentSniff;

class ClassCommentSniff extends ClassCommentSniff
{
    // 只保留需要强制检查的标签,键是标签名,值设为true表示需要检查
    protected $tags = [
        '@description' => true,
        '@since'       => true,
    ];
}
  1. 编写自定义标准的配置文件
    在src/Standards/Custom目录下创建ruleset.xml,用来禁用原PEAR规则并启用你的自定义规则:
<?xml version="1.0"?>
<ruleset name="Custom">
    <!-- 先禁用PEAR自带的类注释规则 -->
    <rule ref="PEAR.Commenting.ClassComment">
        <exclude name="PEAR.Commenting.ClassComment"/>
    </rule>
    
    <!-- 启用我们自己写的类注释规则 -->
    <rule ref="Custom.Commenting.ClassComment"/>

    <!-- 如果还需要PEAR的其他规则,保留这部分并排除掉原类注释规则即可 -->
    <rule ref="PEAR">
        <exclude name="PEAR.Commenting.ClassComment"/>
    </rule>
</ruleset>
  1. 让PHPCS加载你的自定义标准
    使用命令行检查代码时,直接指定自定义标准的路径:
phpcs --standard=/path/to/your/project/src/Standards/Custom src/

或者在项目根目录的phpcs.xml里引入自定义标准,这样每次运行phpcs会自动加载:

<?xml version="1.0"?>
<ruleset>
    <rule ref="/path/to/your/project/src/Standards/Custom"/>
</ruleset>

额外说明:

如果之后需要调整标签的必填性或者其他检查逻辑,还可以重写原Sniff里的processTags等方法,比如修改某个标签是否为必填项,或者调整标签的顺序检查逻辑。

内容的提问来源于stack exchange,提问作者Peter van Garderen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:52:15