使用PHPCS+GIT钩子保障团队开发中代码风格一致性实践

本文介绍了如何使用PHP CodeSniffer (PHPCS) 和 PHP Coding Standards Fixer (PHPCBF) 结合 Git 钩子来确保团队开发过程中代码风格的一致性。首先,详细讲解了安装和配置 PHPCS 和 PHPCBF 的步骤,包括设置默认编码标准。然后,通过示例展示了如何使用 PHPCS 检测代码风格问题,以及 PHPCBF 自动修复部分问题。最后,讨论了如何在 Git 的 pre-commit 钩子中添加策略,以阻止不符合编码风格的代码提交。
摘要由CSDN通过智能技术生成
  • 实现:

php-cs可以用来检测代码是否符合PSR-2规范,同时支持对不符合规范的代码自动格式化,让其转成PSR-2的编码风格。

  • 安装:

  1. 安装composer

php-cs依赖于composer,所以笔者需要先安装composer,安装的方法有很多种,这里提供mac操作系统和手动安装方法

brew install composer

手动安装composer命令为:

wget https://getcomposer.org/download/1.7.1/composer.phar && chmod 777 composer.phar && mv composer.phar /usr/local/bin/composer

 

  1. 安装PHP-CS

安装好composer之后,可以用composer快速安装php-cs,安装命令如下

composer global require "squizlabs/php_codesniffer=*"

 

当命令执行完成之后,会在笔者当前用户的主目录下创建一个 .composer 目录,在目录中包含了需要的php-cs,此时可以执行下方命令来验证是否安装成功

~/.composer/vendor/bin/phpcs  --help

当命令执行后,如果能看到下方的一些信息,那么就代表安装成功

 -     Check STDIN instead of local files and directories
 -n    Do not print warnings (shortcut for --warning-severity=0)
 -w    Print both warnings and errors (this is the default)
 -l    Local directory only, no recursion
 -s    Show sniff codes in all reports
 -a    Run interactively
 -e    Explain a standard by showing the sniffs it includes
 -p    Show progress of the run
 -q    Quiet mode; disables progress and verbose output
 -m    Stop error messages from being recorded
       (saves a lot of memory, but stops many reports from being used)
 -v    Print processed files
 -vv   Print ruleset and token output
 -vvv  Print sniff processing information
 -i    Show a list of installed coding standards
 -d    Set the [key] php.ini value to [value] or [true] if value is omitted
  1. 全局使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值