两款代码规范报告和修复工具 PHP Coding Standards Fixer、PHP_CodeSniffer 的简单安装和使用说明。
使用 bash 编写 Git Hooks 中的 pre-commit 钩子,实现 git commit
时检查 php 文件是否存在语法错误。其他语言也可进行参考,这里面很有想象力,能实现的东西还很多。
PHP Coding Standards Fixer(PHP 编码标准修复器)
PHP 版本需要大于等于 5.6.0
对 Atom、NetBeans、PhpStorm、Sublime Text、Vim 等编辑器有插件
安装
wget http://cs.sensiolabs.org/download/php-cs-fixer-v2.phar -O php-cs-fixer
chmod a+x php-cs-fixer
mv php-cs-fixer /usr/local/bin/php-cs-fixer
composer 方式可查看官网
升级
php php-cs-fixer self-update
composer 方式可查看官网
使用
直接修复指定文件
php php-cs-fixer fix /tmp/ArticlesController.php
修复目录下的所有文件
php php-cs-fixer fix /tmp
指定修复规范规则。默认 PSR1、PSR2
# 指定 PSR2 规则
php php-cs-fixer fix /tmp/ArticlesController.php --rules=@PSR2
# 指定多个规则
php php-cs-fixer fix /tmp/ArticlesController.php --rules=@Symfony,@PSR1,@PSR2
缓存。默认使用缓存
# 不使用缓存
php php-cs-fixer fix /tmp/ArticlesController.php --using-cache no
不实际修复文件,只查看要修复的报告差异
php php-cs-fixer fix /tmp/ArticlesController.php --dry-run --diff
PHP_CodeSniffer(PHP 美化修整器)
PHP 版本需要大于等于 5.4.0
命令的使用可以通过 -h 参数进行查看帮助。
PHP_CodeSniffer 除了下面我所罗列的安装、查看报告、设置编码标准、文件修复等,还可以设置设置报告的级别、编码,并且通过设置可以检查 JavaScript、CSS 问题。详情可查看 PHP_CodeSniffer WIKI
安装
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
php phpcs.phar -h
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar
php phpcbf.phar -h
composer 方式可以查看 PHP_CodeSniffer 安装官方文档
查看报告
# 指定单个文件
phpcs /tmp/ArticlesController.php
# 指定目录
phpcs /path/to/code
打印差异报告
打印差异报告
phpcs --report=diff /tmp/Controllers/ArticlesController.php
输出差异报告到指定文件
phpcs --report-diff=/tmp/changes.diff /tmp/ArticlesController.php
查看已经安装的编码标准
phpcs -i
指定编码标准
phpcs --standard=PEAR /tmp/ArticlesController.php
phpcs --standard=PEAR,Squiz /tmp/ArticlesController.php
使用 PSR2 编码标准对文件进行修复
phpcbf -w --standard=PSR2 /tmp/ArticlesController.php
Git Hooks 语法错误检测
写了一个逻辑简单的 Git HOOKS 的 pre-commit,作用就是在 git commit
时检查所有 PHP 文件是否存在语法错误。
Git HOOKS 的里面能做的事情非常多,大家可以发挥自己想象力,来里实现自己想做的事情,从而提高工程效率。
#!/bin/bash
# 错误消息内容
IS_ERROR_MESSAGE=()
while read st file
do
# 文件状态为 D 时跳出本次循环
if [ 'D' == "$st" ]
then
echo $file
continue
fi
# 文件末为不是 .php 时输出文件,并跳出本次循环
if [[ ! "$file" =~ (\.php$) ]]
then
echo $file
continue
fi
PHP_LINT=`php -l $file`
# 本文件不存在语法错误,输出结果,并跳出本次循环
if [ 0 -eq $? ]
then
echo $PHP_LINT
continue
fi
# 统计错误消息内容的数据个数
ERROR_COUNT=${#IS_ERROR_MESSAGE[@]}
# 将错误的存放到数组里面
IS_ERROR_MESSAGE[${ERROR_COUNT}]=$PHP_LINT
done <<EOF
`git diff --cached --name-status`
EOF
if [ -n "${IS_ERROR_MESSAGE}" ]
then
# 循环输出错误消息,并且指定文字颜色为红色
for ((i=0;i<${#IS_ERROR_MESSAGE[@]};i++))
do
echo -e "\033[31m ${IS_ERROR_MESSAGE[$i]} \033[0m"
done
exit 1
fi
exit 0