Php_codesniffer: How can I modify PSR2 to check that the brace is on the same line as the method?

Created on 15 Sep 2015  路  3Comments  路  Source: squizlabs/PHP_CodeSniffer

I've spent now over 2h on trying to figure out how to require the { in the same line as the method declaration instead of the default requirement being the next line. How can I get this done? I've copied the PSR2 standard to a new folder to be ably to modify it to my liking.

I've tried the ruleset.xml and I've tried to modify it in the code directly without success.

    <rule ref="PEAR.Classes.ClassDeclaration">
        <properties>
            <property name="eolChar" value="{"/>
        </properties>
    </rule>
    <rule ref="PSR2R.Classes.ClassDeclaration">
        <properties>
            <property name="eolChar" value="{"/>
        </properties>
    </rule>
Awaiting Feedback Question

Most helpful comment

@aik099 is talking about class braces, but if you actually mean method braces, you'd do this in your ruleset.xml file:

<rule ref="PSR2">
    <exclude name="Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine" />
</rule>
<rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie" />

That will include the PSR2 standard, but exclude the specific message about the brace needing to be on the same line. Then, it includes the Generic sniff that forces method and function braces to be on the following line.

There is no need to copy the PSR2 standard code and make any changes for this specific case.

Does that help?

All 3 comments

I see no option in existing ClassDeclaration sniffs (I've found 4 of them in different standards) to make them configurable.

I recommend you do this:

  1. create new standard with just a ruleset.xml
  2. in the ruleset.xml include PSR2 standard
  3. mute specific PSR2 standard error that wants { to be on separate line in class declaration
  4. create simple sniff that would only check { placement in class declaration

Or maybe you can Google for other standards (you're not limited to using only PHP_CodeSniffer bundled standards) that have such check coded already.

@aik099 is talking about class braces, but if you actually mean method braces, you'd do this in your ruleset.xml file:

<rule ref="PSR2">
    <exclude name="Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine" />
</rule>
<rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie" />

That will include the PSR2 standard, but exclude the specific message about the brace needing to be on the same line. Then, it includes the Generic sniff that forces method and function braces to be on the following line.

There is no need to copy the PSR2 standard code and make any changes for this specific case.

Does that help?

Was this page helpful?
0 / 5 - 0 ratings