PHP Advent

#[Tooling]

Rector PHP: Automated Upgrades and Safe Refactoring

By Charles Hickle ·

An illuminated horologist workbench displays precision brass escapements, a balance wheel, and calibrated transformation gears beside an open blueprint notebook showing hierarchical tree diagrams.

Start a legacy PHP upgrade by installing Rector as a development dependency and configuring rector.php for small batches of changes. Rector automates abstract syntax tree transformations. Run a dry run (vendor/bin/rector process --dry-run) on a narrow directory first, then apply a single rule level or a targeted PHP version set. Skip rules that need manual architectural changes, and commit each step with a passing test suite. Working in stages avoids manual search-and-replace errors and keeps pull requests small enough for colleagues to review.

Upgrading syntax by hand takes time, and it is easy to miss something in a large PHP codebase. A team moving an application from PHP 7.4 to PHP 8.2 might have hundreds of constructor assignments to replace with promoted properties. Nullable arguments to string functions may need casts, and switch statements may need conversion to match expressions. Regular expressions frequently introduce syntax bugs or miss subtle type coercions during these edits. The resulting pull request can also be too large to review thoroughly.

Rector parses PHP source files into an Abstract Syntax Tree (AST) using nikic/php-parser. It can inspect class hierarchies, method signatures, argument types, and return values. When a node matches a configured rule, Rector transforms it into modern syntax and writes the code back to disk. It preserves the surrounding formatting where possible.

Automated refactoring works best alongside static analysis with PHPStan. PHPStan inspects your codebase to find typing defects, missing docblocks, and undefined method calls without modifying files. Rector uses PHPStan's type resolution engine to check whether a transformation is safe before changing an AST node. Together, static analysis and automated AST refactoring check that the updated code preserves the program's behavior.

Installing Rector and Setting Up rector.php

Install Rector in your project using Composer as a development dependency:

composer require rector/rector --dev

Keep Rector in the require-dev section of composer.json and commit the updated composer.lock file. Team members and CI runners will then use the same toolchain. Follow the usual Composer dependency management practices to prevent drift between local developer machines and automated pipelines.

Create rector.php in the root of your repository. Rector has a fluent configuration builder available through Rector\Config\RectorConfig::configure(). For full options, consult the official Rector documentation.

Start with this rector.php configuration:

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;

return RectorConfig::configure()
    ->withPaths([
        __DIR__ . '/src',
        __DIR__ . '/tests',
    ])
    ->withRootFiles();

Use withPaths() to choose the directories Rector should analyze and modify. The withRootFiles() helper includes PHP scripts in the repository root, such as standalone configuration files, so you do not have to list each file.

Target PHP Version Sets Versus Incremental Rule Levels

Rector groups refactoring rules into sets. For a PHP version upgrade, you can apply a full version set or work through incremental rule levels.

A version set enables all rules required to migrate code up to a target PHP release. You can enable version sets using the withPhpSets() method:

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;

return RectorConfig::configure()
    ->withPaths([__DIR__ . '/src'])
    ->withPhpSets();

When called without arguments, withPhpSets() uses the "php" requirement in the "require" section of composer.json. You can also select version sets explicitly with named arguments such as ->withPhpSets(php82: true). Keep that target consistent with the runtime used in production and CI.

A full version set can change thousands of lines across hundreds of files in a large legacy codebase. A pull request that size is hard to review, and subtle bugs can slip through.

For smaller batches, use rule levels through withPhpLevel(). As described in the Rector level sets documentation, levels select rules ordered from safest to most complex. Level 0 activates the single safest rule in the target version set. Level 1 adds the next rule, and each subsequent integer activates an additional transformation:

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;

return RectorConfig::configure()
    ->withPaths([__DIR__ . '/src'])
    ->withPhpLevel(0);

With levels, the team can work through an upgrade one rule at a time. Configure level 0 and run Rector, then review the diff and run the test suite. After merging that pull request, increase the level to 1 for the next sprint.

Worked Before and After Refactoring Examples

