rector/docs/FluentBuilderRector.md
2018-02-25 18:34:21 +01:00

2.1 KiB

Master Fluent API Builder

You can add own Rector that extends Rector\Rector\AbstractRector. But it takes lot of code and knowledge to do so.

How about nice fluent API like this?

$rector = $this->builderRectorFactory->create()
    ->matchMethodCallByType('Nette\Application\UI\Control')
    ->matchMethodName('invalidateControl')
    ->changeMethodNameTo('redrawControl');

That can perform followin change:

-$control->invalidateControl();
+$control->redrawControl();

Nice and clear change in 4 lines, with autocomplete and typehinting of PHP.

3 Steps to Build Specific Rector

1. Implement Rector\Contract\Rector\RectorInterface

namespace App\Rector;

use Rector\Contract\Rector\RectorInterface;

final class NetteRectorProvider implements RectorInterface
{
    /**
     * @return RectorInterface[]
     */
    public function provide(): array
    {
        return [];
    }
}

2. Builder the Rector

 namespace App\Rector;

 use Rector\Contract\Rector\RectorInterface;
+use Rector\RectorBuilder\BuilderRectorFactory;

 final class NetteRectorProvider implements RectorInterface
 {
+    /**
+     * @var BuilderRectorFactory
+     */
+    private $builderRectorFactory;
+
+    public function __construct(BuilderRectorFactory $builderRectorFactory)
+    {
+        $this->builderRectorFactory = $builderRectorFactory;
+    }
+
     /**
      * @return RectorInterface[]
      */
     public function provide(): array
     {
+         $redrawControlRector = $this->builderRectorFactory->create()
+            ->matchMethodCallByType('Nette\Application\UI\Control')
+            ->matchMethodName('invalidateControl')
+            ->changeMethodNameTo('redrawControl');
-        return [];
+        return [$redrawControlRector];

     }
 }

3. Register as Service to rector.yml

services:
    _defaults:
        autowire: true

    App\Rector\NetteRectorProvider: ~

That's it!

Now you can load the config and process your code with it:

vendor/bin/rector process src --config rector.yml