使用PHP_CodeSniffer来纠正PHP编码样式
PHP_CodeSniffer是一种著名的用于检查PHP编码风格的工具,但在目前正在开发中的2.0版本中,似乎不仅可以进行检查,还可以进行修正。
自动修复错误·squizlabs/PHP_CodeSniffer Wiki
安装
在2.0版本中,因此也提供了phar文件。请从https://github.com/squizlabs/PHP_CodeSniffer/releases 下载phpcs.phar和phpcbf.phar文件。
$ curl -LO https://github.com/squizlabs/PHP_CodeSniffer/releases/download/2.0.0RC1/phpcs.phar
$ curl -LO https://github.com/squizlabs/PHP_CodeSniffer/releases/download/2.0.0RC1/phpcbf.phar
使用方法 (shǐ fǎ)
使用phpcs.phar进行检查。
$ cat test.php
<?php
if($a==2)
echo $a;
else
echo '3';
$ php phpcs.phar --standard=PSR2 test.php
FILE: C:\Users\ishida\src\test.php
--------------------------------------------------------------------------------
FOUND 7 ERRORS AFFECTING 4 LINES
--------------------------------------------------------------------------------
1 | ERROR | [x] Expected 1 space after closing brace; 0 found
2 | ERROR | [x] Expected 1 space after IF keyword; 0 found
2 | ERROR | [x] Inline control structures are not allowed
2 | ERROR | [x] Whitespace found at end of line
4 | ERROR | [x] Expected 1 space after ELSE keyword; newline found
4 | ERROR | [x] Inline control structures are not allowed
5 | ERROR | [x] Expected 1 blank line at end of file; 2 found
--------------------------------------------------------------------------------
PHPCBF CAN FIX THE 7 MARKED SNIFF VIOLATIONS AUTOMATICALLY
--------------------------------------------------------------------------------
Time: 90ms; Memory: 2.5Mb
$ php phpcs.phar --standard=PSR2 --report=diff test.php
--- test.php
+++ PHP_CodeSniffer
@@ -1,6 +1,6 @@
<?php
-if($a==2)
+if ($a==2) {
echo $a;
-else
+} else {
echo '3';
-
+}
修正可以使用phpcbf.phar来进行。
$ php phpcbf.phar --standard=PSR2 test.php
Patched 1 file
Time: 182ms; Memory: 2.5Mb
$ cat test.php
<?php
if ($a==2) {
echo $a;
} else {
echo '3';
}
在中文中,有一种有趣的功能叫做gitblame(或者svnblame、hgblame),可以查找谁在问题中添加了代码(也可称为编写记录报告)。
$ php phpcs.phar --report=gitblame src
PHP CODE SNIFFER GIT BLAME SUMMARY
--------------------------------------------------------------------------------
AUTHOR (Author %) (Overall %) COUNT
--------------------------------------------------------------------------------
ISHIDA Akio (16.18) (100) 11
--------------------------------------------------------------------------------
A TOTAL OF 11 SNIFF VIOLATIONS WERE COMMITTED BY 1 AUTHOR
--------------------------------------------------------------------------------
Time: 164ms; Memory: 2.75Mb
好的。我真的非常抱歉!
另外,作为类似的工具,也有 PHP Coding Standards Fixer 。
另外还有一个相似的工具叫做 PHP Coding Standards Fixer。