phpcs:如何修改PSR2来检查大括号与方法在同一行?

bur*_*zum 17 php rules codesniffer phpcs

我现在花了2个多小时试图弄清楚如何要求{与方法声明在同一行,而不是默认要求是下一行.我怎么能这样做?我已经将PSR2标准复制到一个名为PSR2的新文件夹,以便根据自己的喜好对其进行修改.所以我正在研究的基础基本上是我想要修改的PSR2标准.

我已经尝试过ruleset.xml,我试图在代码中直接修改它而没有成功.

<rule ref="PEAR.Classes.ClassDeclaration">
    <properties>
        <property name="eolChar" value="{"/>
    </properties>
</rule>
<rule ref="PSR2R.Classes.ClassDeclaration">
    <properties>
        <property name="eolChar" value="{"/>
    </properties>
</rule>
Run Code Online (Sandbox Code Playgroud)

我已经发现这是错的.EOL由phpcs设置.但我无法弄清楚我是否可以通过规则配置一个值.

到目前为止,这对我来说很好用(搞愚蠢的空间!):

<?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>
Run Code Online (Sandbox Code Playgroud)

但我想补充上面的规则.

Gre*_*ood 14

将此代码放在ruleset.xml文件中:

<rule ref="PSR2">
    <exclude name="Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine" />
</rule>
<rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie" />
Run Code Online (Sandbox Code Playgroud)

这将包括PSR2标准,但排除有关支架需要在同一行上的特定消息.然后,它包括Generic sniff,它强制方法和函数括号位于以下行.

有了这个改变,这段代码:

<?php
namespace Test;

class Foo
{
    public function bar() {
    }
}
Run Code Online (Sandbox Code Playgroud)

将不会产生任何错误,但直接在其上运行PSR2会产生一个错误:

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
----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)


Jor*_*eFG 7

除了Greg的答案以外,如果您使用的是PHPStorm,请转到Settings -> Editor -> Inspections -> PHP -> Code Sniffer,您会看到一个option Show sniff name

在此处输入图片说明

这将为您提供违规规则的名称(首先,在中配置PHP Code Sniffer可执行路径Settings -> Languages and frameworks -> PHP -> Code sniffer)。然后,在源代码文件中的警告工具提示上,小心地移动光标,选择文本,而无需释放按钮,请按Control C进行复制。

然后将其粘贴到规则中:

<?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>
Run Code Online (Sandbox Code Playgroud)

我在这里添加PSR2.Classes.ClassDeclaration.OpenBraceNewLine了排除规则。