Rector - Automated Refactoring
Project ini menggunakan Rector untuk automated refactoring dan code quality/type checking.
Selain Rector official, kita menggunakan package driftingly/rector-laravel
untuk rule khusus Laravel.
π¦ Installationβ
Untuk menambahkan Rector di project:
composer require --dev rector/rector
composer require --dev driftingly/rector-laravel
File konfigurasi utama Rector ada di rector.php
di root project.
βοΈ Konfigurasi Rectorβ
Contoh konfigurasi yang dipakai:
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\Php83\Rector\ClassMethod\AddOverrideAttributeToOverriddenMethodsRector;
use RectorLaravel\Set\LaravelLevelSetList;
return RectorConfig::configure()
->withPaths([
__DIR__.'/app',
__DIR__.'/bootstrap/app.php',
__DIR__.'/database',
__DIR__.'/public',
])
->withSkip([
AddOverrideAttributeToOverriddenMethodsRector::class,
])
->withPreparedSets(
deadCode: true,
codeQuality: true,
typeDeclarations: true,
privatization: true,
earlyReturn: true,
strictBooleans: true,
)
->withSets([
LaravelLevelSetList::UP_TO_LARAVEL_120,
])
->withPhpSets();
Penjelasan Configβ
-
withPaths β path folder/file yang akan di-scan oleh Rector.
-
withSkip β list rules atau rector yang ingin dilewatkan (tidak dijalankan).
-
withPreparedSets β preset Rector resmi untuk refactor otomatis:
deadCode
β hapus kode tidak terpakaicodeQuality
β optimasi kualitas kodetypeDeclarations
β menambahkan type hintsprivatization
β ubah property/method yang bisa privateearlyReturn
β refactor untuk early returnstrictBooleans
β paksa boolean strict comparisons
-
withSets β preset khusus Laravel dari driftingly/rector-laravel (
UP_TO_LARAVEL_120
) -
withPhpSets β pakai rule terbaru sesuai versi PHP yang digunakan
π Menjalankan Rectorβ
- Dry-run (cek tanpa perubahan):
composer test:refactor
# atau
vendor/bin/rector process --dry-run
- Apply fixes:
composer refactor
# atau
vendor/bin/rector process
β Pastikan commit semua perubahan sebelum menjalankan
rector process
, karena bisa melakukan banyak refactor sekaligus.
β Menghapus driftingly/rector-laravel
β
Jika ingin remove package Laravel khusus:
composer remove driftingly/rector-laravel
Efeknya:β
- Preset
LaravelLevelSetList::UP_TO_LARAVEL_120
tidak bisa dipakai lagi. - Rector tetap berjalan untuk rule default (
deadCode
,codeQuality
, dll). - Laravel-specific refactor dan patch (misal: route optimizations, Model type hints) tidak berlaku lagi.
- Jika ada konfigurasi
withSets([LaravelLevelSetList::...])
, Rector akan error β harus hapus atau ganti dengan set lain.
π‘ Tipsβ
- Jalankan dry-run dulu sebelum apply, supaya tahu apa yang akan berubah.
- Gunakan commit terpisah untuk perubahan Rector, supaya mudah rollback.
- Selalu perbarui package Rector dan Laravel preset jika upgrade Laravel.
- Contributor baru bisa menambahkan rule kustom di
rector.php
sesuai kebutuhan, lalu commit perubahan terpisah.