Photo by Matteo del Piano on Unsplash
Introduction to Rector PHP
In the ever-evolving world of PHP development, keeping your codebase clean, up-to-date, and efficient is crucial. This is where Rector PHP comes into play. If you’ve been wondering how to use Rector PHP, how to install it, or what exactly Rector PHP is, this comprehensive guide is for you. We’ll walk you through the basics, provide a detailed Rector PHP tutorial, and offer insights on PHP Rector and how to use it effectively. By the end of this article, you’ll have a solid grasp of Rector PHP and how it can enhance your development workflow.
What is Rector PHP?
Rector was started in 2020, but only got it’s 1.0 release in 2024. It’s a command line tool that performs a static analysis of a code base. From that analysis changes can be applied. I guess a good example of this would be what if your code base was riddled with array() calls when this is now considered an old practise, now replaced by the [] short array syntax.
Going through a code base to replace this is tedious. We could use a simple find and replace tool but what if there were an array() encapsulated a string or inside a comment that shouldn’t be changed? Now we’re having to check every instance we’re replaced.
This kind of problem is what Rector excels at. Instead Rector is able to look at the code and know definitively if it’s an array to be replaced.
You might be asking, PHP CS Fixer can also do this, which is true. But Rector also has PHPStan working under the hood to not only recognise syntax but to also analyse types. This means Rector can detect when a Class has a particular parent class, when a variable is a particular type or what the expected return type of a function. Giving it a far bigger scope for making changes on mass to a codebase.
How to Install Rector PHP
This might seem obvious to experienced PHP developers but there’s two primary ways and it really depends how you want to use Rector.
If you want to use Rector as part of continuous integration it makes sense to install Rector different into your projects through composer.
composer require --dev rector/rector
But if you were wanting to experiment with Rector on a single or multiple projects to perform upgrades, you might be better off by installing Rector globally by using
composer global require rector/rector
Which ever step you chose, the next step will be to create a config in the root directory for a project and include all the folders containing PHP code that you wish to upgrade. That doesn’t include the vendor folder of course as we don’t want to modify that.
This is what a config for say a Laravel project might look like:
use Rector\Config\RectorConfig;
use Rector\Php71\Rector\List_\ListToArrayDestructRector;
return RectorConfig::configure()
->withPaths([__DIR__. '/config', __DIR__. '/src', __DIR__. '/tests', __DIR__. '/routes'])
->withImportNames(removeUnusedImports: true);
PHP Rector: How to Use It Effectively
Like in the last section, using Rector can be determined by how you want to use it. Rector applies changes through the selections of Rules. This is the same as PHP CS Fixer. These rules will both detect the issue and then try to fix the problem they’re designed to solve.
If we wish to use Rector in a continuous integration manner, because we want to make use all of code is as optimised as best as possible as we develop it, we might use only a particular set of rules.
Rector has sets of rules, often described as Dead Code or Code Quality, which removes code or enhances and optimises respectively. It’s quite advantagous to stick to just these sets as we can be confident they work most of the time. But you should absolutely be aware that the way Rector writes code is never perfect. Often when rules are written they may cover the typical scenarios and may miss some circumstances found it your code base. This could lead to broken code.
In the event you want to use Rector, you should absolutely have tests written for your application. Without them Rector can easily lead to introducing bugs that you won’t discover until it’s a problem.
Another thing to consider when using Rector is that you should use a linting tool like PHP CS Fixer. Rector doesn’t look at whitespace, the spaces and newlines between method calls and it’s arguments etc. Using a linting tool should keep the code formatting to the standard you expect after Rector has applied it’s fixes.
Step-by-Step Rector PHP Tutorial
Now we’re installed Rector and we’re ready to try it out, let’s try applying one rule. Let’s start by updating our config file we made earlier.
use Rector\Config\RectorConfig;
use Rector\Php71\Rector\List_\ListToArrayDestructRector;
return RectorConfig::configure()
->withPaths([__DIR__. '/config', __DIR__. '/src', __DIR__. '/tests', __DIR__. '/routes'])
->withImportNames(removeUnusedImports: true)
->withRules([
ListToArrayDestructRector::class,
]);
In the case of this config we’re going to make a replacement of the use of listso that instead we use array restructuring. The changes we would expect to make are like the following:
-list($a, $b) = ['a', 'b'];
+[$a, $b] = ['a', 'b'];
Now we can test this config by performing a dry run of Rector.
rector --dry-run
If everything has been successful we should now see an output that contains a diff of all the changes to each file, with a list of the rules that made the changes. Our config only lists one rule so only one rule is applied but if more rules are added we’ll see a list of one or more here.
This is then a great time to review the changes and make sure the rule is performing as expected. Once we’re happy we can run Rector again. Without the dry run flag, changes will be written to the files.
rector
After it’s completed we should run our favourite linting tool and then run our tests. That’s it. We’ve now used Rector.
Conclusion: Boosting Your PHP Development with Rector
Rector PHP is a powerful tool that can significantly enhance your PHP development workflow by automating code refactoring and ensuring your codebase remains clean and modern. By understanding what Rector PHP is, learning how to install it, and mastering how to use it effectively, you can leverage its capabilities to streamline code updates, improve code quality, and reduce the risk of code feeling like a “legacy” project. Whether you’re integrating Rector into your continuous integration pipeline or using it for large-scale codebase upgrades, Rector is an indispensable asset for any PHP developer looking to maintain a high standard of code excellence.
You can continue your Rector journey by learning about configurable Rector Rules in this follow up article, Fix your Type Hints with Configurable Rules and PHP Rector.
If you want to take you knowledge of Rector further I suggest going to https://getrector.com/.
I’m Peter Fox, a software developer in the UK who works with Laravel. Thank you for reading my article, I’ve got many more to read at https://articles.peterfox.me. I’m also now Sponsorable on GitHub. If you’d like to encourage me to write more articles like this please do consider dropping a small one-off donation.
Top comments (0)