Search code examples
wordpresscode-standardsphpcs

Configuring phpcs to disallow spaces after closing bracket and before closing bracket


Most of our projects are WordPress, and while we agree with the most of coding standards it sets, there are some which we disagree on and do not want to use in our own private projects. Somehow pieces of those disagreements still end up in the codebase due to devs copypasting solutions they found online, and I'd like to prevent that with phpcs. Not only because copypasting is questionable (the quality of these codesnippets is often terrible), but because it's harder to read and edit.

This is the way WordPress tells you to do it: fn_call( array( 1, 2, 3 ) );

This is the way we do it: fn_call([1, 2, 3]);

I found a way to exclude these rules from the WordPress coding standards

<exclude name="PEAR.Functions.FunctionCallSignature.SpaceBeforeCloseBracket" />
<exclude name="PEAR.Functions.FunctionCallSignature.SpaceAfterOpenBracket" />
<exclude name="WordPress.Arrays.ArrayDeclaration.NoSpaceAfterOpenParenthesis" />

but how do I enforce that there should be no spaces? I can't find anything on that.


Solution

  • You don't actually want to exclude those 2 PEAR rules. You'll want to override the setting that the WordPress standard uses instead, changing it from 1 required space to 0 required spaces.

    The WordPress Core ruleset.xml file includes this section:

    <rule ref="PEAR.Functions.FunctionCallSignature">
        <properties>
            <property name="requiredSpacesAfterOpen" value="1"/>
            <property name="requiredSpacesBeforeClose" value="1"/>
        </properties>
    </rule>
    

    By default, the PEAR.Functions.FunctionCallSignature sniff enforces that there are 0 spaces after the open brace, and 0 spaces before the close brace, which is exactly what you want. But the WordPress standard changes these settings to 1 space.

    In your ruleset.xml file, after you've included the WordPress standard, put in this section:

    <rule ref="PEAR.Functions.FunctionCallSignature">
        <properties>
            <property name="requiredSpacesAfterOpen" value="0"/>
            <property name="requiredSpacesBeforeClose" value="0"/>
        </properties>
    </rule>
    

    Along with any other exclusions that you want. But don't exclude the PEAR.Functions.FunctionCallSignature.SpaceBeforeCloseBracket and PEAR.Functions.FunctionCallSignature.SpaceAfterOpenBracket error messages or else you wont get any errors for your function calls.