Home Backend Development PHP Tutorial Mastering Code Refactoring: A Complete Guide to Using Rector PHP

Mastering Code Refactoring: A Complete Guide to Using Rector PHP

Aug 26, 2024 am 06:31 AM

Mastering Code Refactoring: A Complete Guide to Using Rector PHP
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
Copy after login

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
Copy after login

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);
Copy after login

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,
    ]);
Copy after login

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'];
Copy after login

Now we can test this config by performing a dry run of Rector.

rector --dry-run
Copy after login

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.

Mastering Code Refactoring: A Complete Guide to Using Rector PHP

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
Copy after login

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.

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.

The above is the detailed content of Mastering Code Refactoring: A Complete Guide to Using Rector PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles