LoginSignup
1
1

More than 1 year has passed since last update.

Laravel環境にPHP-CS-Fixerを導入する

Last updated at Posted at 2022-04-07

概要

  • Laravelの開発環境にPHP-CS-Fixerを導入する方法をまとめる。

方法

  1. アプリ名ディレクトリに移動して下記コマンドを実行してtoolsディレクトリとその直下にphp-cs-fixerディレクトリを設置する。

    cd アプリ名ディレクトリ
    mkdir -p tools/php-cs-fixer
    
  2. アプリ名ディレクトリで下記コマンドを実行して、先に作成したディレクトリを指定してphp-cs-fixerのライブラリ本体をインストールする。(docker環境の場合、$ docker-compose exec php composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixerを実行するか、PHPのコンテナに入り、アプリ名ディレクトリに移動して下記コマンドを実行する。)

    composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixer
    
  3. アプリ名ディレクトリに.php-cs-fixer.dist.phpファイルを作成して下記の様に記載する。(laravelのコードをgit管理しているならこのファイルもgit管理することをおすすめする)

    アプリ名ディレクトリ/.php-cs-fixer.dist.php
    <?php 
    
    declare(strict_types=1);
    
    $finder = PhpCsFixer\Finder::create()
        // チェックするディレクトリの指定
        ->in([
            __DIR__ . '/app',
            __DIR__ . '/config',
            __DIR__ . '/database/seeders',
            __DIR__ . '/routes',
            __DIR__ . '/tests',
        ]);
    
    $config = new PhpCsFixer\Config();
    
    return $config
        ->setRiskyAllowed(true)
        ->setRules([
            '@PSR2' => true,
        ])
        ->setFinder($finder);
    
  4. 下記コマンドを実行してエラーが出なければ導入完了(docker環境の場合、$ docker-compose exec php ./tools/php-cs-fixer/vendor/bin/php-cs-fixerを実行するか、PHPのコンテナに入り、アプリ名ディレクトリに移動して下記コマンドを実行する。)

    ./tools/php-cs-fixer/vendor/bin/php-cs-fixer
    

2022/06/20追記

  • tools直下のvendorディレクトリをgitの管理から外したい場合下記の内容の.gitignoreファイルをtools直下に設置すれば良い。

    .gitignore
    .php-cs-fixer.cache
    /tools/php-cs-fixer/vendor
    
  • リポジトリで一個の.gitignoreファイルで終わらせたいならメインの.gitignoreファイルからの相対パスで当該tools直下の/vendorディレクトリを指定する。

  • ただし/vendorをgit管理下から外した場合、セットアップ時などのcomposer install実行するときにアプリ名ディレクトリとtoolsディレクトリの二箇所で実行する必要があると思う。

2022/08/29追記

  • クローンしたら通常のアプリ名ディレクトリでのcomposer installとは別に下記を実行してphp-cs-fixerをインストールする必要あり。

    composer install --working-dir=tools/php-cs-fixer
    

参考文献

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