PHP 代码规范

文章内容
  1. CodeSniffer

PHP 常用代码规范检查工具如下:

工具 lint 命令 支持 IDE
CodeSniffer phpcs –standard=PSR12 app/ VSCodeIDEA
PHPMD phpmd app/ VSCode
PHPStan phpstan analyse app tests VSCode

CodeSniffer

CodeSniffer 内置多种规范,其中常用的「PSR12」规范包括下列规则:

  • 每行代码最大长度 120 个字符;
  • 运算符左右各 1 个空格;

安装:

$ composer require --dev squizlabs/php_codesniffer

全量检查:

$ ./vendor/bin/phpcs --standard=PSR12 src/

FILE: laravel-wechat/src/ServiceProvider.php
-------------------------------------------------------------------
FOUND 30 ERRORS AND 1 WARNING AFFECTING 12 LINES
-------------------------------------------------------------------
  43 | ERROR   | [x] Expected at least 1 space before "."; 0 found
  43 | ERROR   | [x] Expected at least 1 space after "."; 0 found

  91 | WARNING | [ ] Line exceeds 120 characters; contains 130 characters

 101 | ERROR   | [x] Expected at least 1 space before "."; 0 found
 101 | ERROR   | [x] Expected at least 1 space after "."; 0 found

本地增量检查:

git diff --diff-filter=d --name-only HEAD | grep ".php$" | xargs ./vendor/bin/phpcs --standard=PSR12

持续集成合并请求增量检查:

sh "git diff --diff-filter=d --name-only ${env.MR_TARGET_BRANCH}... | grep '.php\$' | xargs ./vendor/bin/phpcs --standard=PSR12"
上一篇Markdown 代码块编程语言清单
文档是否对您有用?
感谢反馈有用
感谢反馈没用