Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 named PSR2 to be ably to modify it to my liking. So the base I'm working on is basically the PSR2 standard which I would like to modify.

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>

I've already figured out that this is wrong. The EOL is set by phpcs. But I can't figure out if there is at all a value I can configure via a rule.

This works fine for me so far (screw the silly spaces!!!):

<?xml version="1.0"?>
<ruleset name="PSR2R">
    <description>PSR2 with tabs instead of spaces.</description>
    <arg name="tab-width" value="4"/>
    <rule ref="PSR2">
        <exclude name="Generic.WhiteSpace.DisallowTabIndent"/>
    </rule>
    <rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/>
    <rule ref="Generic.WhiteSpace.ScopeIndent">
        <properties>
            <property name="indent" value="4"/>
            <property name="tabIndent" value="true"/>
        </properties>
    </rule>
</ruleset>

But I would like to add the rule above.

like image 511
floriank Avatar asked Sep 15 '15 12:09

floriank


1 Answers

Put this code 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.

With that change, this code:

<?php
namespace Test;

class Foo
{
    public function bar() {
    }
}

Will produce no errors, but running PSR2 directly over it produces one error:

FILE: temp.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 6 | ERROR | [x] Opening brace should be on a new line
----------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------
like image 77
Greg Sherwood Avatar answered Sep 21 '22 17:09

Greg Sherwood