PHP-CS-Fixer 使用指南:代码规范自动修复工具详解
PHP-CS-Fixer 项目地址: https://gitcode.com/gh_mirrors/php/PHP-CS-Fixer
工具简介
PHP-CS-Fixer 是一款强大的 PHP 代码风格自动修复工具,它能够自动检测并修复代码中不符合规范的部分,帮助开发者保持代码风格的一致性。本文将详细介绍该工具的各项功能和使用方法。
基本使用命令
fix 命令
fix
是 PHP-CS-Fixer 的核心命令,用于自动修复代码风格问题。
基础用法:
php php-cs-fixer.phar fix
如果没有配置文件,可以使用默认规则集 PSR12 修复非隐藏、非 vendor 目录下的 PHP 文件:
php php-cs-fixer.phar fix .
并行处理
对于大型项目,可以利用多核 CPU 进行并行处理以提高效率:
<?php
return (new PhpCsFixer\Config())
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect())
;
也可以手动指定并行参数:
<?php
return (new PhpCsFixer\Config())
->setParallelConfig(new PhpCsFixer\Runner\Parallel\ParallelConfig(4, 20))
;
路径处理
可以指定特定文件或目录进行修复:
php php-cs-fixer.phar fix /path/to/dir
php php-cs-fixer.phar fix /path/to/file
路径模式有两种:
override
(默认):忽略配置文件中的路径,只处理命令行指定的路径intersection
:处理命令行和配置文件中路径的交集
php php-cs-fixer.phar fix --path-mode=intersection /path/to/dir
输出格式与详细程度
支持多种输出格式:
txt
(默认)checkstyle
gitlab
json
junit
xml
php php-cs-fixer.phar fix --format=json
详细程度控制:
--quiet
:不输出任何信息--verbose
:显示应用的规则-v
:详细模式-vv
:非常详细-vvv
:调试模式
规则控制
可以指定或排除特定规则:
php php-cs-fixer.phar fix --rules=@PSR12
php php-cs-fixer.phar fix --rules=line_ending,full_opening_tag
php php-cs-fixer.phar fix --rules=-full_opening_tag,-indentation_type
也可以使用 JSON 格式配置规则:
php php-cs-fixer.phar fix --rules='{"concat_space": {"spacing": "none"}}'
其他实用选项
--dry-run
:模拟运行,不实际修改文件--diff
:输出变更的差异信息--allow-risky
:是否允许运行有风险的规则--stop-on-violation
:遇到第一个需要修复的文件时停止--show-progress
:显示进度(none/dots/bar)
其他命令
check 命令
check
命令是 fix --dry-run
的简写,用于检查但不修改代码:
php php-cs-fixer.phar check
list-files 命令
列出所有需要修复的文件,适合与 xargs 结合使用:
php php-cs-fixer.phar list-files | xargs -n 50 -P 8 php php-cs-fixer.phar fix
describe 命令
查看规则描述:
php php-cs-fixer.phar describe align_multiline_comment
php php-cs-fixer.phar describe @PSR2
缓存机制
PHP-CS-Fixer 默认启用缓存机制,只修复自上次运行后修改过的文件。可以通过配置禁用或自定义缓存文件:
<?php
$config = new PhpCsFixer\Config();
return $config
->setUsingCache(false)
->setCacheFile(__DIR__.'/.php-cs-fixer.cache');
CI 集成
在持续集成环境中使用示例:
IFS='
'
CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "${COMMIT_RANGE}")
if ! echo "${CHANGED_FILES}" | grep -qE "^(\\.php-cs-fixer(\\.dist)?\\.php|composer\\.lock)$"; then EXTRA_ARGS=$(printf -- '--path-mode=intersection\n--\n%s' "${CHANGED_FILES}"); else EXTRA_ARGS=''; fi
vendor/bin/php-cs-fixer check --config=.php-cs-fixer.dist.php -v --stop-on-violation --using-cache=no ${EXTRA_ARGS}
环境变量
PHP_CS_FIXER_IGNORE_ENV
可以忽略环境要求:
PHP_CS_FIXER_IGNORE_ENV=1 php php-cs-fixer.phar fix /path/to/dir
退出代码
- 0:成功
- 1:一般错误
- 4:文件有语法错误(仅 dry-run 模式)
- 8:文件需要修复(仅 dry-run 模式)
- 16:应用配置错误
- 32:修复器配置错误
- 64:应用内部异常
通过本文的详细介绍,开发者可以全面掌握 PHP-CS-Fixer 的使用方法,有效提升代码质量和团队协作效率。
PHP-CS-Fixer 项目地址: https://gitcode.com/gh_mirrors/php/PHP-CS-Fixer
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考