The purpose of this article is to identify the differences between PHPLint, PHP-CS-Fixer and PHP_CodeSniffer, choose based on current company needs, and write a simple custom rule.
Analysis of Lint Tools
PHPLint is the only lint tool I have used among the three, and the other two are more well-known automatic syntax specifications or static error locating tools in the PHP field.
Each tool is installed and running on the basis of three tests:
- Show errors, auto-fix (if available)
- A line of code to skip a specific check
- Toggle rule set.
- Close a rule.
- Write a custom rule.
With reference to the activeness of the open source community, the main exploration points this time will also be placed on the latter two.
PHP-CS-Fixer
The environment states that PHP 7.4 is the minimum version it requires.
A word of caution: please make sure your PHP is at least in the LTS version, otherwise it will lose subsequent security patches.
It supports multiple installation methods: PHAR, Composer, etc.
Install through composer require friendsofphp/php-cs-fixer
, then run: vendor/bin/php-cs-fixer fix some_path
.
If you install it globally, you don't need to call the executable file of the vendor directory, but consider whether the specification is global, otherwise it is more appropriate to write a shell.
Display errors, auto-fix
Take the Laravel Demo I wrote as an example: vendor/bin/php-cs-fixer fix app/Http/
, I successfully converted my if (expression) once_line_code, nothing wrong.
Use vendor/bin/php-cs-fixer fix app/Http --dry-run --diff
, so that the file will not be modified, and the specific problems and recommended modifications of the test results can be obtained.
A line of code to skip a specific check
Based on Issue 4512 , currently not supported.
Toggle rule set
Through /.php-cs-fixer.dist.php
, you can easily define your own configuration file - which covers the changes of specific rules, rule sets, file directories to be checked, directories to be excluded from checking, etc.
Simple try: replace with PSR12 and turn on insecure repair mode, no problem.
turn off a rule
This tool uses the minimum rule default, so if it is not included in the configuration file, the detection of the corresponding rule can be abandoned.
CI
The official provides the corresponding command, so that you can efficiently incorporate it into the CI build process.
Write custom rules
Tried adding a App/test_rule
rule. The advantages are as follows:
- It is simple to write. Under the premise of interface constraints, it is basically written in readable Functions;
- The rules are stored flexibly, and the rule class can be placed directly under any project path - you can also write a package to isolate it, if you like;
- The reference is strong, although there is a lack of enough custom rule writing guides, but you can easily find all the rule classes, read, understand, program, and loop well.
- Basically follow the
\PhpCsFixer\Fixer\FixerInterface
interface, more self-reference documents.
PHP_CodeSniffer
The environment states that PHP 5.4 is the minimum version it requires, but certain rules require higher versions of PHP support.
Similar to CS-Fixer, it also provides a variety of installation methods, the old way:
composer require "squizlabs/php_codesniffer=*"
Display errors, auto-fix
Take the Laravel Demo I wrote as an example: ./vendor/bin/phpcs app/Http/
.
Shows a dense number of error prompts: Line | Level | Message. Well, it smells like PHPLint.
One of its tools: phpcbf
allows you to automatically fix problems you find - if you can.
If we want to access CI, PHP CS provides corresponding Actions that you can integrate into the build process.
A line of code to skip a specific check
CS provides skipping files, skipping a line, temporarily closing, and even not checking a rule for the next line.
Simply test the above, for example, by // phpcs:ignore
, you can skip a line of detection, you can find more and more detailed explanations from the documentation.
Toggle rule set
With .phpcs.xml
or similar (it actually supports several different names...), we can define the configuration:
<rule ref="/path/to/standards/Generic/Sniffs/Commenting/TodoSniff.php"/>
This adds the corresponding ToDo Sniff rule.
turn off a rule
Consistent with CS Fixer, as long as no corresponding rules are included. We feel that it supports many rules by default because its default configuration is more comprehensive.
The naming is simpler than CS Fixer, but the list of rules is harder to find.
CI
The official support of PHP CS is Github CI Action, and there is no suitable support for distribution and diff requirements.
Nonetheless, you can give it reasonable hints based on commit or PR scope via diffFilter .
Tried it, and tweaking the shell and hooks is slightly time consuming compared to the PHP CS Fixer.
Write custom rules
CS calls the rules a sniffer (Sniff), and supports general rules such as PSR2 and PSR12. It feels like there are fewer rules than what Fixer provides, but that's okay, let's try adding a test_rule
rule.
First of all, it is pointed out that CS has a complete Step-To-Step tutorial to guide you how to write your own rules. If you want to use CS in your own technology stack, it is recommended to read it directly (official Wiki guide), not blogs like mine article.
start.
First of all, let's create our own rule directories and files directly in the project like Fixer. While maintaining flexibility, we can still extract them as Composer Packages later.
We call the directory containing custom rule sets , definition files, etc. MyStandard
, enter it and create ruleset.xml
It can define the specific conditions of the rules.
The format is roughly:
<?xml version="1.0"?>
<ruleset name="MyStandard">
<description>A custom coding standard.</description>
</ruleset>
So, this rule is called the MyStandard rule set, which will contain one or more actual sniffers to perform the checks.
Then create a directory MyStandard/Sniffs
, in order not to confuse you, I directly use a nested structure to indicate its actual location. This will house the sniffer files.
Then we sniff the comments and proceed to create the directory MyStandard/Sniffs/Commenting
, in which we create the DisallowHashCommentsSniff.php
sniffer (file).
The directory under Sniffs is not really important, it is just for the convenience of distinguishing more sniffers. If you like, you can also throw a dozen rules together to achieve the "hodgepodge" that software engineers hate (:D) .
Like Fixer, it also specifies an interface - Only Once, PHP_CodeSniffer\Sniffs\Sniff
, just inherit and implement key methods.
-
supportedTokenizers
Attribute definition: file types to sniff, PHP, JS, Rust, etc. -
register
Method definition: sniffed code type, single-line comment, multi-line comment, single-line code, code block, etc. process
Method definition: actual error checking and processing.- The system provides
addError / addWarning
as a method for adding error information.
- The system provides
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['content']{0} === '#') {
$error = 'Hash comments are prohibited; found %s';
$data = array(trim($tokens[$stackPtr]['content']));
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}
}
Finally, we use phpcs --standard=/path/to/MyStandard has_error_code.php
to try to detect a has_error_code.php
file, which contains some errors.
/path/to/MyStandard
defines the location of our rule set to help CS find rule sets outside the package.
Give it a try!
Lastly, the sniffed file type doesn't support Rust, that's a joke - although you can make it do so - it's weird.
In any case, which tool you prefer, have fun!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。