如何通过错误消息查找phpcs规则名称以抑制遗留代码报错
维护遗留代码时,用Vim的ALE插件运行phpcs检测出大量格式错误,想临时抑制这些报错,但没法把错误消息和phpcs的规则名称对应起来,也就不知道该在exclude-patterns里排除哪些规则。你遇到的错误如下:
participant.php|1 col 1 error| Header blocks must be separated by a single blank line participant.php|5 col 18 error| Expected 1 space(s) after closing parenthesis; found newline participant.php|7 col 12 error| Space before opening parenthesis of function call prohibited participant.php|9 col 1 error| Multi-line function call not indented correctly; expected 6 spaces but found 7 participant.php|11 col 1 error| Multi-line function call not indented correctly; expected 4 spaces but found 6 participant.php|12 col 3 error| Expected 1 space after closing brace; newline found participant.php|13 col 3 error| Expected 1 space(s) after ELSE keyword; newline found participant.php|15 col 12 error| Space before opening parenthesis of function call prohibited participant.php|17 col 1 error| Multi-line function call not indented correctly; expected 6 spaces but found 7 participant.php|20 col 1 error| Multi-line function call not indented correctly; expected 4 spaces but found 6
可以用这几个简便方法找到错误对应的规则名称:
让phpcs直接输出规则名
直接在命令行运行phpcs时加上--report=full参数,比如:phpcs --report=full participant.php这样输出的错误信息里会附带完整的规则名称(比如
Squiz.Functions.FunctionDeclarationSpace.SpaceAfterCloseParenthesis)。如果是通过ALE调用phpcs,在Vim里添加配置:let g:ale_php_phpcs_options = '--report=full'之后ALE显示的错误就会包含规则名。
用phpcs的规则列表模糊匹配
针对某条错误消息,比如"Header blocks must be separated by a single blank line",可以用--list-rules配合grep模糊查找:phpcs --list-rules | grep -i "header\|blank line"找到疑似规则后,用
--describe-rule命令确认规则描述是否匹配错误消息:phpcs --describe-rule Generic.Files.InlineHTML直接查看本地规则文件
找到phpcs的标准规则目录(通常在vendor/squizlabs/php_codesniffer/src/Standards下),进入你正在使用的标准目录(比如PSR2、Squiz),查看规则类文件里的错误消息,类名去掉后缀后,用点分隔命名空间就是规则名称。比如Squiz/Functions/FunctionDeclarationSpaceSniff.php对应的规则名是Squiz.Functions.FunctionDeclarationSpace。
内容的提问来源于stack exchange,提问作者klokop

