1
1

More than 1 year has passed since last update.

php-cs-fixerをvscodeに設定する ハマりポイントも添えて

Posted at

目的

php-cs-fixerをvscodeで動作させるのに想定以上に時間がかかったのでその備忘録として

取り扱わないこと

  1. php-cs-fixerのそれぞれの設定の意味
    PHP-CS-Fixer configurationを読んだ方が分かりやすいです
  2. php-cs-fixerやphpのインストール方法

前提

php-cs-fixerと動かすphpはダウンロード済み

.php-cs-fixer.phpを設定

<?php

$target_dir = ""; // 任意のディレクトリ
return (new PhpCsFixer\Config())
    ->setRiskyAllowed(false)
    ->setRules([
        // configurationを見ながら設定
    ])
    ->setFinder(
        PhpCsFixer\Finder::create()
            ->in($target_dir)
            ->exclude([
                // 除外ファイル/ディレクトリを指定
            ])
            ->name('*.php')
    )

ハマりポイント

$target_dirをルートディレクトリとして、そこからの相対パスを指定
/path/to/working/hoge/fuga/のfuga配下を除外したい場合、$target_dir = /path/to/working; であれば'hoge/fuga', と指定する

vscodeで設定する方法

php-cs-fixer拡張を入れる

settings.jsonを設定

{
    "php-cs-fixer.documentFormattingProvider": true,
    "php-cs-fixer.excutablePath": "php-cs-fixer",
    "php-cs-fixer.excutablePathWindows": "php-cs-fixer.bat", // windowsで利用する場合こちらを設定
    "php-cs-fixer.exclude": [
        // .php-cs-fixer.phpと異なる
        // **/hoge/**/*.php のように設定する
        "",
    ],
    "php-cs-fixer.onsave": true,
    "php-cs-fixer.pathMode": "intersection",
    [php]: {
        "editor.defaultFormatter": "junstyle.php-cs-fixer"
    },
}

ハマりポイント

  1. .php-cs-fixer.phpのexcludeを設定しているのに保存時のフォーマットが行われる
    • プラグインの問題でonsave時に実行されるとpathModeがoverrideで実行されてしまうため.php-cs-fixer.phpのsetFinderの内容が上書きされてしまう

      intersection mode only works on explorer context menu action.
      参照

    • そのため、onsaveとexcludeをどちらも利用する際はsettings.jsonのexcludeを設定する
  2. excludeを設定しているのにフォーマットされる
    • コマンドパレット(cmd + shift + p)から実行するときは"php-cs-fixer.pathMode": "intersection"を設定していないとoverrideで実行される
  3. excludeは**/から始めないと認識してくれない
    https://github.com/junstyle/vscode-php-cs-fixer/issues/173

まとめ

分からないことがあれば公式ドキュメントやリポジトリのissueを探そう
大体のことは記載 or 質問済みです

1
1
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
1