Skip to content

Rector: modernising old PHP code one level at a time

Published on

PHPStan tells you what is wrong. Rector rewrites the code. $a ? $a : $b becomes $a ?: $b, substr($x, 0, 3) === 'abc' becomes str_starts_with(), a property plus an assignment in the constructor becomes constructor promotion. That saves work, but only if you do it in small steps. Turn all the rules loose at once and Rector quickly changes a few hundred files, and nobody reviews that seriously.

That is what the levels are for.

A level is a number of rules

A rule set is an ordered list: the harmless rules at the front, the ones that cut deeper at the back. The level says how many of them are active:

Level N enables the first N+1 rules.

A staircase of Rector levels: steps 0, 20, 40, 60 are checked off, step 80 is under the magnifying glass of the dry run, 100 is next, and the top step, 137, is replaced by withPhpSets(). Each step is higher because each level enables more rules

So withPhpLevel(0) is exactly one rule. The list holds every PHP version and is not filtered. Rules for versions above the one in composer.json ("php": "~8.4") run along but change nothing.

PHP
use Rector\Config\RectorConfig;
use Rector\Php53\Rector\Ternary\TernaryToElvisRector;

return RectorConfig::configure()
    ->withPaths([__DIR__])
    ->withSkip([
        // contradicts the strict PHPStan rules (see below)
        TernaryToElvisRector::class,
        __DIR__ . '/vendor',
        __DIR__ . '/var/cache',
    ])
    ->withPhpLevel(0);

How many rules a set has is not in the documentation but in the source. For the PHP set it is vendor/rector/rector/config/set/php-version-based.php, and the order there is the order of the levels. In Rector 2.7 there are 138 rules, so levels 0 to 137. The last ones belong to PHP 8.5 and 8.6 and do nothing on an 8.4 project.

Once you are at the top, you replace the level with the complete set:

PHP
    ->withPhpSets();

There is no constant like -1 for "everything". withPhpSets() is exactly that, and it grows with every Rector update.

The commands, and why --clear-cache

Bash
vendor/bin/rector process --clear-cache --dry-run
vendor/bin/rector process --clear-cache

--clear-cache always belongs there. Rector remembers files it had nothing to change in and skips them on the next run. Turn the level up and down all day, and without the parameter Rector happily reports "nothing found", even though the new rule would very much have something to do.

The routine for each step

  1. Raise the level, look at the dry run.
  2. Run rector process.
  3. Run the code formatter afterwards (PHP-CS-Fixer in my case), because it wants some things differently.
  4. PHPStan: are there new errors?
  5. Tests (Pest or PHPUnit).
  6. Read the diff.

Then run Rector once more: after the corrections from steps 3 and 4 it sometimes finds something again.

Most steps change nothing. So you can safely jump in steps of ten and only look closer once the dry run finds something.

Where to look closely

Almost everything Rector rewrites behaves exactly the same afterwards. A few rules do change the meaning, though, and neither PHPStan nor the tests reliably notice.

switch becomes match. switch compares loosely (==), match strictly (===). If the value comes from a URL or a form, it is a string:

PHP
// before: '2' == 2 is true
switch ($filter) { case 2: ... }

// after: '2' === 2 is false, default kicks in
match ($filter) { 2 => ..., default => '' };

For me, exactly that switched off a filter, without an error message. The fix is an (int) in front of the value. For every new match, check which type the value really has.

readonly and constructor promotion. Rector checks whether a property is still written after the constructor. What it does not see is access by reference or from outside. Searching once for &$this->…, sort($this->…) and the like is worth it.

When two tools contradict each other. Rector turns $a ? $a : $b into the short form $a ?: $b, and the strict rules of PHPStan (phpstan-strict-rules) forbid exactly that short form, and rightly so: ?: only checks "is the value falsy", and that includes '0', 0 and ''. Most of the time you mean "not set" (??) or "empty string" (!== ''). That is why TernaryToElvisRector is at the top of the skip list.

Docblocks with constructor promotion. Rector puts a property's description as an inline comment between the constructor parameters. IDEs pick that up poorly. It is better to move it into the docblock above the constructor as @param.

::class drops the leading backslash. Rector turns '\\Foo\\Bar' into \Foo\Bar::class, which gives Foo\Bar, without the backslash in front. If the string is compared in exactly that spelling, the comparison no longer matches. In my code it now says '\\' . Bar::class.

is_string(...) instead of 'is_string'. To PHP that is the same. Psalm, however, narrows array_filter($values, 'is_string') to a list of strings, but not with is_string(...), and afterwards everything is mixed again. FunctionFirstClassCallableRector is in my skip list.

Promotion can overwrite a property. A constructor kept a value raw and then normalised the local variable. Rector turned it into a promoted property and wrote the normalised form into it. The raw value was gone, and so was the comment that explained exactly that.

Into the pipeline

Once a step is clean, a CI job freezes it:

YAML
rector:
    script:
        - vendor/bin/rector process --clear-cache --dry-run --no-progress-bar

If Rector finds something, the dry run ends with a non-zero exit code and the job turns red.

There is one trap: if constants are missing in CI that come from a config file locally which is not checked in, Rector takes them for misspelled constants and wants to rename dbHost to DBHOST (SensitiveConstantNameRector). Locally everything passes, the pipeline complains. The fix: copy the example config first, as the PHPStan job usually does anyway.

Dead code and the constants trap

After the PHP set comes the dead-code set, again one level at a time from withDeadCodeLevel(0) upwards and complete in the end:

PHP
    ->withPhpSets()
    ->withPreparedSets(true) // first parameter = deadCode
    ->withPHPStanConfigs([__DIR__ . '/phpstan.neon']);

The last line is the most important one. Without it, Rector deletes code that only runs on the live system.

Rector asks PHPStan which code never runs. PHPStan works with the constants as they are set locally. If the local config says define('APP_LOCAL', true), then !APP_LOCAL is always false for PHPStan, and everything inside if (!APP_LOCAL) { … } counts as dead code. Rector deletes it.

The fix: list the constant under dynamicConstantNames in phpstan.neon. Then PHPStan does not work with its value. But Rector only reads that file if you hand it over with withPHPStanConfigs().

And here, too: read the diff. RemoveNextSameValueConditionRector merged two consecutive if (count($cache) === 0) for me, even though the first block fills the cache. After that the cache was ignored on every request. The rule has been in the skip list ever since.

Conclusion

Rector saves a lot of typing, but you should not let it run blind. With the levels each step stays small enough that you really read the diff. After the PHP set and dead code, the next sets work the same way: withTypeCoverageLevel() and withCodeQualityLevel().

And that is far from everything. A look at the parameters of withPreparedSets() shows how much more is coming: codingStyle, typeDeclarationDocblocks, privatization, naming, earlyReturn, instanceOf and more, plus sets for PHPUnit, Doctrine and Symfony. Only some of them have a level variant, though (the list is in vendor/rector/rector/src/Config/Level/). All the others you switch on completely or not at all, and that is where a dry run first pays off most.

Product, company and trademark names mentioned here belong to their respective owners and are used descriptively only. No affiliation with them, and no endorsement by them, is implied.