Giter VIP home page Giter VIP logo

rector's Introduction

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 โค๏ธ

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 ๐Ÿ’ช

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.

rector's People

Contributors

aerendir avatar bendavies avatar carusogabriel avatar derrickschoen avatar dobryy avatar github-actions[bot] avatar gnutix avatar greg0ire avatar janmikes avatar jeroensmit avatar keulinho avatar kodiakhq[bot] avatar lctrs avatar leoloso avatar lulco avatar markstory avatar mssimi avatar ondrejmirtes avatar ruudk avatar sabbelasichon avatar samsonasik avatar sashabeton avatar scheb avatar shyim avatar simivar avatar snapshotpl avatar staabm avatar stedekay avatar tomasvotruba avatar uftimmy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rector's Issues

Run tool

Hi,

I have trouble with run Rector. After creating rector as project (via #46) then I run

rector/bin/rector process /path/to/my-files

Iteration from files was correct (I dumped file names) but it did nothing. Where is the problem, maybe it is in rewrited command?

packagist

Hi,

is it on packagist already?
It looks really great, I want test it :)

 [InvalidArgumentException]                                                                                                                     
  Could not find package rector/rector at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability  

PHPUnit rectors

- $this->assertTrue(is_readable($readmeFile), sprintf('Cannot read "%s".', $readmeFile));
+ $this->assertIsReadable($readmeFile, sprintf('Cannot read "%s".', $readmeFile));

   $this->setExpectedExceptionRegExp(
-            \PhpCsFixer\ConfigurationException\InvalidConfigurationException::class,
+        $this->expectException(InvalidConfigurationException::class);
+        $this->expectExceptionMessageRegExp(
             '#^The config file: ".+[\/\\\]Fixtures[\/\\\]ConfigurationResolverConfigFile[\/\\\]case_5[\/\\\]\.php_cs\.dist" does not return a "PhpCsFixer\\\ConfigInterface" instance\. Got: "string"\.$#'
         );

See PHP-CS-Fixer/PHP-CS-Fixer#3182

Ideas to use abstract class replacer in config way

Faster to bootstrap:

# symfony33.yml
rectors:
    ClassReplacer:
        OldClass: NewClass

It would also make change more transparent and easy to scale - adding new class is now easy.

It's not worth writing custom class and tests, since it only uses AbstractClassReplacerRector over and over again.

What do you think @grogy?

Todo

  • document in docs: How to write Rectors โ†’ Class or method replacement in config

[Symfony] 3.2 to 3.3

For @shopsys โค๏ธ

Ref: https://github.com/symfony/symfony/blob/master/UPGRADE-3.3.md

  • FrameworkBundle classes https://github.com/symfony/symfony/blob/master/UPGRADE-3.3.md#frameworkbundle

  • The console.exception event and the related ConsoleExceptionEvent class have been deprecated in favor of the console.error event and the ConsoleErrorEvent class. The deprecated event and class will be removed in 4.0.

  • The ContextErrorException class is deprecated. \ErrorException will be used instead in 4.0.

[Nette] 2.3 to 2.4

All migration guides in Docs:

Done

  • "In PhpGenerator methods setDocuments(), getDocuments() and addDocument() was replaced by setComment(), getComment() and addComment()" - Closed by #12

  • "Negative validation rules. An alternative for the ~Form::FILLED is Form::BLANK, or ~Form::EQUAL can be replaced with Form::NOT_EQUAL"

  • "Nette\Utils\Html::add() is replaced with addHtml() and addText()" - Closed by #8

Sources

mimic Retors from umpirsky/Symfony-Upgrade-Fixer

See https://github.com/umpirsky/Symfony-Upgrade-Fixer#fixers-available

  • symfony30.yml
Done Name Description
๐Ÿ‘ form_configure_options The method AbstractType::setDefaultOptions(OptionsResolverInterface $resolver) have been renamed to AbstractType::configureOptions(OptionsResolver $resolver).
๐Ÿ‘ form_events The events PRE_BIND, BIND and POST_BIND were renamed to PRE_SUBMIT, SUBMIT and POST_SUBMIT.
๐Ÿ‘ form_getname_to_getblockprefix The method FormTypeInterface::getName() was deprecated, you should now implement FormTypeInterface::getBlockPrefix() instead.
๐Ÿ‘ form_option_names Options precision and virtual was renamed to scale and inherit_data.
๐Ÿ‘ form_parent_type Returning type instances from FormTypeInterface::getParent() is deprecated, return the fully-qualified class name of the parent type class instead.
๐Ÿ‘ form_type_names Instead of referencing types by name, you should reference them by their fully-qualified class name (FQCN) instead.
๐Ÿ‘ get_request The getRequest method of the base controller class was removed, request object is injected in the action method instead.
๐Ÿ‘ inherit_data_aware_iterator The class VirtualFormAwareIterator was renamed to InheritDataAwareIterator.
๐Ÿ‘ progress_bar ProgressHelper has been removed in favor of ProgressBar.
๐Ÿ‘ property_access Renamed PropertyAccess::getPropertyAccessor to PropertyAccess::createPropertyAccessor.

Project specific rectors should be in their own repos

This looks amazing! Really looking forward to testing it. One thing I noticed straight from the README, though. Shouldn't the nette, symfony, etc rectors be in their own repositories? I think it will be a pain, further down the road, to strip them from the main repo and notify everyone to update the dependencies, etc.

Crazy dependencies in Nette 0.9

I get project with full of problems in codebase. For example how are created dependencies:

  protected function createComponent($name)
  {
    switch ($name)
    {
      // models
      case 'catalog': $this->addComponent(Environment::getService('CatalogModel'), $name); return;
      case 'library': $this->addComponent(Environment::getService('LibraryModel'), $name); return;
      case 'page': $this->addComponent(Environment::getService('PageModel'), $name); return;
      case 'seo': $this->addComponent(Environment::getService('SeoModel'), $name); return;
      case 'shop': $this->addComponent(Environment::getService('ShopModel'), $name); return;
      case 'user': $this->addComponent(Environment::getService('UserModel'), $name); return;

      default:
        return parent::createComponent($name);
    }
  }

and using of dependency:

$this['shop']->getShopSubcategories(..);

Any idea how automaticaly repair this? :-))

