Search code examples
phpwordpressphpcodesniffer

Force space indentation instead of tabs in PHP_CodeSniffer?


In my custom sniff I added

<rule ref="Generic.WhiteSpace.ScopeIndent">
    <properties>
        <property name="indent" value="2" />
        <property name="tabIndent" value="false" />
    </properties>
</rule>

Which works for functions and control structures within, but for instance

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' ) );
}

the return will have error Tabs must be used to indent lines, spaces are not allowed.

Is there a way to check for correct spacing for that as well, while not using tabs, but only spaces?


Solution

  • If you want to use the WordPress coding standard but you want to indent using spaces, you will need to overwrite the ScopeIndent settings (as you've done), exclude the sniff that provides a blanket ban on space indenting, and include the sniff that provides a blanket ban on tab indenting.

    This ruleset is probably what you want:

    <?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>
    

    If anyone else wants to do something similar but uses a 4-space indent, just change 2 to 4 in the ruleset and it will work the way you want.

    If you don't actually include the whole WordPress standard (maybe just WordPress-Core) then change the WordPress ref accordingly.