我的代码如下所示:

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 中,它看起来像这样:

enter image description here

消息是:

错误 - 行缩进不正确;预期 2 个空格,发现 4 个(PEAR.WhiteSpace.ScopeIndent.In Correct)

显然 CodeSniffer 希望 case 语句的缩进量比实际少。

我如何告诉 CodeSniffer 允许我的案例语句按照我想要的方式缩进。或者更好的是, 执行 我的案例陈述是这样缩进的吗?

有帮助吗?

解决方案

嗅探被称为 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 大批。

因此,为了让我的 case 语句按照我想要的方式进行,我所做的就是修改规则集.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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top