[Dynamic] Add Argument Replacer

use Symfony\Component\DependencyInjection\ContainerBuilder;

$container = new ContainerBuilder();
$container
    ->register('foo', 'stdClass')
    ->setScope(ContainerBuilder::SCOPE_PROTOTYPE)
;

last call into

  ->setShared(false)

Add multiple types support

E.g.

class MyControl extends Control
{
}
$types = $controlNode->getAttribute(Attribute::TYPES);
dump($types); // ['MyControl', 'Control']

[Dynamic] Property to MethodCall

Should cover

  • getter
  • setter

E.g Symfony 3.0

Before

 class CustomTranslator extends Translator
 {
     public function fooMethod()
     {
        // get locale
        $locale = $this->locale;

        // update locale
        $this->locale = $locale;
     }
 }

After

 class CustomTranslator extends Translator
 {
     public function fooMethod()
     {
        // get locale
        $locale = $this->getLocale();

        // update locale
        $this->setLocale($locale);
    }
 }

Rector fails to run

I run rector as standalone project. If I run it on my project like this:

php w:\git\rector\bin\rector process src --level symfony40

I get following error

...
 - src\Admin\Media\Image\EntityType.php

...and 356 more.

PHP Notice:  Undefined property: PhpParser\Node\Stmt\Trait_::$extends in W:\git\rector\src\NodeAnalyzer\ClassAnalyzer.php on line 48

Notice: Undefined property: PhpParser\Node\Stmt\Trait_::$extends in W:\git\rector\src\NodeAnalyzer\ClassAnalyzer.php on line 48
PHP Notice:  Undefined property: PhpParser\Node\Stmt\Trait_::$implements in W:\git\rector\src\NodeAnalyzer\ClassAnalyzer.php on line 58

Notice: Undefined property: PhpParser\Node\Stmt\Trait_::$implements in W:\git\rector\src\NodeAnalyzer\ClassAnalyzer.php on line 58
PHP Notice:  Undefined property: PhpParser\Node\Stmt\Interface_::$implements in W:\git\rector\src\NodeAnalyzer\ClassAnalyzer.php on line 58

Notice: Undefined property: PhpParser\Node\Stmt\Interface_::$implements in W:\git\rector\src\NodeAnalyzer\ClassAnalyzer.php on line 58

[Rector\BetterReflection\Reflector\Exception\IdentifierNotFound]
  Rector\BetterReflection\Reflection\ReflectionClass "XY\AppBundle\Sentry\SentryObject" could not be found in the located source

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.