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

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


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:

<?phpnamespace 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----------------------------------------------------------------------


In addition to the answer from Greg, if you are using PHPStorm, go to Settings -> Editor -> Inspections -> PHP -> Code Sniffer and you will see an option Show sniff name.

enter image description here

This will give you the name of the offending rule (first, configure the PHP Code Sniffer executable path in Settings -> Languages and frameworks -> PHP -> Code sniffer). Then on the warning tooltip in your source code file, carefully move the cursor, select the text and without releasing the button, press Control C to copy it.

Then you paste it in the rules:

<?xml version="1.0"?><ruleset name="PSR2R">    <rule ref="PSR2">        <exclude name="Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine" />        <exclude name="PSR2.Classes.ClassDeclaration.OpenBraceNewLine" />    </rule>    <rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie" /></ruleset>

I have added here PSR2.Classes.ClassDeclaration.OpenBraceNewLine to the excluded rules.