1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2021-11-27

手順

1. 環境設定

  1. VSCodeにて拡張機能PHPStanを追加
  2. 下記のパスを通す
terminal
export PATH=$HOME/.composer/vendor/bin:$PATH

2. 各種ツールを導入

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

terminal
composer global require "squizlabs/php_codesniffer=*"
composer global require friendsofphp/php-cs-fixer
composer global require phpstan/phpstan

※ プロジェクトごとに導入する場合はcomposer require *** --devと書きます。
composer global require ***とした場合は ~/.composer/vendor にインストールされます。

3. PHPStanの設定ファイルを作成

terminal
vim ~/.composer/phpstan.neon
terminal
parameters:
    level: 8
    paths:
        - %currentWorkingDirectory%/app
        - %currentWorkingDirectory%/database
        - %currentWorkingDirectory%/tests
    excludePaths:
        - %currentWorkingDirectory%/**/*Test.php
        - %currentWorkingDirectory%/**/*TestBase.php

4. setting.json に下記を追加

setting.json
"phpstan.binPath":"/Users/[username]/.composer/vendor/bin/phpstan",
"phpstan.configFile": "/Users/[username]/.composer/phpstan.neon"

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

terminal
cd <プロジェクトのディレクトリ>
cp .git/hooks/pre-commit.sample .git/hooks/pre-commit
vim .git/hooks/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
        # コーディング規約チェック
        phpcs --standard=PSR12 $FILE

        # コード整形
        php-cs-fixer fix $FILE

        # コード静的解析
        if ! phpstan analyse $FILE; then
            IS_ERROR=1
        fi
    else
        IS_ERROR=1
    fi
done

exit $IS_ERROR

これで、git commit 時に自動でコーディング規約チェック・コード整形・コード静的解析を行ってくれるようになります。

チェック等を行いたくない場合は、 git commit 実行時に --no-verify をつけると呼び出されません。

terminal
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?