Instant Upgrades and Automated Refactoring of any PHP 5.3+ code
Go to file
2020-03-31 17:49:26 +02:00
.docker/php Warmup opcache in docker 2020-01-26 16:34:32 +01:00
.github use properties over referecnes 2020-03-29 16:57:15 +02:00
bin Fixed PHPStan issues 2020-02-08 20:00:10 +01:00
ci naming 2020-03-29 16:16:27 +02:00
compiler fix scoping of OxidEsales 2020-02-29 01:37:15 +01:00
config [DeadCode] Add RemoveDeadRecursiveClassMethodRector 2020-03-31 15:17:42 +02:00
docs [DeadCode] Add RemoveDeadRecursiveClassMethodRector 2020-03-31 15:17:42 +02:00
helpers rename generator to rules 2020-02-13 17:10:07 +01:00
packages [DeadCode] Add RemoveDeadRecursiveClassMethodRector 2020-03-31 15:17:42 +02:00
rules clear commander from AbstractRector 2020-03-31 17:49:26 +02:00
src clear commander from AbstractRector 2020-03-31 17:49:26 +02:00
stubs fix method annotation 2020-03-04 23:22:29 +01:00
tests add CurrentRectorProvider 2020-03-19 14:15:08 +01:00
utils [Privatization] Add PrivatizeLocalPropertyToPrivatePropertyRector 2020-03-29 19:07:26 +02:00
.dockerignore remove dead code 2020-02-27 19:56:38 +01:00
.editorconfig improve attributes, add .editorconfig 2018-12-13 17:23:24 +01:00
.gitattributes add Windows print test 2020-02-27 11:32:53 +01:00
.gitignore use filesytem utils package name 2020-02-13 23:02:57 +01:00
.phpstorm.meta.php improve PhpVersionFeature autocomplete by PHPStorm 2020-03-24 23:49:19 +01:00
.travis.yml build just once 2020-02-27 14:28:50 +01:00
BACKERS.md [SOLID] Add ChangeIfElseValueAssignToEarlyReturnRector 2020-01-06 01:42:15 +01:00
changelog-linker.yaml init CHANGELOG for 0.4.11 2019-04-13 15:16:49 +02:00
CHANGELOG.md apply privatization 2020-03-29 00:06:05 +01:00
CODE_OF_CONDUCT.md Use HTTPS instead of HTTP 2018-02-14 07:23:09 -02:00
composer.json fix Safe\function conflicts 2020-03-31 17:46:04 +02:00
CONTRIBUTING.md Move contributing guide to its own file 2020-03-21 14:22:10 +01:00
Dockerfile Warmup opcache in docker 2020-01-26 16:34:32 +01:00
ecs-after-rector.yaml use explicit null in yaml 2020-01-05 20:00:32 +01:00
ecs.yaml use properties over referecnes 2020-03-29 16:57:15 +02:00
LICENSE Update LICENSE year forever 2018-01-02 20:27:07 -02:00
phpstan.neon use properties over referecnes 2020-03-29 16:57:15 +02:00
phpunit.xml improve ParamTypeDeclarationRector complexity 2020-02-11 14:11:47 +01:00
README.md Avoid long lines in code 2020-03-21 14:23:09 +01:00
rector-ci.yaml apply privatization 2020-03-29 00:06:05 +01:00
rector.yaml [DeadCode] Add RemoveDeadRecursiveClassMethodRector 2020-03-31 15:17:42 +02:00
sonar-project.properties fix property path for sonar 2020-03-29 03:21:29 +02:00

Rector - Upgrade Your Legacy App to a Modern Codebase

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

Coverage Status Downloads SonarCube



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 donations are welcome through PayPal.

Thank you:


Open-Source First

Rector instantly upgrades and instantly refactors the PHP code of your application. It supports all modern versions of PHP and many open-source projects:




What Can Rector Do for You?

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

How to Apply Coding Standards?

The AST libraries that Rector uses aren't well-suited for coding standards, so it's better to let coding standard tools do that.

Don't have a coding standard tool for your project? Consider adding EasyCodingStandard, PHP CS Fixer or PHP_CodeSniffer.

Tip: If you have EasyCodingStandard, you can start your set with ecs-after-rector.yaml.

Try Rector Online

No time to try Rector locally?

We have an online demo just for you!

Install

composer require rector/rector --dev

Having conflicts during composer require or on run?

Using a different PHP version than Rector supports?

Running Rector

A. Get Started

Try the demo and get familiar with rector

B. Prepared Sets

Featured open-source projects have prepared sets. You can find them in /config/set or by running:

vendor/bin/rector sets

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

# show a list of known changes in Symfony 4.0
vendor/bin/rector process src --set symfony40 --dry-run
# apply upgrades to your code
vendor/bin/rector process src --set symfony40

Some sets, such as code-quality can be used on a regular basis. You can include them in your rector.yaml to run them by default:

# rector.yaml
parameters:
    sets:
        - 'code-quality'
        - 'php71'
        - 'php72'
        - 'php73'

C. Custom Sets

  1. Create a rector.yaml configuration file with your desired Rectors or provide another configuration file with --config:

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

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

Features

Extra Autoloading

Rector relies on whatever autoload setup the project it is fixing is using by using the Composer autoloader as default. To specify your own autoload file, use --autoload-file option:

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

Or use a rector.yaml configuration file:

# 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/*'

You can use a whole ruleset, except one rule:

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

Do you want to skip just specific line with specific rule?

Use @noRector \FQN name annotation:

class SomeClass
{
    /**
     * @noRector \Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector
     */
    public function foo()
    {
        /** @noRector \Rector\DeadCode\Rector\Plus\RemoveDeadZeroAndOneOperationRector */
        round(1 + 0);
    }
}

Filter Rectors

If you have a configuration file for Rector including many sets and Rectors, you might want at times to run only a single Rector from them. The --only argument allows that, for example :

vendor/bin/rector process --set solid --only "Rector\SOLID\Rector\Class_\FinalizeClassesWithoutChildrenRector" src/

Will only run Rector\SOLID\Rector\Class_\FinalizeClassesWithoutChildrenRector.

Please note that the backslash in the Rector's fully-qualified class name needs to be properly escaped (by surrounding the string in double quotes).

Provide PHP Version

By default Rector uses the language features matching your system version of PHP. You can configure it for a different PHP version:

# rector.yaml
parameters:
    php_version_features: '7.2' # your version is 7.3

Paths

If you're annoyed by repeating paths in arguments, you can move them to config instead:

# rector.yaml
parameters:
    paths:
        - 'src'
        - 'tests'

Import Use Statements

FQN classes are not imported by default. If you don't to do do it manually after every Rector run, enable it by:

# rector.yaml
parameters:
    auto_import_names: true

You can also fine-tune how these imports are processed:

# rector.yaml
parameters:
    # this will not import root namespace classes, like \DateTime or \Exception
    import_short_classes: false

    # this will not import classes used in PHP DocBlocks, like in /** @var \Some\Class */
    import_doc_blocks: false

Limit Execution to Changed Files

Execution can be limited to changed files using the process option --match-git-diff. This option will filter the files included by the configuration, creating an intersection with the files listed in git diff.

vendor/bin/rector process src --match-git-diff

This option is useful in CI with pull-requests that only change few files.

Symfony Container

To work with some Symfony rules, you now need to link your container XML file

# rector.yaml
parameters:
    # path to load services from
    symfony_container_xml_path: 'var/cache/dev/AppKernelDevDebugContainer.xml'

3 Steps to Create Your Own Rector

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

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

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

1. Create a New Rector and Implement Methods

Create a class that extends Rector\Core\Rector\AbstractRector. It will inherit useful methods e.g. to check node type and name. See the source (or type $this-> in an IDE) for a list of available methods.

<?php

declare(strict_types=1);

namespace Utils\Rector;

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

final class MyFirstRector extends AbstractRector
{
    /**
     * @return string[]
     */
    public function getNodeTypes(): array
    {
        // what node types are we looking for?
        // pick any node from https://github.com/rectorphp/rector/blob/master/docs/NodesOverview.md
        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
        if (! $this->isName($node->name, 'set*')) {
            // return null to skip it
            return null;
        }

        $methodCallName = $this->getName($node);
        $newMethodCallName = Strings::replace($methodCallName, '#^set#', 'change');

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

        // return $node if you modified it
        return $node;
    }

    /**
     * From this method documentation is generated.
     */
    public function getDefinition(): RectorDefinition
    {
        return new RectorDefinition(
            'Change method calls from set* to change*.', [
                new CodeSample(
                    // code before
                    '$user->setPassword("123456");',
                    // code after
                    '$user->changePassword("123456");'
                ),
            ]
        );
    }
}

This is how the file structure should look like:

/src/YourCode.php
/utils/Rector/MyFirstRector.php
rector.yaml
composer.json

We also need to load Rector rules in composer.json:

{
    "autoload": {
        "psr-4": {
            "App\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Utils\\": "utils"
        }
    }
}

After adding this to composer.json, be sure to reload Composer's class map:

composer dump-autoload

2. Register It

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

3. Let Rector Refactor Your Code

The rector.yaml configuration is loaded by default, so we can skip it.

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

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

That's it!

Generating a Rector Rule

Do you want to save time with making rules and tests?

Use the create command.

More Detailed Documentation

How to Contribute

See the contribution guide.

Run Rector in Docker

You can run Rector on your project using Docker:

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

# Note that a volume is mounted from `pwd` (the current directory) 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? Add it here: