在 PHP_CodeSniffer 中强制使用空格缩进而不是制表符?

din*_*o_d 2 php wordpress phpcodesniffer

在我的自定义嗅探中我添加了

<rule ref="Generic.WhiteSpace.ScopeIndent">
    <properties>
        <property name="indent" value="2" />
        <property name="tabIndent" value="false" />
    </properties>
</rule>
Run Code Online (Sandbox Code Playgroud)

它适用于内部的功能和控制结构,但例如

function test_plugin_admin_enqueue( $hook ) {
  /**
   * Load only on ?page=test-ajax-admin.php
   * The easiest way to find out the hook name is to go to the
   * options page and put print_r( $hook ); before the conditional.
   */
  if ( $hook !== 'toplevel_page_test-ajax-admin' ) {
    return;
  }

  wp_enqueue_script( 'test-plugin-admin-script', plugin_dir_url( __FILE__ ) . 'js/admin.js', array( 'jquery' ) );
}
Run Code Online (Sandbox Code Playgroud)

将会return有错误Tabs must be used to indent lines, spaces are not allowed

有没有办法在不使用制表符而仅使用空格的情况下检查其间距是否正确?

Gre*_*ood 8

如果您想使用 WordPress 编码标准,但想使用空格缩进,则需要覆盖 ScopeIndent 设置(如您所做的那样),排除全面禁止空格缩进的嗅探,并包含以下嗅探:全面禁止制表符缩进。

这个规则集可能就是您想要的:

<?xml version="1.0"?>
<ruleset name="MyStandard">
    <description>WordPress with space indent.</description>
        <rule ref="WordPress">
            <exclude name="Generic.WhiteSpace.DisallowSpaceIndent" />
        </rule>
        <rule ref="Generic.WhiteSpace.ScopeIndent">
            <properties>
                <property name="indent" value="2"/>
                <property name="tabIndent" value="false"/>
            </properties>
        </rule>
        <rule ref="Generic.WhiteSpace.DisallowTabIndent" />
</ruleset>
Run Code Online (Sandbox Code Playgroud)

如果其他人想做类似的事情但使用 4 个空格缩进,只需在规则集中更改24,它就会按照您想要的方式工作。

如果您实际上并未包含整个 WordPress 标准(可能只是WordPress-Core),则相应地更改WordPress引用。