Rector PHP is an extremely powerful and amazing tool to help developers improve the code quality of your PHP projects. It could be used to safely upgrade your legacy codebase from PHP 5.6 to PHP 8 ! Rector could also be integrated to your CI and let it fix your code for you, so if you have code-reviews for each member of your team, but don’t have time for it, this is the tool you need to get !
Rector PHP supports all versions of PHP from 5.3 and major open-source projects such as Symfony, Drupal, CakePHP, Typo3 …etc. The tool provides more than 660 rules to help you scan and fix issues depending on what you want to achieve with your code. The only issue here with Rector that you need to know the rules you need to run, or you can choose one of the recipe available.
How Rector PHP works
- The application finds files in the source code you provide and registered Rectors – from
--config
or localrector.php
- Then it iterates all found files and applies relevant Rectors to them.
- A Rector in this context is 1 single class that modifies 1 thing, e.g. changes the class name
- When work on all nodes of 1 file is done, the file will be saved if it has some changes
- Or if the
--dry-run
option is on, it will store the git-like diff thanks to GeckoPackages/GeckoDiffOutputBuilder - Then Rector will go to the next file
- After this, Rector displays the list of changed files
- Or with
--dry-run
option the diff of these files
Converting legacy code to PHP8
To explore capabilities of Rector we tried a Symfony Bundle that is actually working with Symfony 4, however it’s extensively using curly braces features which is no longer supported since PHP 7.4. So this bundle will make your Symfony code fail if you are using PHP >= 7.4. Honestly, we picked a missed feature in Rector to see how easy it is to create new rules.
So I cloned a fork of the bundle and installed Rector prefixed, which is useful for legacy code since the latest version will have certainly conflicts.
$ git clone https://github.com/hatemben/BGBarcodeBundle.git
$ composer require rector/rector-prefixed --dev
$ # generate "rector.php" config
$ vendor/bin/rector init
$ # dry run
$ vendor/bin/rector process Util --dry-run
$ # changing run
$ vendor/bin/rector process Util
So the result could be seen in the diff below, the code quality have been improved, but the deprecation remain there.
So here if you want to fix this issue, you need to create a new rule. For this you can use the command generate in interactive mode and provide an answer to questions asked by the command :
$ vendor/bin/rector generate --interactive
Or by initializing rector-recipe.php
config file and completing the same parameters to design your new rule, then you can run
$ vendor/bin/rector generate
Creating your own rules is not an easy task, and you can read more in Leonardo Tutorial how to create your first Rector rule.
Rector PHP is an open source tool released under an MIT license. More information at getrector.org