Search code examples
phpcodesniffer

How to configure PHP CodeSniffer to allow arrays with any indentation?


I have a custom rule set defined in an XML.

I am used to hit a tab after each => so that, if my array is multi-line, things will align nicely. It became a habit and I use that for single line arrays also. Therefore, a multi-line array might look like this

$array = array(
    'something' =>  array(
        'short'     =>  1,
        'longer'    =>  1,
    ),
);

The problem is that PHP CodeSniffer is complaining that there is more than 1 space between => and the value (since I always hit tab, there will be more than one space most of the times - of course, depending on the length of the line so far, it can also be a single space sometimes)

I tried adding the T_ARRAY token to the Generic.WhiteSpace.ScopeIndent rule definition but it didn't help

<rule ref="Generic.WhiteSpace.ScopeIndent">
    <properties>
        <property name="indent" value="4"/>
        <property name="ignoreIndentationTokens" type="array" value="T_COMMENT,T_DOC_COMMENT_OPEN_TAG,T_ARRAY"/>
    </properties>
</rule>

Is there a solution for this?

UPDATE

Ok, I realised that Generic.WhiteSpace.ScopeIndent has nothing to do with this because it's the Squiz.WhiteSpace.OperatorSpacing that is enforcing this rule. Now, according to the docs I can't configure this property to exclude the => operator. Is there any other way of doing this?


Solution

  • Unfortunately, that sniff does not have any config options to ignore this specific case. Besides adding an option to the sniff, you really only have two ways to solve this. Neither are great.

    1. You can exclude the Squiz.WhiteSpace.OperatorSpacing.SpacingAfter error code in your ruleset. This will still allow the sniff to produce errors for spacing before operators and around bitwise operators, but you wont get any errors for when you have multiple spaces after a standard operator.

    To exclude the error code, you would add this to your ruleset:

    <exclude name="Squiz.WhiteSpace.OperatorSpacing.SpacingAfter"/>
    

    2. You can write a custom sniff that extends PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff and overrides the isOperator() method. Your overridden method would detect the T_DOUBLE_ARROW token and return false, which will cause the main sniff code to stop checking double arrows. If it's not a double arrow, you can throw the request back to the parent class.

    If you do this, you need to maintain your own standard with sniffs, which means putting a directory somewhere, with a Sniffs sub-directory structure to hold your sniff.