安装pear
- 下载go-pear.phar文件,放至PHP目录下,http://pear.php.net/go-pear.phar
- 在cmd命令行下(管理员权限),进入php目录,执行 php go-pear.phar,一路回车搞定
- 在cmd命令行下 输入pear,出现help文档
pear安装phpcs
在cmd命令行下,输入安装命令:
pear install PHP_CodeSniffer
在cmd命令行下,输入 phpcs --version ,安装成功会显示版本信息
phpcs命令
忽略warning,如一行超过85字符
phpcs -n your_file
查看当前标准
phpcs -i
设置默认标准
phpcs --config-set default_standard PSR2
设置文件编码
phpcs --config-set encoding utf-8
检查PHP文件
phpcs test.php
phpcs D:\work\testApp\controller\
使用phpcbf修复
phpcbf --standard=PSR2 test.php
git集成phpcs
使用git的hook中的pre-commit,把以下代码拷贝到项目中的 .git/hook/pre-commit中,在代码commit的时候,就会运行pre-commit,调用phpcs检测代码规范性
#!/bin/bash
#
# check PHP code syntax error and standard with phpcs
# author : star[github.com/star1989]
# date : 2017-02-24
PROJECT=$(git rev-parse --show-toplevel)
cd $PROJECT
SFILES=$(git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\.php)
TMP_DIR=$PROJECT."/tmp"
# Determine if a file list is passed
if [ "$#" -ne 0 ]
then
exit 0
fi
echo "Checking PHP Lint..."
for FILE in $SFILES
do
# echo "php -l -d display_errors=0 ${FILE}"
# echo "git show :$FILE > $TMP_DIR/$FILE"
php -l -d display_errors=0 $FILE
if [ $? != 0 ]
then
echo "Fix the error before commit."
exit 1
fi
FILES="$FILES $PROJECT/$FILE"
done
if [ "$FILES" != "" ]
then
echo "Running Code Sniffer..."
TMP_DIR=/tmp/$(uuidgen)
mkdir -p $TMP_DIR
for FILE in $SFILES
do
mkdir -p $TMP_DIR/$(dirname $FILE)
git show :$FILE > $TMP_DIR/$FILE
done
phpcs --standard=PSR2 --encoding=utf-8 -n $TMP_DIR
PHPCS_ERROR=$?
rm -rf $TMP_DIR
if [ $PHPCS_ERROR != 0 ]
then
echo "Fix the error before commit."
exit 1
fi
fi
exit $?
安装phpmd
composer安装phpmd
composer global require phpmd/phpmd
在cmd命令行输入 phpmd --version,安装成功就会显示版本信息;
phpstorm集成phpcs和phpmd
File -> Default Setting -> Language & Frameworks -> Code Sniffer -> Config[Local] 点击 ... 按钮 -> path: 定位到phpcs.bat
File -> Default Setting -> Language & Frameworks -> Mess Detector -> Config[Local] 点击 ... 按钮 -> path: 定位到phpmd.bat
三、PhpStorm启用phpcs, phpmd
File -> Default Setting -> Editor -> Inspections -> PHP -> PHP Code Sniffer validation (打上勾)-> Coding standard -> PSR2 -> Apply
File -> Default Setting -> Editor -> Inspections -> PHP -> PHP Mess Detector validation (打上勾)-> Options(选择相应规则) -> Apply
网友评论