Rector — Automated PHP Upgrades & Refactoring
Also Known As
TL;DR
Explanation
Rector (Reconstruct, Refactor) uses PHP-Parser to build an AST, applies transformation rules, and rewrites the source files. Primary uses: automated PHP version upgrades (replace deprecated functions, add typed properties, convert to match expressions, add return types), framework migrations (Symfony 4→5→6, Laravel upgrades, PHPUnit version migrations), and custom rule sets for enforcing architectural patterns. Run rector process --dry-run to preview changes; rector process to apply them. Commit Rector output as a separate commit for clean diffs. Write custom Rector rules to automate project-specific refactors — extracting a recurring pattern into a method or renaming a class across the codebase. Pair with PHPStan to validate the output is type-correct.
Common Misconception
Why It Matters
Common Mistakes
- Running Rector on the whole codebase without reviewing changes — automated changes can be wrong.
- Not committing before running Rector — no clean rollback if a rule causes issues.
- Using only the 'upgrade' rule set and ignoring code quality rules that reduce complexity.
- Not creating a custom Rector rule for project-specific repetitive refactors.
Code Examples
# Running Rector without review — risky:
rector process src/ --no-diffs # Applies changes silently
# Safe workflow:
git stash # Clean state
rector process src/ --dry-run # Preview changes
# Review output, adjust rector.php rules
rector process src/ # Apply after review
git diff # Review all changes before committing
// Rector — automated PHP refactoring and upgrades
// Install:
$ composer require --dev rector/rector
// rector.php config
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\SetList;
use Rector\Set\ValueObject\LevelSetList;
return RectorConfig::configure()
->withPaths([__DIR__ . '/src', __DIR__ . '/tests'])
->withSets([
LevelSetList::UP_TO_PHP_83, // upgrade deprecated syntax
SetList::DEAD_CODE, // remove dead code
SetList::CODE_QUALITY, // simplify expressions
SetList::TYPE_DECLARATION, // add missing type hints
]);
// Dry run first:
$ vendor/bin/rector process --dry-run
// Apply:
$ vendor/bin/rector process
$ composer test // verify nothing broke