Search code examples
phpphpcodesniffer

Custom codesniffer rules / sniffs


I'm looking for custom rules extending the PSR2 standard for CodeSniffer, but could not find a reliable solution.

Here is a sample code:

if ($var1==$var2) {
    $var3=1;
    $var4 = array("test"=>"test1");
}

I need to enforce spaces around the == >= <= and != as well as when assigning variables $var3 = 1; and => as well.

I have created a custom standard named MyStandard which extends PSR-2, where I have put rules for the cyclomatic complexity, line lengths and tab indents instead of spaces, but can't solve those last ones.

Edit: My current ruleset.xml looks like this:

<?xml version="1.0"?>
<ruleset name="MyStandard">
    <description>PSR2 with tabs instead of spaces.</description>
    <arg name="tab-width" value="4"/>
    <rule ref="PSR2">
        <exclude name="Generic.WhiteSpace.DisallowTabIndent"/>
        <exclude name="PSR1.Classes.ClassDeclaration.MissingNamespace"/>
    </rule>
    <rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/>
    <rule ref="Generic.WhiteSpace.ScopeIndent">
        <properties>
            <property name="indent" value="4"/>
            <property name="tabIndent" value="true"/>
        </properties>
    </rule>
    <rule ref="Generic.Files.LineLength">
        <properties>
            <property name="lineLimit" value="140"/>
            <property name="absoluteLineLimit" value="160"/>
        </properties>
     </rule>
     <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
         <properties>
             <property name="ignoreBlankLines" value="false"/>
         </properties>
     </rule>
     <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace.StartFile">
         <severity>10</severity>
     </rule>
     <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace.EndFile">
         <severity>10</severity>
     </rule>
     <rule ref="Generic.Metrics.CyclomaticComplexity"/>
</ruleset>

Solution

  • Figured it out, thanks to @MarkBaker.

    I've used the proposed sample and modified it to check for T_EQUAL, T_IS_NOT_EQUAL, T_IS_EQUAL, T_DOUBLE_ARROW, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_GREATER_OR_EQUAL and T_IS_SMALLER_OR_EQUAL

    If anyone is interested, here is the complete ruleset.