Upgrading to PHP 8 involves both automated AST refactoring and targeted manual adjustments. The following examples show an automated constructor property promotion handled by Rector alongside a manual PHP 8.1 compatibility fix for a nullable string argument in Slugger.

Constructor Property Promotion

In PHP 7.4 and earlier, class constructors required repetitive property declarations, parameter lists, and manual property assignments. PHP 8.0 introduced constructor property promotion to declare and initialize class fields in a single signature.

Here is a domain class before running Rector:

<?php

declare(strict_types=1);

namespace App\Domain;

final class InvoiceItem
{
    private string $description;
    private int $quantity;
    private int $unitPriceCents;

    public function __construct(string $description, int $quantity, int $unitPriceCents)
    {
        $this->description = $description;
        $this->quantity = $quantity;
        $this->unitPriceCents = $unitPriceCents;
    }

    public function getTotalCents(): int
    {
        return $this->quantity * $this->unitPriceCents;
    }
}

Rector detects this boilerplate and applies the rule ClassPropertyAssignToConstructorPromotionRector. Here is the class after Rector refactors the code:

<?php

declare(strict_types=1);

namespace App\Domain;

final class InvoiceItem
{
    public function __construct(
        private string $description,
        private int $quantity,
        private int $unitPriceCents
    ) {
    }

    public function getTotalCents(): int
    {
        return $this->quantity * $this->unitPriceCents;
    }
}

The transformation preserves the exact types, visibility, and parameter order, but cuts four lines of redundant boilerplate.

A split workbench view contrasts a tangled cluster of loose uncoupled brass linkages on the left with a streamlined, unified precision brass escapement mechanism on the right.

Strict String Argument Handling in PHP 8.1

Starting in PHP 8.1, passing null to non-nullable internal string functions like strlen(), explode(), and trim() is deprecated in coercive mode, as documented in the PHP 8.1 deprecations manual. In coercive mode, earlier PHP versions silently coerced null to an empty string; PHP 8.1 emits a deprecation notice.

Here is a legacy string helper before refactoring:

<?php

namespace App\Utility;

final class Slugger
{
    public function sanitize(?string $title): string
    {
        $trimmed = trim($title);

        return strtolower($trimmed);
    }
}

NullToStrictStringFuncCallArgRector is a separate rule you can enable explicitly with ->withRules([\Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector::class]), or find through the Rector rule finder. This rule acts only on arguments whose type is known to be exactly null, replacing them with empty strings. Because a nullable variable like $title may contain a string or null at runtime, Rector leaves it unchanged, so resolving the deprecation notice requires a manual (string) cast. Here is the class after applying that manual cast:

<?php

namespace App\Utility;

final class Slugger
{
    public function sanitize(?string $title): string
    {
        $trimmed = trim((string) $title);

        return strtolower($trimmed);
    }
}

Applying the (string) cast during manual review eliminates the deprecation warning. Pairing automated refactoring with targeted manual review keeps codebases reliable and ready to adopt modern PHP features.

Excluding Rules and Handling Edge Cases with withSkip()

Mature applications have code that needs to stay out of automatic refactoring, such as legacy files, third-party stubs, or domain models. Use withSkip() to exclude paths, file patterns, or individual rules. The syntax options are in the Rector configuration reference.

You can skip entire directories, target specific files, or disable a single rule for a file:

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;

return RectorConfig::configure()
    ->withPaths([
        __DIR__ . '/src',
    ])
    ->withPhpSets(php82: true)
    ->withSkip([
        // Skip an entire legacy directory
        __DIR__ . '/src/Legacy',

        // Skip any file inside a Fixture directory
        '*/Fixture/*',

        // Skip a specific file
        __DIR__ . '/src/Kernel.php',

        // Skip one rule for an entity that needs manual review
        ClassPropertyAssignToConstructorPromotionRector::class => [
            __DIR__ . '/src/Infrastructure/Persistence/InvoiceEntity.php',
        ],
    ]);

Skip a rule for a file when a framework or library relies on reflection, custom docblock annotations, or specific magic methods that the transformation would affect. Review those files manually and remove the skip when the code and its tests are ready.

Enforcing Quality in Continuous Integration

