Unlock the Power of Rector: A PHP Code Transformation Tool
The Rector Pillars
Rector stands on the shoulders of two giants: PHP Parser and PHPStan. PHP Parser enables static code analysis and manipulation, while PHPStan provides a deep understanding of the code, allowing Rector to map, browse, and validate relationships among entities in the code.
What Are Rector Rules?
A Rector rule is a PHP class that inherits from AbstractRector
, executing transformations on nodes from the Abstract Syntax Tree (AST) corresponding to the parsed PHP file. A rule consists of three main methods:
getRuleDefinition
getNodeTypes
refactor
Creating a Custom Rule
Let’s take a closer look at the implementation of the DowngradeNullCoalescingOperatorRector
rule, which replaces the ??=
operator introduced in PHP 7.4 with its equivalent from PHP 7.3.
// Example implementation of DowngradeNullCoalescingOperatorRector
class DowngradeNullCoalescingOperatorRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Downgrade null coalescing operator',
new \Rector\Core\Provider\CurrentPhpVersionProvider()
);
}
public function getNodeTypes(): array
{
return [Assignment::class];
}
public function refactor(Node $node):?Node
{
// Implementation details omitted
}
}
This rule demonstrates the basic concept of creating a rule: finding the new node that satisfies the target code, identifying the required data, and porting data from the old node to the new node.
Reusing Code from Existing Rules
With almost 700 existing rules in the Rector repository, you can tap into a wealth of knowledge and code to help implement your custom rules. Before creating a new rule, check if similar logic has already been coded in an existing rule. Chances are, you’ll find what you need.
Tips for Testing
When testing rules connected to PHPUnit, use the --filter
option to execute only a specific test. For instance, phpunit --filter=test#X
, where X is the order number of the fixture test. You can also use the dump
function from Symfony’s VarDumper component to visualize the node content and identify potential issues.
Getting Started with Rector
Rector is a powerful tool for transforming PHP code, allowing you to transpile your application to support older PHP versions while still using modern features. With its extensive library of existing rules and customizable nature, Rector is an invaluable asset in your PHP development toolkit.
Get started with Rector by exploring its repository and discovering the endless possibilities it offers for transforming your PHP code.