Convert Figma logo to code with AI

rectorphp logorector

Instant Upgrades and Automated Refactoring of any PHP 5.3+ code

8,596
681
8,596
13

Top Related Projects

12,802

PHP Static Analysis Tool - discover bugs in your code without running it!

5,537

A static analysis tool for finding errors in PHP applications

5,528

Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.

A tool to automatically fix PHP Coding Standards issues

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

A PHP parser written in PHP

Quick Overview

Rector is a powerful PHP refactoring tool that automates code upgrades and refactoring. It can instantly upgrade and refactor your PHP code, supporting migrations between different PHP versions and popular frameworks. Rector is designed to save developers time and reduce errors in large-scale code transformations.

Pros

  • Automates complex code refactoring tasks, saving significant development time
  • Supports a wide range of PHP versions and popular frameworks
  • Highly customizable with the ability to create custom rules
  • Continuously updated to support the latest PHP features and best practices

Cons

  • Steep learning curve for creating custom rules
  • May require manual review and adjustments for complex refactoring scenarios
  • Can be resource-intensive for large codebases
  • Some edge cases might not be handled correctly, requiring manual intervention

Code Examples

  1. Basic usage to upgrade PHP code:
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->sets([
        LevelSetList::UP_TO_PHP_81
    ]);
};

This configuration upgrades PHP code to be compatible with PHP 8.1.

  1. Applying specific rules:
use Rector\Config\RectorConfig;
use Rector\Php74\Rector\Property\TypedPropertyRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->rule(TypedPropertyRector::class);
};

This example applies the TypedPropertyRector rule to add property types to class properties.

  1. Custom rule creation:
use PhpParser\Node;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

final class MyCustomRector extends AbstractRector
{
    public function getRuleDefinition(): RuleDefinition
    {
        return new RuleDefinition('Description of my custom rule', [
            new CodeSample(
                'old code',
                'new code'
            ),
        ]);
    }

    public function getNodeTypes(): array
    {
        return [Node\Stmt\Class_::class];
    }

    public function refactor(Node $node): ?Node
    {
        // Implement your custom refactoring logic here
    }
}

This example shows the structure of a custom Rector rule.

Getting Started

  1. Install Rector via Composer:

    composer require rector/rector --dev
    
  2. Create a rector.php configuration file in your project root:

    use Rector\Config\RectorConfig;
    use Rector\Set\ValueObject\LevelSetList;
    
    return static function (RectorConfig $rectorConfig): void {
        $rectorConfig->paths([
            __DIR__ . '/src'
        ]);
        $rectorConfig->sets([
            LevelSetList::UP_TO_PHP_81
        ]);
    };
    
  3. Run Rector:

    vendor/bin/rector process
    

This will apply the configured rules to your code in the src directory.

Competitor Comparisons

12,802

PHP Static Analysis Tool - discover bugs in your code without running it!

Pros of PHPStan

  • More focused on static analysis and type checking
  • Larger community and more extensive documentation
  • Easier to integrate into existing projects without modifying code

Cons of PHPStan

  • Limited ability to automatically fix detected issues
  • May require more manual intervention to resolve identified problems
  • Less flexibility in customizing analysis rules compared to Rector

Code Comparison

PHPStan example:

<?php
function foo(int $a, int $b): int {
    return $a + $b;
}
foo('1', 2);

PHPStan would detect the type mismatch in the function call.

Rector example:

<?php
$user->getName();

Rector could automatically refactor this to:

<?php
$user?->getName();

Both tools aim to improve PHP code quality, but they approach it differently. PHPStan focuses on identifying potential issues through static analysis, while Rector emphasizes automated code refactoring and modernization. PHPStan is generally easier to adopt in existing projects, as it doesn't modify code directly. Rector, on the other hand, offers more powerful refactoring capabilities but may require more careful integration to avoid unintended changes. The choice between the two depends on specific project needs and development workflows.

5,537

A static analysis tool for finding errors in PHP applications

Pros of Psalm

  • Focuses on static analysis and type checking, providing deeper insights into potential type-related issues
  • Offers a wider range of checks and analysis capabilities, including taint analysis and security checks
  • Integrates well with popular IDEs and CI/CD pipelines

Cons of Psalm

  • Steeper learning curve due to its extensive configuration options and advanced features
  • May produce more false positives, requiring careful tuning of configuration

Code Comparison

Psalm:

<?php
/** @psalm-suppress PossiblyUndefinedMethod */
$result = $object->someMethod();

Rector:

<?php
$result = $object->someMethod();

Key Differences

  • Psalm focuses on static analysis and type checking, while Rector specializes in automated code refactoring and upgrades
  • Psalm provides more in-depth analysis of code quality and potential issues, whereas Rector actively modifies code to improve it
  • Psalm requires more configuration and annotation to suppress warnings, while Rector's transformations are more straightforward

Use Cases

  • Use Psalm for ongoing code quality checks, type safety, and identifying potential bugs
  • Use Rector for automated code upgrades, enforcing coding standards, and large-scale refactoring tasks

Both tools can be valuable in a PHP development workflow, often complementing each other to improve code quality and maintainability.

5,528

Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.

Pros of Phan

  • More focused on static analysis and type checking
  • Supports a wider range of PHP versions (5.6 to 8.2)
  • Better suited for large-scale projects with complex codebases

Cons of Phan

  • Steeper learning curve and more complex configuration
  • May produce more false positives, requiring manual verification
  • Less emphasis on automatic code refactoring

Code Comparison

Phan (static analysis):

<?php
function example($param) {
    return $param->undefinedMethod();
}

Rector (code transformation):

<?php
$config->ruleWithConfiguration(RemoveUnusedPrivatePropertyRector::class, [
    'excludes' => ['SomeClass']
]);

Key Differences

  • Phan focuses on detecting potential errors and type inconsistencies, while Rector specializes in automated code refactoring and upgrades.
  • Phan provides more in-depth static analysis, whereas Rector offers broader code transformation capabilities.
  • Phan is better for ongoing code quality maintenance, while Rector excels at large-scale codebase modernization and framework upgrades.

Both tools serve different purposes in the PHP ecosystem, with Phan being more suitable for continuous code quality checks and Rector for automated code modifications and upgrades.

A tool to automatically fix PHP Coding Standards issues

Pros of PHP-CS-Fixer

  • More focused on code style and formatting
  • Extensive set of predefined rules for consistent coding standards
  • Faster execution for style-related fixes

Cons of PHP-CS-Fixer

  • Limited ability to perform complex code transformations
  • Less flexibility in creating custom rules
  • Primarily focused on PSR standards and may not cover all project-specific needs

Code Comparison

PHP-CS-Fixer:

$fixer = new PhpCsFixer\Fixer\ClassNotation\VisibilityRequiredFixer();
$fixer->fix($file);

Rector:

$rector = new Rector\Rector\ClassMethod\AddReturnTypeDeclarationRector();
$rector->refactor($node);

Summary

PHP-CS-Fixer excels in maintaining consistent code style and formatting, offering a wide range of predefined rules. It's faster for style-related fixes but has limitations in complex code transformations. Rector, on the other hand, provides more powerful refactoring capabilities and greater flexibility in creating custom rules, making it better suited for larger-scale code modifications and upgrades. The choice between the two depends on whether the primary focus is on code style (PHP-CS-Fixer) or more comprehensive code refactoring (Rector).

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

Pros of PHP_CodeSniffer

  • Widely adopted and well-established in the PHP community
  • Extensive set of pre-defined coding standards (PSR-1, PSR-2, PSR-12, etc.)
  • Ability to create custom coding standards and sniffs

Cons of PHP_CodeSniffer

  • Limited to detecting and reporting coding standard violations
  • Cannot automatically fix complex code issues or perform refactoring
  • Requires manual intervention to fix reported issues

Code Comparison

PHP_CodeSniffer (detecting a coding standard violation):

<?php
if($condition){
    echo "Indentation error";
}

Rector (automatically fixing a code issue):

<?php
// Before
$result = join(',', $items);

// After
$result = implode(',', $items);

PHP_CodeSniffer focuses on detecting coding standard violations and reporting them, while Rector is designed to automatically refactor and upgrade PHP code. PHP_CodeSniffer excels at maintaining consistent coding styles across projects, but Rector offers more advanced code transformation capabilities, including upgrading PHP versions and applying complex refactoring patterns.

A PHP parser written in PHP

Pros of PHP-Parser

  • More focused and lightweight, specifically designed for parsing PHP code
  • Provides a lower-level API, offering greater flexibility for custom analysis and transformations
  • Has a longer history and is more widely used in various PHP tools and projects

Cons of PHP-Parser

  • Requires more manual work to implement complex code transformations
  • Lacks built-in refactoring and code modification capabilities
  • Steeper learning curve for developers who need to perform high-level code analysis or transformations

Code Comparison

PHP-Parser example:

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse($code);
$nodeFinder = new NodeFinder;
$variables = $nodeFinder->findInstanceOf($ast, Variable::class);

Rector example:

$rector = new RectorContainer();
$rector->addPhpFile($filePath);
$rector->registerRules([
    RemoveUnusedVariableRector::class,
    TypedPropertyRector::class,
]);
$rector->refactor();

PHP-Parser provides a lower-level API for parsing and analyzing PHP code, while Rector offers a higher-level interface for automated refactoring and code transformations. PHP-Parser is more flexible but requires more manual work, whereas Rector provides ready-to-use tools for common refactoring tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Rector - Instant Upgrades and Automated Refactoring

Downloads


Rector instantly upgrades and refactors the PHP code of your application. It can help you in 2 major areas:

1. Instant Upgrades

Rector now supports upgrades from PHP 5.3 to 8.2 and major open-source projects like Symfony, PHPUnit, and Doctrine. Do you want to be constantly on the latest PHP and Framework without effort?

Use Rector to handle instant upgrades for you.

2. Automated Refactoring

Do you have code quality you need, but struggle to keep it with new developers in your team? Do you want to see smart code-reviews even when every senior developers sleeps?

Add Rector to your CI and let it continuously refactor your code and keep the code quality high.

Read our blogpost to see how to set up automated refactoring.

Install

composer require rector/rector --dev

Running Rector

There are 2 main ways to use Rector:

  • a single rule, to have the change under control
  • or group of rules called sets

To use them, create a rector.php in your root directory:

vendor/bin/rector

And modify it:

use Rector\Config\RectorConfig;
use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromStrictConstructorRector;

return RectorConfig::configure()
    // register single rule
    ->withRules([
        TypedPropertyFromStrictConstructorRector::class
    ])
    // here we can define, what prepared sets of rules will be applied
    ->withPreparedSets(
        deadCode: true,
        codeQuality: true
    );

Then dry run Rector:

vendor/bin/rector process src --dry-run

Rector will show you diff of files that it would change. To make the changes, drop --dry-run:

vendor/bin/rector process src

Documentation


Learn Faster with a Book

Are you curious, how Rector works internally, how to create your own rules and test them and why Rector was born? Read Rector - The Power of Automated Refactoring that will take you step by step through the Rector setup and how to create your own rules.


Empowered by Community :heart:

The Rector community is powerful thanks to active maintainers who take care of Rector sets for particular projects.

Among there projects belong:


Hire us to get Job Done :muscle:

Rector is a tool that we develop and share for free, so anyone can automate their refactoring. But not everyone has dozens of hours to understand complexity of abstract-syntax-tree in their own time. That's why we provide commercial support - to save your time.

Would you like to apply Rector on your code base but don't have time for the struggle with your project? Hire us to get there faster.


How to Contribute

See the contribution guide or go to development repository rector/rector-src.


Debugging

You can use --debug option, that will print nested exceptions output:

vendor/bin/rector process src/Controller --dry-run --debug

Or with Xdebug:

  1. Make sure Xdebug is installed and configured
  2. Add --xdebug option when running Rector
vendor/bin/rector process src/Controller --dry-run --xdebug

To assist with simple debugging Rector provides 2 helpers to pretty-print AST-nodes:

use PhpParser\Node\Scalar\String_;
$node = new String_('hello world!');

// prints node to string, as PHP code displays it
print_node($node);

Known Drawbacks

  • Rector uses nikic/php-parser, built on technology called an abstract syntax tree (AST). An AST doesn't know about spaces and when written to a file it produces poorly formatted code in both PHP and docblock annotations.

  • Rector in parallel mode will work most of the times for most OS. On Windows, you may encounter issues unresolvable despite of following the Troubleshooting Parallel guide. In such case, check if you are using Powershell 7 (pwsh). Change your terminal to command prompt (cmd) or bash for Windows.

How to Apply Coding Standards?

Your project needs to have a coding standard tool and a set of formatting rules, so it can make Rector's output code nice and shiny again.

We're using ECS with this setup.

May cause unexpected output on File with mixed PHP+HTML content

When you apply changes to File(s) thas has mixed PHP+HTML content, you may need to manually verify the changed file after apply the changes.