Run Rector in continuous integration once the team has upgraded a module or agreed on a rule set. The CI check prevents regressions from reaching the main branch after the initial upgrade.

The dry-run flag checks files without changing them:

vendor/bin/rector process --dry-run --no-progress-bar

As explained in the Rector CI documentation, Rector exits with status code 0 if all files adhere to the configured rules. If any file requires refactoring, Rector prints a unified diff showing the required changes and exits with status code 1, failing the CI job.

An orderly sequence of brass calibration stations with glowing green optical indicator rings validates mechanical gear alignment on dark aged walnut timber.

For GitHub Actions, use a workflow like this:

name: Rector

on:
  pull_request:
    branches: [main]

jobs:
  rector:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          coverage: none

      - name: Install Composer dependencies
        run: composer install --prefer-dist --no-progress

      - name: Run Rector Dry Run
        run: vendor/bin/rector process --dry-run --no-progress-bar

For repeat CI runs, set a stable cacheDirectory with withCache() in rector.php and persist that directory between jobs. Rector's default cache location can vary by runner, so a CI cache needs an explicit path. See the Rector CI guide for a cache action example.

Step-by-Step Staged Migration Workflow

For each batch of changes, follow these five steps:

  1. Start with passing tests and static analysis. Fix failing tests or unresolved PHPStan errors before refactoring so you can tell whether a later failure came from the change.
  2. Limit rector.php to a single rule, level, or directory. Keep multiple prepared sets across the entire repository for separate batches.
  3. Run vendor/bin/rector process --dry-run. Read the unified diff in your terminal and check that the rule behaves as intended.
  4. Apply the refactoring with vendor/bin/rector process, then use git diff to check the changes against what you expected.
  5. Run your automated test suite (vendor/bin/phpunit) and PHPStan (vendor/bin/phpstan analyse). If all checks pass, commit the refactored code and open a focused pull request.

Common Mistakes to Avoid

  • Enabling broad prepared sets on Day One: Switching on typeDeclarations: true, deadCode: true, and codeQuality: true all at once on an existing application produces thousands of changed lines. Apply a single rule level or work on a single directory at a time.
  • Skipping code formatting after refactoring: Rector changes abstract syntax trees and can leave unexpected line breaks or spacing in its output. Run a formatter such as PHP-CS-Fixer or Laravel Pint immediately afterward.
  • Running Rector without automated test coverage: AST transformations assume the code behaves according to its declared types. Rules can change edge-case behavior in legacy code that uses magic methods or loose type coercion. Keep high test coverage over the modules you refactor.
  • Omitting rector.php from version control: Some teams treat rector.php as a temporary local script. Commit it so the team and CI pipeline use the same configuration.
  • Ignoring a rule change that does not appear in the diff: If a newly configured rule seems to have no effect, run vendor/bin/rector process --clear-cache --dry-run once before investigating the rule or file scope.
An open engineering notebook shows hand-drawn gear diagrams with crossed-out red schematic mistake branches beside an unseated brass pinion and precision tweezers.

Frequently Asked Questions

What is the difference between Rector and PHP-CS-Fixer?

PHP-CS-Fixer inspects and modifies PHP tokens to enforce coding standards, indentation, whitespace, and bracket positioning. Rector inspects and modifies the Abstract Syntax Tree (AST), changing language constructs, class hierarchies, method signatures, and types. Teams typically run Rector first to modernize syntax, followed by PHP-CS-Fixer to format the resulting code.

Can Rector break dynamic code?

Yes. Static AST analysis may not work out the runtime types when code relies on dynamic property access, unannotated magic methods, or variable variables. Pair Rector with thorough unit and integration tests. Use withSkip() for dynamic legacy modules that need protection.

How does Rector use PHPStan under the hood?

Rector uses PHPStan's type and reflection information to help rules decide whether they can change an expression. Review the diff and run tests because runtime-only behavior remains outside static analysis.

How should teams handle framework-specific upgrades?

Check Rector's available framework sets and each framework's migration guide before enabling specialized rules. Scope a framework upgrade to one package or module, inspect the dry-run diff, and run the framework's test suite after applying it.