Instant Upgrades and Automated Refactoring of any PHP 5.3+ code
Go to file
2019-05-01 13:51:56 +02:00
bin make OutputFormatters specific for DumpRectorsCommand 2019-02-23 00:49:32 +01:00
config [PHP] Add AddDefaultValueForUndefinedVariableRector 2019-04-29 16:05:39 +02:00
docs [CodeQuality] prevent double negative in SimplifyBoolIdenticalTrueRector 2019-04-03 20:29:46 +02:00
packages add ImportsInClassCollection 2019-05-01 13:51:56 +02:00
src fix cs 2019-05-01 00:49:59 +02:00
tests restore test case 2019-04-29 12:58:29 +02:00
utils/PHPStanExtensions rename Attribute to AttributeKey to prevent duplicated names with similar classes in 3rd party project 2019-04-13 14:21:36 +02:00
.coveralls.yml travis: add coverage 2018-10-28 18:47:21 +01:00
.dockerignore Fixed missing autoload in docker build and optimized caching 2019-03-12 13:19:30 +01:00
.editorconfig improve attributes, add .editorconfig 2018-12-13 17:23:24 +01:00
.gitattributes Add "dump-node-help" command 2019-02-23 00:49:32 +01:00
.gitignore version rector.yaml for dog food 2019-03-31 23:21:00 +02:00
.phpstorm.meta.php rename Attribute to AttributeKey to prevent duplicated names with similar classes in 3rd party project 2019-04-13 14:21:36 +02:00
.travis.yml travis: allow dog food run to fail 2019-04-29 13:14:25 +02:00
changelog-linker.yaml init CHANGELOG for 0.4.11 2019-04-13 15:16:49 +02:00
CHANGELOG.md update CHANGELOG date 2019-04-14 01:36:12 +02:00
CODE_OF_CONDUCT.md Use HTTPS instead of HTTP 2018-02-14 07:23:09 -02:00
composer.json composer: bump deps 2019-04-29 06:30:04 +02:00
create-rector.yaml.dist add celebrity level config 2019-02-23 09:38:31 +01:00
Dockerfile Fixed missing autoload in docker build and optimized caching 2019-03-12 13:19:30 +01:00
ecs-after-rector.yaml [PhpSpecToPHPUnit] Init new package 2019-03-15 13:42:28 +01:00
ecs.yaml composer: bump deps 2019-04-29 06:30:04 +02:00
LICENSE Update LICENSE year forever 2018-01-02 20:27:07 -02:00
phpstan.neon phpstan: remove unmatched errors 2019-04-29 07:20:23 +02:00
phpunit.xml [tests] Refactor tests to use container just once, if not enforced config 2019-04-29 00:36:52 +02:00
README.md README: add sponsor links, cleanup 2019-04-29 23:42:11 +02:00
rector.yaml composer: bump deps 2019-04-29 06:30:04 +02:00

Rector - Upgrade your Legacy App to Modern Codebase

Rector is a reconstructor tool - it does instant upgrades and instant refactoring of your code. Why doing it manually if 80% Rector can handle for you?

Build Status Coverage Status Downloads

Rector-showcase


Sponsors

Rector grows faster with your help, the more you help the more work it saves you. Check out Rector's Patreon. One-time donation is welcomed trough PayPal.


Open-Source First

Rector instantly upgrades and instantly refactors PHP code of your application. It covers many open-source projects and PHP changes itself:



What can Rector do for You?

...look at overview of all available Rectors with before/after diffs and configuration examples. You can use them to build your own sets.

Install

composer require rector/rector --dev

Do you have conflicts on composer require or on run?

Extra Autoloading

Rector relies on project and autoloading of its classes. To specify own autoload file, use --autoload-file option:

vendor/bin/rector process ../project --autoload-file ../project/vendor/autoload.php

Or make use of rector.yaml config:

# rector.yaml
parameters:
    autoload_paths:
        - 'vendor/squizlabs/php_codesniffer/autoload.php'
        - 'vendor/project-without-composer'

Exclude Paths and Rectors

You can also exclude files or directories (with regex or fnmatch):

# rector.yaml
parameters:
    exclude_paths:
        - '*/src/*/Tests/*'

Do you want to use whole set, except that one rule? Exclude it:

# rector.yaml
parameters:
    exclude_rectors:
        - 'Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector'

By default Rector uses language features of your PHP version. If you you want to use different PHP version than your system, put it in config:

parameters:
    php_version_features: '7.2' # your version 7.3

Running Rector

A. Prepared Sets

Featured open-source projects have prepared sets. You'll find them in /config/level or by calling:

vendor/bin/rector levels

Let's say you pick symfony40 level and you want to upgrade your /src directory:

# show known changes in Symfony 4.0
vendor/bin/rector process src --level symfony40 --dry-run
# apply
vendor/bin/rector process src --level symfony40

B. Custom Sets

  1. Create rector.yaml with desired Rectors:

    services:
        Rector\Rector\Architecture\DependencyInjection\AnnotatedPropertyInjectToConstructorInjectionRector:
            $annotation: "inject"
    
  2. Run on your /src directory:

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

How to Apply Coding Standards?

AST that Rector uses doesn't deal with coding standards very well, so it's better to let coding standard tools do that. Your project doesn't have one? Rector ships with EasyCodingStandard set that covers namespaces import, 1 empty line between class elements etc.

Just use --with-style option to handle these basic cases:

vendor/bin/rector process src --with-style

4 Steps to Create Own Rector

First, make sure it's not covered by any existing Rectors yet.

Let's say we want to change method calls from set* to change*.

 $user = new User();
-$user->setPassword('123456');
+$user->changePassword('123456');

1. Create New Rector

Create class that extends Rector\Rector\AbstractRector. It has useful methods like checking node type and name. Just run $this-> and let PHPStorm show you all possible methods.

<?php declare(strict_types=1);

namespace App\Rector;

use PhpParser\Node;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\RectorDefinition;

final class MyFirstRector extends AbstractRector
{
    public function getDefinition(): RectorDefinition
    {
        // what does this do?
        // minimalistic before/after sample - to explain in code
    }

    /**
     * @return string[]
     */
    public function getNodeTypes(): array
    {
        // what node types we look for?
        // String_? FuncCall? ...
        // pick any node from https://github.com/nikic/PHP-Parser/tree/master/lib/PhpParser/Node
        return [];
    }

    public function refactor(Node $node): ?Node
    {
        // what will happen with the node?
        // common work flow:
        // - should skip? → return null;
        // - modify it? → do it, then return $node;
        // - remove/add nodes elsewhere? → do it, then return null;
    }
}

2. Implement Methods

<?php declare(strict_types=1);

namespace App\Rector;

use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Expr\MethodCall;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;

final class MyFirstRector extends AbstractRector
{
    public function getDefinition(): RectorDefinition
    {
        return new RectorDefinition('Change method calls from set* to change*.', [
            new CodeSample('$user->setPassword('123456');', '$user->changePassword('123456');')
        ]);
    }

    /**
     * @return string[]
     */
    public function getNodeTypes(): array
    {
        return [MethodCall::class];
    }

    /**
     * @param MethodCall $node - we can add "MethodCall" type here, because only this node is in "getNodeTypes()"
     */
    public function refactor(Node $node): ?Node
    {
        // we only care about "set*" method names
        $methodCallName = $this->getName($node);

        if (! Strings::startsWith($methodCallName, 'set')) {
            return null;
        }

        $newMethodCallName = Strings::replace($methodCallName, '#^set#', 'change');

        $node->name = new Identifier($newMethodCallName);

        return $node;
    }
}

3. Register it

# rector.yaml
services:
    App\Rector\MyFirstRector: ~

4. Let Rector Refactor Your Code

# see the diff first
vendor/bin/rector process src --dry-run

# if it's ok, apply
vendor/bin/rector process src

That's it!

More Detailed Documentation

How to Contribute

Just follow 3 rules:

  • 1 feature per pull-request

  • New feature needs tests

  • Tests, coding standards and PHPStan checks must pass:

    composer complete-check
    

    Don you need to fix coding standards? Run:

    composer fix-cs
    

We would be happy to merge your feature then.

Run Rector in Docker

With this command, you can process your project with rector from docker:

docker run -v $(pwd):/project rector/rector:latest process /project/src --level symfony40 --dry-run

# Note that a volume is mounted from `pwd` into `/project` which can be accessed later.

Using rector.yaml:

docker run -v $(pwd):/project rector/rector:latest process /project/app --config /project/rector.yaml --autoload-file /project/vendor/autoload.php --dry-run

Community Packages

Do you use Rector to upgrade your code? Share it here: