如何配置PHP CodeSniffer以允许我的case语句以我喜欢的方式缩进?

Che*_*eso 7 php emacs static-analysis codesniffer

我的代码看起来像这样:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

消息是:

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

显然,CodeSniffer希望case语句比它们更简洁.

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

Che*_*eso 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
Run Code Online (Sandbox Code Playgroud)

看到了$nonIndentingScopes?它显然意味着切换语句范围内的任何内容都不会相对于范围开放卷曲缩进.

我找不到一种方法来调整这个设置PEAR.Whitespace.ScopeIndent,但是.... Sniff扩展了更基本的Generic.Whitespace.ScopeIndent,不包括T_SWITCH$nonIndentingScopes数组中.

所以我按照我想要的方式允许我的case语句是修改我的ruleset.xml文件,排除那个sniff的PEAR版本,并包含该sniff的Generic版本.它看起来像这样:

<?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>
Run Code Online (Sandbox Code Playgroud)

此文件需要存在于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