7

我的代码如下所示:

function processRequest() {

  // get the verb
  $method = strtolower($_SERVER['REQUEST_METHOD']);

  switch ($method) {
    case 'get':
      handleGet();
      break;
    case 'post':
      handlePost();
      // $data = $_POST;
      break;
    case 'delete':
      handleDelete();
      break;
    case 'options':
      header('Allow: GET, POST, DELETE, OPTIONS');
      break;
    default:
      header('HTTP/1.1 405 Method Not Allowed');
      break;
  }
}

PHP CodeSniffer 抱怨这些 case 语句的缩进。在带有 flymake 的 emacs 中,它看起来像这样:

在此处输入图像描述

消息是:

error - 行缩进不正确;预期 2 个空格,找到 4 个(PEAR.WhiteSpace.ScopeIndent.Incorrect)

显然 CodeSniffer 希望 case 语句的缩进比它们少。

我如何告诉 CodeSniffer 允许我的 case 语句以我想要的方式缩进。或者更好的是,强制我的案例陈述以这种方式缩进?

4

1 回答 1

12

Sniff 被称为PEAR.Whitespace.ScopeIndent在代码文件中定义phpcs\CodeSniffer\Standards\PEAR\Sniffs\Whitespace\ScopeIndentSniff.php,包括以下代码:

class PEAR_Sniffs_WhiteSpace_ScopeIndentSniff extends Generic_Sniffs_WhiteSpace_ScopeIndentSniff
{
    /**
     * Any scope openers that should not cause an indent.
     *
     * @var array(int)
     */
    protected $nonIndentingScopes = array(T_SWITCH);

}//end class

看到了$nonIndentingScopes吗?这显然意味着 switch 语句范围内的任何内容都不会相对于范围打开的花括号缩进。

我找不到在 中调整此设置的方法PEAR.Whitespace.ScopeIndent,但是.... Sniff 扩展了更基本的Generic.Whitespace.ScopeIndent,它不包含T_SWITCH$nonIndentingScopes数组中。

因此,为了按照我想要的方式允许我的案例陈述,我所做的就是修改我的 ruleset.xml 文件,排除该嗅探的 PEAR 版本,并包含该嗅探的通用版本。它看起来像这样:

<?xml version="1.0"?>
<ruleset name="Custom Standard">
  <!-- http://pear.php.net/manual/en/package.php.php-codesniffer.annotated-ruleset.php -->
  <description>My custom coding standard</description>

  <rule ref="PEAR">
         ......
    <exclude name="PEAR.WhiteSpace.ScopeIndent"/>
  </rule>

   ....

  <!-- not PEAR -->
  <rule ref="Generic.WhiteSpace.ScopeIndent">
    <properties>
      <property name="indent" value="2"/>
    </properties>
  </rule>

</ruleset>

该文件需要存在于 PHP CodeSniffer 的 Standards 目录下的子目录中。对我来说,文件位置是\dev\phpcs\CodeSniffer\Standards\MyStandard\ruleset.xml

然后我像这样运行phpcs:

\php\php.exe \dev\phpcs\scripts\phpcs --standard=MyStandard --report=emacs -s file.php

于 2012-03-11T06:17:17.467 回答