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

如何阻止PHP CS Fixer分离trait的use语句末尾注释?

问题场景

我常在类定义开头的trait use语句末尾添加单行注释(有时是功能说明,有时是文档链接),项目使用Laravel Pint(基于PHP CS Fixer ^1.2)整理代码。近期执行composer update后,注释会被从对应的use语句分离。

原始代码:

use \Illuminate\Database\Eloquent\Factories\HasFactory; // adds the factory static methods
use \App\Methods\SetCasts;
use \Illuminate\Database\Eloquent\SoftDeletes; // https://laravel.com/docs/9.x/eloquent#soft-deleting

执行Pint后变为:

// adds the factory static methods
use \App\Methods\SetCasts;
use \Illuminate\Database\Eloquent\Factories\HasFactory;
use \Illuminate\Database\Eloquent\SoftDeletes; // https://laravel.com/docs/9.x/eloquent#soft-deleting

我不介意use语句被排序,但注释与对应trait的关联被破坏,需要配置PHP CS Fixer避免这种情况。

解决方法

核心是调整ordered_imports规则的配置,让PHP CS Fixer在排序use语句时,将行尾注释与对应的use视为一个整体移动。

  • 找到项目中的Pint配置文件:通常是根目录下的pint.json(无则新建),或使用.php-cs-fixer.php配置文件。

  • 修改配置文件,添加/调整ordered_imports规则:
    使用pint.json的示例:

    {
        "rules": {
            "ordered_imports": {
                "sort_algorithm": "alpha",
                "imports_order": ["class", "function", "const"],
                "comments_order": ["code", "comments"]
            }
        }
    }
    

    使用.php-cs-fixer.php的示例:

    return (new PhpCsFixer\Config())
        ->setRules([
            'ordered_imports' => [
                'sort_algorithm' => 'alpha',
                'imports_order' => ['class', 'function', 'const'],
                'comments_order' => ['code', 'comments'],
            ],
        ])
        ->setFinder(PhpCsFixer\Finder::create()->in(__DIR__));
    
  • 关键参数说明:
    comments_order设置为["code", "comments"],强制让PHP CS Fixer将注释视为use语句的一部分,排序时会随use一起移动;保留sort_algorithm为alpha(默认值),满足不介意排序的需求。

  • 验证配置:执行./vendor/bin/pint重新格式化代码,此时行尾注释会和对应的use语句保持关联,不会被分离。

若上述配置无效,可检查是否开启了single_line_comment_style规则,该规则设置不当也可能导致注释位置异常,可暂时禁用或调整其配置。


内容的提问来源于stack exchange,提问作者Jay Bienvenu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:32:04