Rector automatically rewrites PHP source with configured upgrade or quality rules. Its changes must be reviewed just like human-written code.
What It Does
Install Rector in the project rather than a global, unpinned tool. Limit transformations to explicitly chosen paths and Rector rule sets.
Requirements and Compatibility
Use a supported PHP runtime and install any third-party tool or extension explicitly shown in the examples. Commands should be run from the project root unless stated otherwise.
Syntax, Inputs and Results
The examples separate configuration, the smallest working operation and a realistic follow-up task. Adapt file paths and dependency versions to your own project.
Example 1: Basic Use
Install Rector in the project rather than a global, unpinned tool.
composer require --dev rector/rector
vendor/bin/rector --version
Example 2: Another Case
Limit transformations to explicitly chosen paths and Rector rule sets.
<?php
// File: rector.php
use Rector\Config\RectorConfig;
return RectorConfig::configure()
->withPaths([__DIR__ . '/src'])
->withPreparedSets(deadCode: true, codeQuality: true);
Practical Example
Preview, test and then apply the same configured changes.
vendor/bin/rector process --dry-run
vendor/bin/phpunit
vendor/bin/rector process
For production, apply the compatibility and edge-case limits described below.
Important Behavior and Edge Cases
Run Rector in dry-run mode first, inspect the diff, run tests, and avoid applying broad rule sets blindly.
Comparison with Related Functions and Tools
| Subject | Key difference |
|---|---|
| Direct function calls vs injectable services | Constructor injection exposes collaborators so they can be replaced during testing. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Relying on a demonstration as production validation | Add explicit error handling and test all inputs that can change behavior. |
| Skipping the prerequisite of this specific workflow | Install or configure the named tool and confirm the example can actually run. |
| Ignoring edge conditions | Run Rector in dry-run mode first, inspect the diff, run tests, and avoid applying broad rule sets blindly. |
Key Takeaways
- Rector automatically rewrites PHP source with configured upgrade or quality rules. Its changes must be reviewed just like human-written code.
- Run Rector in dry-run mode first, inspect the diff, run tests, and avoid applying broad rule sets blindly.
- Keep application configuration, source code and validation tests under version control.
Use these examples as a starting point, then validate the result with the actual PHP build, dependencies and inputs used by your application.