1. 程式人生 > >PHP程式碼Git提交前新增 phpcs 語法檢查

PHP程式碼Git提交前新增 phpcs 語法檢查

1.安裝phpcs

sudo apt install php-codesniffer

設定標準

phpcs --config-set default_standard PSR2

設定編碼

phpcs --config-set encoding utf-8

2.git整合提交前程式碼檢查

開啟當前專案的.git/hooks目錄,裡面有很多xxx.sample檔案, 其中一個就是pre-commit.sample。

cp pre-commit.sample pre-commit && vim pre-commit

修改pre-commit檔案,將下面程式碼替換掉裡面的原來的程式碼

#!/bin/bash
#
# check PHP code syntax error and standard with phpcs

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 $?