Open3
php-cs-fixer

結論
- VSCodeの拡張機能ではうまく動作しないので、gitのpre-commitでコマンドライン上からfixするようにする。

VSCodeで行なった設定
前提
-
composer
でphp-cs-fixerをインストール - vscodeの拡張でphp-cs-fixerをインストール
- 以下vscodeのsettings.json
{
"php-cs-fixer.documentFormattingProvider": true,
"php-cs-fixer.executablePath": "${workspaceFolder}/vendor/bin/php-cs-fixer",
"php-cs-fixer.config": ".php-cs-fixer.dist.php",
"php-cs-fixer.exclude": [
"**/vendor/**/*.php",
],
"php-cs-fixer.onsave": true,
"php-cs-fixer.pathMode": "intersection",
"[php]": {
"editor.defaultFormatter": "junstyle.php-cs-fixer"
},
}

ここからが実際にやってる方法
.php-cs-fixer.dist.php
<?php
$finder = PhpCsFixer\Finder::create()
->exclude('vendor')
->in(__DIR__);
$config = new PhpCsFixer\Config();
return $config
->setRiskyAllowed(true)
->setRules([
'@PSR2' => true,
'@Symfony' => true,
'binary_operator_spaces' => [
'operators' => [
'=>' => 'align',
'=' => 'align',
],
],
'no_whitespace_before_comma_in_array' => true,
'whitespace_after_comma_in_array' => true,
])
->setFinder($finder);
.git/hooks/pre-commit
#!/bin/bash
# ディレクトリ定義
ROOT_DIR=$(git rev-parse --show-toplevel)
LIST=$(git diff --name-only --cached --diff-filter=AM | grep '\.php')
# php-cs-fixer
error=false
for file in $LIST
do
# --path-modeをintersectionにすることで、Finderが無視されないようにします。
$ROOT_DIR/vendor/bin/php-cs-fixer fix --path-mode=intersection --dry-run $ROOT_DIR/$file > /dev/null 2>&1
if [ $? != 0 ]; then
echo -e " please, cs fix to $ROOT_DIR/$file"
error=true
fi
done
if "${error}"; then
echo
echo -e "\033[31mCommit fail\033[m please run \"vendor/bin/php-cs-fixer fix\" command"
exit 1
fi
- 補足として、
@Symfony
などのセットの中にルールは追加されている。
いまだに解決できていない問題
- 配列のフォーマットがうまくいかない。(一行に入れ子の配列を書いた場合でもフォーマットされない。)