如何解决是否有使用PHP Code Sniffer强制进行严格比较===的规则?
正如标题所说。我正在寻找类似于eslint的eqeqeq的规则,但适用于PHP。我想强制使用===
/ !==
而不是==
/ !=
。
我已经尝试使用Google搜索,并搜索了他们的存储库,但不幸的是没有结果。只是想问一下在Github上发布问题之前,是否有人知道我错过的规则:)
解决方法
尝试包括Squiz.Operators.ComparisonOperatorUsage
嗅探。它强制进行严格的类型比较,包括禁止使用!$foo
来支持=== false
。
它也禁止隐式的真正比较,因此您不能做类似if ($foo)
的事情,但是如果对您的标准来说太严格了,可以通过排除Squiz.Operators.ComparisonOperatorUsage.ImplicitTrue
错误代码来禁用它。
Slevomat Coding Standard 包含专门用于禁止松散比较运算符的规则。
安装
通过 Composer 将编码标准全局安装到您的项目目录中。
composer global require slevomat\coding-standard
composer require slevomat\coding-standard --dev
参考
phpcs 通常通过 phpcs.xml
文件进行配置。使用 config 标记在此文件中添加对 slevomat 编码标准的引用。
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="PHP_CodeSniffer" xsi:noNamespaceSchemaLocation="phpcs.xsd">
<config name="installed_paths" value="{path}"/>
...
</ruleset>
如果全局安装,{path} 值可能是绝对路径,如果安装在您的项目中,则可能是相对路径。
C:\Users\{username}\AppData\Roaming\Composer\vendor\slevomat\coding-standard
vendor\slevomat\coding-standard
配置
这是一个已配置的 phpcs.xml 文件示例。我已经告诉 phpcs 使用 PSR2 规则并使用 Slevomat 编码标准中的 DisallowEqualOperators 规则。
<ruleset ...>
<config name="installed_paths" value="vendor\slevomat\coding-standard"/>
<!-- Add your rules below this line -->
<!-- Use the PSR2 rules that are included with phpcs. -->
<rule ref="PSR2">
<!--
https://github.com/slevomat/coding-standard#slevomatcodingstandardoperatorsdisallowequaloperators-
Disallows using loose == and != comparison operators. Use === and !== instead,they are much more secure and predictable.
-->
<rule ref="SlevomatCodingStandard.Operators.DisallowEqualOperators"/>
</ruleset>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。