LoginSignup
1
0

More than 1 year has passed since last update.

[PHP] git commit 時に自動でコーディング規約チェック・コード整形・コード静的解析を実行してくれるようにする

Last updated at Posted at 2021-11-27

プロジェクトに各種ツールを導入

コーディング規約チェック: PHP_CodeSniffer
コード整形: PHP-CS-Fixer
コード静的解析: PHPStan

cd <Laravelプロジェクトパス>
composer require "squizlabs/php_codesniffer=*"
composer require friendsofphp/php-cs-fixer
composer require phpstan/phpstan
composer update

git commit 時に呼び出される pre-commit の用意

cp .git/hooks/pre-commit.sample .git/hooks/pre-commit

pre-commit の編集

.git/hooks/pre-commit
# 指定ブランチへのpush防止
while read local_ref local_sha1 remote_ref remote_sha1
do
  if [[ "${remote_ref##refs/heads/}" = "master" ]]; then
    echo "Do not push to master branch"
    exit 1
  fi
done

IS_ERROR=0

# コーディング規約チェック・コード整形・静的解析
for FILE in `git diff-index --name-status $against -- | grep -E '^[AUM].*\.php$'| cut -c3-`; do
    if php -l $FILE; then
        # コーディング規約チェック
        <Laravelプロジェクトパス>/vendor/bin/phpcs --standard=PSR12 $FILE

        # コード整形
        <Laravelプロジェクトパス>/vendor/bin/php-cs-fixer fix $FILE

        # コード静的解析
        if ! <Laravelプロジェクトパス>/vendor/bin/phpstan analyse $FILE; then
            IS_ERROR=1
        fi
    else
        IS_ERROR=1
    fi
done

exit $IS_ERROR

これで git commit 時に自動でコーディング規約チェック・コード整形・コード静的解析を行ってくれるようになります。
git commit 実行時に --no-verify をつけると呼び出されません。

git commit -m "~~~" --no-verify
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0