如何使用注释抑制 PHPCS 警告?
我的 TestMyClass.php
在同一个文件中有两个类定义(单元测试类),PHP Code Sniffer 报错每个类都必须单独在一个文件中.如何取消此警告?
My TestMyClass.php
has two class definitions in the same file (unit testing class), and PHP Code Sniffer complains about each class must be in a file by itself. How can I suppress this warning?
class MyClassImpl implements MyInterface
{
// ...
}
class MyClassTest extends PHPUnit_Framework_TestCase
{
// ...
}
推荐答案
您可以使用注释让 PHP_CodeSniffer 忽略文件中的特定文件或行:https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#ignoring-files-and-folders
You can get PHP_CodeSniffer to ignore specific files or lines in a file using comments: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#ignoring-files-and-folders
在这种情况下,错误将在您的第二个类定义中生成,因此您必须像这样编写第二个定义:
In this case, the error will be generated on your second class definition, so you'd have to write you second definition like this:
// @codingStandardsIgnoreStart
class MyClassTest extends PHPUnit_Framework_TestCase
{
// @codingStandardsIgnoreEnd
// ...
}
但如果不应该检查整个文件,您也可以选择忽略整个文件,使用@codingStandardsIgnoreFile 注释或在命令行上指定排除项(有关信息,请参阅上一个链接).
But you might also choose to just ignore the whole file if it is not supposed to be checked, either using the @codingStandardsIgnoreFile comment or by specifying exclusions on the command line (see the previous link for info).
如果您发现自己经常这样做并且不想在代码中添加注释,您还可以创建自己的自定义编码标准.假设您现在正在使用 PSR2 标准,您将创建一个 XML 文件(例如 mystandard.xml)并包含以下内容:
If you find that you do this a lot and you don't want to add comments to your code, you can also create your own custom coding standard. Assuming you are using the PSR2 standard right now, you'd create an XML file (e.g., mystandard.xml) and include the following content:
<?xml version="1.0"?>
<ruleset name="MyStandard">
<description>My custom coding standard.</description>
<rule ref="PSR2" />
<rule ref="PSR1.Classes.ClassDeclaration.MultipleClasses">
<severity>0</severity>
</rule>
</ruleset>
然后像这样运行 PHP_CodeSniffer:phpcs --standard=/path/to/mystandard.xml/path/to/code
Then run PHP_CodeSniffer like this: phpcs --standard=/path/to/mystandard.xml /path/to/code
拥有自己的规则集可以让您做很多事情,包括更改错误消息、更改消息的严重性或类型,包括来自其他标准的检查以及设置全局忽略规则.更多信息:https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml
Having your own ruleset lets you do a lot of things, including changing error messages, changing the severity or type of a message, including checks from other standards, and setting global ignore rules. More info here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml
相关文章