どの会社でも同じようなwikiを書いているので、ここにまとめておきます。
Rectorとは
PHPの自動リファクタリングができるツールです。
フレームワークのアップグレードによるコードの書き換え、自動型付けなどで活用できます。
使い方
パッケージインストール
$ composer require rector/rector --dev
実行(設定ファイル rector.php が存在しない場合は作成される)
$ vendor/bin/rector
Laravel用のRectorプラグイン
$ composer require driftingly/rector-laravel --dev
https://github.com/driftingly/rector-laravel
rector.phpサンプル
自動で型付けしたい
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
return RectorConfig::configure()
->withPaths([
__DIR__ . '/app',
])
->withImportNames(importShortClasses: false)
->withTypeCoverageLevel(0);
typeDeclarationsを有効にすると以下のRectorルールが適用されます。 https://getrector.com/find-rule?rectorSet=core-type-declarations&activeRectorSetGroup=core
withTypeCoverageLevelで段階的な適用もできます。 https://getrector.com/documentation/levels
withImportNamesを入れるとuseも適切に付与してくれます。 https://getrector.com/documentation/import-names
旧Factoryから新Factoryに移行したい
古いLaravelからバージョンアップするとき限定ですが…
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use RectorLaravel\Set\LaravelSetList;
return RectorConfig::configure()
->withPaths([
__DIR__ . '/app',
])
->withImportNames(importShortClasses: false)
->withSets([
LaravelSetList::LARAVEL_LEGACY_FACTORIES_TO_CLASSES,
]);
参考: https://zenn.dev/zatsuyooo/articles/laravel7-to-8
ルーティングの記述方法を配列方式に変更
routes.php で 'UserController@index' の形式から [UserController::class, 'index'] の形式に変更したい場合に使う
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use RectorLaravel\Rector\StaticCall\RouteActionCallableRector;
return RectorConfig::configure()
->withPaths([
__DIR__ . '/routes',
])
->withImportNames(importShortClasses: false)
->withConfiguredRule(RouteActionCallableRector::class, [
RouteActionCallableRector::NAMESPACE => 'App\Http\Controllers',
]);
関連URL
- https://getrector.com/find-rule
- Rectorルールを探すときに活用ください
- https://getrector.com/ast
- カスタムルールを作るときなどASTの構造を知りたいときに便利です
- https://getrector.com/demo
- WebでRectorの動作を確認できるツール