首先,您需要知道这些缩进错误来自于您的PSR2运行而不是PSR1运行。 PSR2包含了所有PSR1的检查,因此您实际上不需要执行两次PHPCS运行。如果您想遵守这两个规范,请使用--standard = PSR2即可。
至于修复,PHP_CodeSniffer的当前alpha版本包含一个名为phpcbf的脚本,可以自动为您修复错误,包括缩进问题。当我在您的文件(setup/upgrade/upgrade.php)上运行PHP_CodeSniffer的alpha版本时,我得到了以下PSR2报告:
phpcs --standard=PSR2 /path/to/file
--------------------------------------------------------------------------------
FOUND 8 ERRORS AND 1 WARNING AFFECTING 10 LINES
--------------------------------------------------------------------------------
34 | ERROR | [x] Line indented incorrectly; expected 4 spaces, found 8
36 | ERROR | [x] Line indented incorrectly; expected 8 spaces, found 12
40 | ERROR | [x] Line indented incorrectly; expected 4 spaces, found 8
43 | ERROR | [x] Line indented incorrectly; expected 8 spaces, found 12
47 | ERROR | [x] Line indented incorrectly; expected 8 spaces, found 12
51 | ERROR | [x] Line indented incorrectly; expected 12 spaces, found 16
52 | WARNING | [ ] Line exceeds 120 characters; contains 200 characters
55 | ERROR | [x] Line indented incorrectly; expected 4 spaces, found 8
60 | ERROR | [x] A closing tag is not permitted at the end of a PHP file
--------------------------------------------------------------------------------
PHPCBF CAN FIX THE 8 MARKED SNIFF VIOLATIONS AUTOMATICALLY
--------------------------------------------------------------------------------
如果我使用新的差异报告运行PHPCS,它会向我展示需要对文件进行哪些更改,包括以下代码片段:
phpcs --standard=PSR2 --report=diff /path/to/file
@@ -31,32 +31,29 @@
if ($installed_version >= $latest_version) {
echo "<p style=\"color:green\">No upgrade is necessary. Return to the <a href=\"../../\">main page</a>.</p>";
} else {
- foreach (glob(dirname(__FILE__) . '/*.inc') as $script) {
- $a = basename($script, '.inc');
- if (is_numeric($a) && ($a > $installed_version) && ($a <= $latest_version)) {
- $scripts[] = $a;
- }
+ foreach (glob(dirname(__FILE__) . '/*.inc') as $script) {
+ $a = basename($script, '.inc');
+ if (is_numeric($a) && ($a > $installed_version) && ($a <= $latest_version)) {
+ $scripts[] = $a;
}
如果您想自动修复文件,可以使用phpcbf命令而不是phpcs命令:
phpcbf --standard=PSR2 /path/to/file
Patched 1 files
Time: 78 ms, Memory: 4.50Mb
你可以在这里了解更多信息:
https://github.com/squizlabs/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically
而这个版本是你想要获取的:
https://github.com/squizlabs/PHP_CodeSniffer/releases/tag/2.0.0a1
或者,您可以克隆Github存储库并检出phpcs-fixer分支以获取最新代码。 然后,您可以从克隆中运行phpcs和phpcbf,而无需通过PEAR或Composer安装它们:
git clone -b phpcs-fixer git://github.com/squizlabs/PHP_CodeSniffer.git
cd PHP_CodeSniffer
php scripts/phpcs ...
php scripts/phpcbf ...
~/phpcsGIT/scripts/phpcbf --standard=PSR2 --sniffs=PSR2.Methods.FunctionCallSignature.Indent --report=diff *php */*php */*/*php */*/*/*php | patch -p4
这个命令可以工作,但是在phpcbf
中使用相同的命令会出现“在补丁输入中只找到垃圾”的错误。 - William Entrikenphp scripts/phpcbf /path/to/cameralife/ --standard=PSR2 --sniffs=PSR2.Methods.FunctionCallSignature.Indent
的结果是Patched 11 files Time: 2.62 seconds, Memory: 34.50Mb
,而且 git diff 看起来也不错。 - Greg Sherwood