自动检查代码规范 - 使用PHP_CodeSniffer ¶
先准备一个PHP文件,比如我的是D:\test.php
,代码内容如下:
if(true)echo 123;
然后执行phpcs D:\test.php
会输出如下检查报告:
FILE: D:\test.php
----------------------------------------------------------------------
FOUND 1 ERROR AND 1 WARNING AFFECTING 1 LINE
----------------------------------------------------------------------
2 | WARNING | [x] Inline control structures are discouraged
2 | ERROR | [ ] Missing file doc comment
----------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------
Time: 19ms; Memory: 4Mb
其中它说这里有2个代码问题,第一个问题的描述是Inline control structures are discouraged
大概意思是if的执行语句不用花括号包起来不是很好,所以将代码改成
if(true){echo 123;}
这样再检查一次,则检测报告又不同了,变成了这样:
FILE: D:\test.php
----------------------------------------------------------------------
FOUND 4 ERRORS AFFECTING 1 LINE
----------------------------------------------------------------------
2 | ERROR | [ ] Missing file doc comment
2 | ERROR | [ ] Expected "if (...) {\n"; found "if(...){echo 123;"
2 | ERROR | [x] There must be a single space between the closing
| | parenthesis and the opening brace of a multi-line IF
| | statement; found 0 spaces
2 | ERROR | [x] Closing brace must be on a line by itself
----------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------
Time: 20ms; Memory: 4Mb
这下一共有4个问题,比之前更多问题了。。。其中第2个问题Expected "if (...) {\n"; found "if(...){echo 123;"
说 if(...) {
后面应该是换行才对,不应该有其它代码,所以咱们换行试试
if(true){
echo 123;
}
再运行!于是问题变成了这样:
2 | ERROR | [ ] Missing file doc comment
2 | ERROR | [ ] Expected "if (...) {\n"; found "if(...){\n"
2 | ERROR | [x] There must be a single space between the closing
| | parenthesis and the opening brace of a multi-line IF
| | statement; found 0 spaces
3 | ERROR | [x] Spaces must be used to indent lines; tabs are not
| | allowed
3 | ERROR | [x] Line indented incorrectly; expected at least 4
| | spaces, found 1
第2个问题Expected "if (...) {\n"; found "if(...){\n"
就是说if(...){
是不对的,应该是if (...) {
,好咱改成
if (true) {
echo 123;
}
运行结果:
2 | ERROR | [ ] Missing file doc comment
3 | ERROR | [x] Spaces must be used to indent lines; tabs are not
| | allowed
3 | ERROR | [x] Line indented incorrectly; expected at least 4
| | spaces, found 1
呼~~问题又变回少许了,再到这里的第2个问题说Spaces must be used to indent lines; tabs are not allowe
就是指你应该用空格缩进,不要用tab,于是把tab缩进换成空格。。。运行后终于剩下一个问题了:
2 | ERROR | Missing file doc comment
好了你听我说,不要改下去了,根本就是没完没了的,越改越多麻烦!
这么麻烦,咋办 ¶
是呀,说是说代码检查,但它太严格啦,这里不行那里不行,要满足它还真是累觉不爱
之前介绍里说过,其实我是自定义了我自己的代码风格检查逻辑来检查的,因为默认是使用官方的风格定义,那作为一个国际化的产品,自然有很多很多的约束了,深入研究它的检查风格你会发现要实现的成本还真的很大
所以我认为根据自己项目和国内的编程风格习惯来定制一套适用于自己的风格很重要,不能直接下载安装就使用官方的,不然累死你