Skip to content
Permalink
Branch: master
Find file Copy path
5038 lines (3602 sloc) 96.2 KB

All 243 Rectors Overview

Projects

CakePHP

ModalToGetSetRector

  • class: Rector\CakePHP\Rector\MethodCall\ModalToGetSetRector

Changes combined set/get value() to specific getValue() or setValue(x).

 $object = new InstanceConfigTrait;

-$config = $object->config();
-$config = $object->config('key');
+$config = $object->getConfig();
+$config = $object->getConfig('key');

-$object->config('key', 'value');
-$object->config(['key' => 'value']);
+$object->setConfig('key', 'value');
+$object->setConfig(['key' => 'value']);

Celebrity

SetTypeToCastRector

  • class: Rector\Celebrity\Rector\FuncCall\SetTypeToCastRector

Changes settype() to (type) where possible

 class SomeClass
 {
-    public function run($foo)
+    public function run(array $items)
     {
-        settype($foo, 'string');
+        $foo = (string) $foo;

-        return settype($foo, 'integer');
+        return (int) $foo;
     }
 }

CommonNotEqualRector

  • class: Rector\Celebrity\Rector\NotEqual\CommonNotEqualRector

Use common != instead of less known <> with same meaning

 final class SomeClass
 {
     public function run($one, $two)
     {
-        return $one <> $two;
+        return $one != $two;
     }
 }

LogicalToBooleanRector

  • class: Rector\Celebrity\Rector\BooleanOp\LogicalToBooleanRector

Change OR, AND to ||, && with more common understanding

-if ($f = false or true) {
+if (($f = false) || true) {
     return $f;
 }

CodeQuality

CombinedAssignRector

  • class: Rector\CodeQuality\Rector\Assign\CombinedAssignRector

Simplify $value = $value + 5; assignments to shorter ones

-$value = $value + 5;
+$value += 5;

UseIdenticalOverEqualWithSameTypeRector

  • class: Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector

Use ===/!== over ==/!=, it values have the same type

 class SomeClass
 {
     public function run(int $firstValue, int $secondValue)
     {
-         $isSame = $firstValue == $secondValue;
-         $isDiffernt = $firstValue != $secondValue;
+         $isSame = $firstValue === $secondValue;
+         $isDiffernt = $firstValue !== $secondValue;
     }
 }

SimplifyDuplicatedTernaryRector

  • class: Rector\CodeQuality\Rector\Ternary\SimplifyDuplicatedTernaryRector

Remove ternary that duplicated return value of true : false

 class SomeClass
 {
     public function run(bool $value, string $name)
     {
-         $isTrue = $value ? true : false;
+         $isTrue = $value;
          $isName = $name ? true : false;
     }
 }

TernaryToElvisRector

  • class: Rector\CodeQuality\Rector\Ternary\TernaryToElvisRector

Use ?: instead of ?, where useful

 function elvis()
 {
-    $value = $a ? $a : false;
+    $value = $a ?: false;
 }

SimplifyTautologyTernaryRector

  • class: Rector\CodeQuality\Rector\Ternary\SimplifyTautologyTernaryRector

Simplify tautology ternary to value

-$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;
+$value = $fullyQualifiedTypeHint;

UnnecessaryTernaryExpressionRector

  • class: Rector\CodeQuality\Rector\Ternary\UnnecessaryTernaryExpressionRector

Remove unnecessary ternary expressions.

-$foo === $bar ? true : false;
+$foo === $bar;

ForeachToInArrayRector

  • class: Rector\CodeQuality\Rector\Foreach_\ForeachToInArrayRector

Simplify foreach loops into in_array when possible

-foreach ($items as $item) {
-    if ($item === "something") {
-        return true;
-    }
-}
-
-return false;
+in_array("something", $items, true);

SimplifyForeachToArrayFilterRector

  • class: Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToArrayFilterRector

Simplify foreach with function filtering to array filter

-$directories = [];
 $possibleDirectories = [];
-foreach ($possibleDirectories as $possibleDirectory) {
-    if (file_exists($possibleDirectory)) {
-        $directories[] = $possibleDirectory;
-    }
-}
+$directories = array_filter($possibleDirectories, 'file_exists');

SimplifyForeachToCoalescingRector

  • class: Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToCoalescingRector

Changes foreach that returns set value to ??

-foreach ($this->oldToNewFunctions as $oldFunction => $newFunction) {
-    if ($currentFunction === $oldFunction) {
-        return $newFunction;
-    }
-}
-
-return null;
+return $this->oldToNewFunctions[$currentFunction] ?? null;

SimplifyUselessVariableRector

  • class: Rector\CodeQuality\Rector\Return_\SimplifyUselessVariableRector

Removes useless variable assigns

 function () {
-    $a = true;
-    return $a;
+    return true;
 };

InArrayAndArrayKeysToArrayKeyExistsRector

  • class: Rector\CodeQuality\Rector\FuncCall\InArrayAndArrayKeysToArrayKeyExistsRector

Simplify in_array and array_keys functions combination into array_key_exists when array_keys has one argument only

-in_array("key", array_keys($array), true);
+array_key_exists("key", $array);

SimplifyInArrayValuesRector

  • class: Rector\CodeQuality\Rector\FuncCall\SimplifyInArrayValuesRector

Removes unneeded array_values() in in_array() call

-in_array("key", array_values($array), true);
+in_array("key", $array, true);

SimplifyFuncGetArgsCountRector

  • class: Rector\CodeQuality\Rector\FuncCall\SimplifyFuncGetArgsCountRector

Simplify count of func_get_args() to fun_num_args()

-count(func_get_args());
+func_num_args();

SingleInArrayToCompareRector

  • class: Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector

Changes in_array() with single element to ===

 class SomeClass
 {
     public function run()
     {
-        if (in_array(strtolower($type), ['$this'], true)) {
+        if (strtolower($type) === '$this') {
             return strtolower($type);
         }
     }
 }

SimplifyStrposLowerRector

  • class: Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector

Simplify strpos(strtolower(), "...") calls

-strpos(strtolower($var), "...")"
+stripos($var, "...")"

SimplifyIfNotNullReturnRector

  • class: Rector\CodeQuality\Rector\If_\SimplifyIfNotNullReturnRector

Changes redundant null check to instant return

 $newNode = 'something ;
-if ($newNode !== null) {
-    return $newNode;
-}
-
-return null;
+return $newNode;

ExplicitBoolCompareRector

  • class: Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector

Make if conditions more explicit

 final class SomeController
 {
     public function run($items)
     {
-        if (!count($items)) {
+        if (count($items) < 0) {
             return 'no items';
         }
     }
 }

SimplifyIfElseToTernaryRector

  • class: Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector

Changes if/else for same value as assign to ternary

 class SomeClass
 {
     public function run()
     {
-        if (empty($value)) {
-            $this->arrayBuilt[][$key] = true;
-        } else {
-            $this->arrayBuilt[][$key] = $value;
-        }
+        $this->arrayBuilt[][$key] = empty($value) ? true : $value;
     }
 }

SimplifyIfReturnBoolRector

  • class: Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector

Shortens if return false/true to direct return

-if (strpos($docToken->getContent(), "\n") === false) {
-    return true;
-}
-
-return false;
+return strpos($docToken->getContent(), "\n") === false;

SimplifyIfIssetToNullCoalescingRector

  • class: Rector\CodeQuality\Rector\If_\SimplifyIfIssetToNullCoalescingRector

Simplify binary if to null coalesce

 final class SomeController
 {
     public function run($possibleStatieYamlFile)
     {
-        if (isset($possibleStatieYamlFile['import'])) {
-            $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'], $filesToImport);
-        } else {
-            $possibleStatieYamlFile['import'] = $filesToImport;
-        }
+        $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'] ?? [], $filesToImport);
     }
 }

ConsecutiveNullCompareReturnsToNullCoalesceQueueRector

  • class: Rector\CodeQuality\Rector\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector

Change multiple null compares to ?? queue

 class SomeClass
 {
     public function run()
     {
-        if (null !== $this->orderItem) {
-            return $this->orderItem;
-        }
-
-        if (null !== $this->orderItemUnit) {
-            return $this->orderItemUnit;
-        }
-
-        return null;
+        return $this->orderItem ?? $this->orderItemUnit;
     }
 }

SimplifyDeMorganBinaryRector

  • class: Rector\CodeQuality\Rector\BinaryOp\SimplifyDeMorganBinaryRector

Simplify negated conditions with de Morgan theorem

 <?php

 $a = 5;
 $b = 10;
-$result = !($a > 20 || $b <= 50);
+$result = $a <= 20 && $b > 50;

SimplifyEmptyArrayCheckRector

  • class: Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector

Simplify is_array and empty functions combination into a simple identical check for an empty array

-is_array($values) && empty($values)
+$values === []

GetClassToInstanceOfRector

  • class: Rector\CodeQuality\Rector\Identical\GetClassToInstanceOfRector

Changes comparison with get_class to instanceof

-if (EventsListener::class === get_class($event->job)) { }
+if ($event->job instanceof EventsListener) { }

SimplifyBoolIdenticalTrueRector

  • class: Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector

Symplify bool value compare to true or false

 class SomeClass
 {
     public function run(bool $value, string $items)
     {
-         $match = in_array($value, $items, TRUE) === TRUE;
-         $match = in_array($value, $items, TRUE) !== FALSE;
+         $match = in_array($value, $items, TRUE);
+         $match = in_array($value, $items, TRUE);
     }
 }

SimplifyConditionsRector

  • class: Rector\CodeQuality\Rector\Identical\SimplifyConditionsRector

Simplify conditions

-if (! ($foo !== 'bar')) {...
+if ($foo === 'bar') {...

SimplifyArraySearchRector

  • class: Rector\CodeQuality\Rector\Identical\SimplifyArraySearchRector

Simplify array_search to in_array

-array_search("searching", $array) !== false;
+in_array("searching", $array, true);
-array_search("searching", $array) != false;
+in_array("searching", $array);

JoinStringConcatRector

  • class: Rector\CodeQuality\Rector\Concat\JoinStringConcatRector

Joins concat of 2 strings

 class SomeClass
 {
     public function run()
     {
-        $name = 'Hi' . ' Tom';
+        $name = 'Hi Tom';
     }
 }

CodingStyle

ReturnArrayClassMethodToYieldRector

  • class: Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector

Turns yield return to array return in specific type and method

services:
    Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector:
        EventSubscriberInterface:
            - getSubscribedEvents

 class SomeEventSubscriber implements EventSubscriberInterface
 {
     public static function getSubscribedEvents()
     {
-        yield 'event' => 'callback';
+        return ['event' => 'callback'];
     }
 }

YieldClassMethodToArrayClassMethodRector

  • class: Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector

Turns yield return to array return in specific type and method

services:
    Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector:
        EventSubscriberInterface:
            - getSubscribedEvents

 class SomeEventSubscriber implements EventSubscriberInterface
 {
     public static function getSubscribedEvents()
     {
-        yield 'event' => 'callback';
+        return ['event' => 'callback'];
     }
 }

SymplifyQuoteEscapeRector

  • class: Rector\CodingStyle\Rector\String_\SymplifyQuoteEscapeRector

Prefer quote that not inside the string

 class SomeClass
 {
     public function run()
     {
-         $name = "\" Tom";
-         $name = '\' Sara';
+         $name = '" Tom';
+         $name = "' Sara";
     }
 }

RemoveUnusedAliasRector

  • class: Rector\CodingStyle\Rector\Use_\RemoveUnusedAliasRector

Removes unused use aliases

-use Symfony\Kernel as BaseKernel;
+use Symfony\Kernel;

-class SomeClass extends BaseKernel
+class SomeClass extends Kernel
 {
 }

ConsistentImplodeRector

  • class: Rector\CodingStyle\Rector\FuncCall\ConsistentImplodeRector

Changes various implode forms to consistent one

 class SomeClass
 {
     public function run(array $items)
     {
-        $itemsAsStrings = implode($items);
-        $itemsAsStrings = implode($items, '|');
+        $itemsAsStrings = implode('', $items);
+        $itemsAsStrings = implode('|', $items);

         $itemsAsStrings = implode('|', $items);
     }
 }

SimpleArrayCallableToStringRector

  • class: Rector\CodingStyle\Rector\FuncCall\SimpleArrayCallableToStringRector

Changes redundant anonymous bool functions to simple calls

-$paths = array_filter($paths, function ($path): bool {
-    return is_dir($path);
-});
+array_filter($paths, "is_dir");

NullableCompareToNullRector

  • class: Rector\CodingStyle\Rector\If_\NullableCompareToNullRector

Changes negate of empty comparison of nullable value to explicit === or !== compare

 /** @var stdClass|null $value */
-if ($value) {
+if ($value !== null) {
 }

-if (!$value) {
+if ($value === null) {
 }

CompleteVarDocTypeConstantRector

  • class: Rector\CodingStyle\Rector\ClassConst\CompleteVarDocTypeConstantRector

Complete constant @var annotations for missing one, yet known.

 final class SomeClass
 {
+    /**
+     * @var int
+     */
     private const NUMBER = 5;
 }

IdenticalFalseToBooleanNotRector

  • class: Rector\CodingStyle\Rector\Identical\IdenticalFalseToBooleanNotRector

Changes === false to negate !

-if ($something === false) {}
+if (! $something) {}

BinarySwitchToIfElseRector

  • class: Rector\CodingStyle\Rector\Switch_\BinarySwitchToIfElseRector

Changes switch with 2 options to if-else

-switch ($foo) {
-    case 'my string':
-        $result = 'ok';
-    break;
-
-    default:
-        $result = 'not ok';
+if ($foo == 'my string') {
+    $result = 'ok;
+} else {
+    $result = 'not ok';
 }

DeadCode

RemoveDoubleAssignRector

  • class: Rector\DeadCode\Rector\Assign\RemoveDoubleAssignRector

Simplify useless double assigns

-$value = 1;
 $value = 1;

RemoveUnusedForeachKeyRector

  • class: Rector\DeadCode\Rector\Foreach_\RemoveUnusedForeachKeyRector

Remove unused key in foreach

 $items = [];
-foreach ($items as $key => $value) {
+foreach ($items as $value) {
     $result = $value;
 }

RemoveDuplicatedArrayKeyRector

  • class: Rector\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector

Remove duplicated key in defined arrays.

 $item = [
     1 => 'A',
-    1 => 'A'
 ];

RemoveParentCallWithoutParentRector

  • class: Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector

Remove unused parent call with no parent class

 class OrphanClass
 {
     public function __construct()
     {
-         parent::__construct();
     }
 }

RemoveEmptyClassMethodRector

  • class: Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector

Remove empty method calls not required by parents

 class OrphanClass
 {
-    public function __construct()
-    {
-    }
 }

RemoveUnusedParameterRector

  • class: Rector\DeadCode\Rector\ClassMethod\RemoveUnusedParameterRector

Remove unused parameter, if not required by interface or parent class

 class SomeClass
 {
-    public function __construct($value, $value2)
+    public function __construct($value)
     {
          $this->value = $value;
     }
 }

RemoveDeadConstructorRector

  • class: Rector\DeadCode\Rector\ClassMethod\RemoveDeadConstructorRector

Remove empty constructor

 class SomeClass
 {
-    public function __construct()
-    {
-    }
 }

RemoveUnusedPrivateMethodRector

  • class: Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector

Remove unused private method

 final class SomeController
 {
     public function run()
     {
         return 5;
     }
-
-    private function skip()
-    {
-        return 10;
-    }
 }

RemoveOverriddenValuesRector

  • class: Rector\DeadCode\Rector\ClassMethod\RemoveOverriddenValuesRector

Remove initial assigns of overridden values

 final class SomeController
 {
     public function run()
     {
-         $directories = [];
          $possibleDirectories = [];
          $directories = array_filter($possibleDirectories, 'file_exists');
     }
 }

RemoveUnusedPrivatePropertyRector

  • class: Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector

Remove unused private properties

 class SomeClass
 {
-    private $property;
 }

RemoveDeadStmtRector

  • class: Rector\DeadCode\Rector\Stmt\RemoveDeadStmtRector

Removes dead code statements

-$value = 5;
-$value;
+$value = 5;

RemoveUnusedPrivateConstantRector

  • class: Rector\DeadCode\Rector\ClassConst\RemoveUnusedPrivateConstantRector

Remove unused private constant

 final class SomeController
 {
-    private const SOME_CONSTANT = 5;
     public function run()
     {
         return 5;
     }
 }

RemoveCodeAfterReturnRector

  • class: Rector\DeadCode\Rector\FunctionLike\RemoveCodeAfterReturnRector

Remove dead code after return statement

 class SomeClass
 {
     public function run(int $a)
     {
          return $a;
-         $a++;
     }
 }

SimplifyMirrorAssignRector

  • class: Rector\DeadCode\Rector\Expression\SimplifyMirrorAssignRector

Removes unneeded $a = $a assigns

-$a = $a;

Doctrine

AliasToClassRector

  • class: Rector\Doctrine\Rector\AliasToClassRector

Replaces doctrine alias with class.

 $entityManager = new Doctrine\ORM\EntityManager();
-$entityManager->getRepository("AppBundle:Post");
+$entityManager->getRepository(\App\Entity\Post::class);

DomainDrivenDesign

ObjectToScalarDocBlockRector

  • class: Rector\DomainDrivenDesign\Rector\ObjectToScalar\ObjectToScalarDocBlockRector

Turns defined value object to simple types in doc blocks

services:
    Rector\DomainDrivenDesign\Rector\ObjectToScalar\ObjectToScalarDocBlockRector:
        $valueObjectsToSimpleTypes:
            ValueObject: string

 /**
- * @var ValueObject|null
+ * @var string|null
  */
 private $name;

-/** @var ValueObject|null */
+/** @var string|null */
 $name;

ObjectToScalarRector

  • class: Rector\DomainDrivenDesign\Rector\ObjectToScalar\ObjectToScalarRector

Remove values objects and use directly the value.

services:
    Rector\DomainDrivenDesign\Rector\ObjectToScalar\ObjectToScalarRector:
        $valueObjectsToSimpleTypes:
            ValueObject: string

-$name = new ValueObject("name");
+$name = "name";

-function someFunction(ValueObject $name): ?ValueObject {
+function someFunction(string $name): ?string {
 }

Guzzle

MessageAsArrayRector

  • class: Rector\Guzzle\Rector\MethodCall\MessageAsArrayRector

Changes getMessage(..., true) to getMessageAsArray()

 /** @var GuzzleHttp\Message\MessageInterface */
-$value = $message->getMessage('key', true);
+$value = $message->getMessageAsArray('key');

Jms

JmsInjectAnnotationRector

  • class: Rector\Jms\Rector\Property\JmsInjectAnnotationRector

Changes properties with @JMS\DiExtraBundle\Annotation\Inject to constructor injection

 use JMS\DiExtraBundle\Annotation as DI;

 class SomeController
 {
     /**
-     * @DI\Inject("entity.manager")
+     * @var EntityManager
      */
     private $entityManager;
+
+    public function __construct(EntityManager $entityManager)
+    {
+        $this->entityManager = entityManager;
+    }
 }

Laravel

MinutesToSecondsInCacheRector

  • class: Rector\Laravel\Rector\StaticCall\MinutesToSecondsInCacheRector

Change minutes argument to seconds in Illuminate\Contracts\Cache\Store and Illuminate\Support\Facades\Cache

 class SomeClass
 {
     public function run()
     {
-        Illuminate\Support\Facades\Cache::put('key', 'value', 60);
+        Illuminate\Support\Facades\Cache::put('key', 'value', 60 * 60);
     }
 }

FacadeStaticCallToConstructorInjectionRector

  • class: Rector\Laravel\Rector\StaticCall\FacadeStaticCallToConstructorInjectionRector

Move Illuminate\Support\Facades* static calls to constructor injection

 use Illuminate\Support\Facades\Response;

 class ExampleController extends Controller
 {
+    /**
+     * @var \Illuminate\Contracts\Routing\ResponseFactory
+     */
+    private $responseFactory;
+
+    public function __construct(\Illuminate\Contracts\Routing\ResponseFactory $responseFactory)
+    {
+        $this->responseFactory = $responseFactory;
+    }
+
     public function store()
     {
-        return Response::view('example', ['new_example' => 123]);
+        return $this->responseFactory->view('example', ['new_example' => 123]);
     }
 }

Redirect301ToPermanentRedirectRector

  • class: Rector\Laravel\Rector\StaticCall\Redirect301ToPermanentRedirectRector

Change "redirect" call with 301 to "permanentRedirect"

 class SomeClass
 {
     public function run()
     {
-        Illuminate\Routing\Route::redirect('/foo', '/bar', 301);
+        Illuminate\Routing\Route::permanentRedirect('/foo', '/bar');
     }
 }

RequestStaticValidateToInjectRector

  • class: Rector\Laravel\Rector\StaticCall\RequestStaticValidateToInjectRector

Change static validate() method to $request->validate()

 use Illuminate\Http\Request;

 class SomeClass
 {
-    public function store()
+    public function store(\Illuminate\Http\Request $request)
     {
-        $validatedData = Request::validate(['some_attribute' => 'required']);
+        $validatedData = $request->validate(['some_attribute' => 'required']);
     }
 }

HelperFunctionToConstructorInjectionRector

  • class: Rector\Laravel\Rector\FuncCall\HelperFunctionToConstructorInjectionRector

Move help facade-like function calls to constructor injection

 class SomeController
 {
+    /**
+     * @var \Illuminate\Contracts\View\Factory
+     */
+    private $viewFactory;
+
+    public function __construct(\Illuminate\Contracts\View\Factory $viewFactory)
+    {
+        $this->viewFactory = $viewFactory;
+    }
+
     public function action()
     {
-        $template = view('template.blade');
-        $viewFactory = view();
+        $template = $this->viewFactory->make('template.blade');
+        $viewFactory = $this->viewFactory;
     }
 }

MysqlToMysqli

MysqlAssignToMysqliRector

  • class: Rector\MysqlToMysqli\Rector\Assign\MysqlAssignToMysqliRector

Converts more complex mysql functions to mysqli

-$data = mysql_db_name($result, $row);
+mysqli_data_seek($result, $row);
+$fetch = mysql_fetch_row($result);
+$data = $fetch[0];

MysqlFuncCallToMysqliRector

  • class: Rector\MysqlToMysqli\Rector\FuncCall\MysqlFuncCallToMysqliRector

Converts more complex mysql functions to mysqli

-mysql_drop_db($database);
+mysqli_query('DROP DATABASE ' . $database);

MysqlPConnectToMysqliConnectRector

  • class: Rector\MysqlToMysqli\Rector\FuncCall\MysqlPConnectToMysqliConnectRector

Replace mysql_pconnect() with mysqli_connect() with host p: prefix

 final class SomeClass
 {
     public function run($host, $username, $password)
     {
-        return mysql_pconnect($host, $username, $password);
+        return mysqli_connect('p:' . $host, $username, $password);
     }
 }

NetteTesterToPHPUnit

NetteTesterClassToPHPUnitClassRector

  • class: Rector\NetteTesterToPHPUnit\Rector\Class_\NetteTesterClassToPHPUnitClassRector

Migrate Nette Tester test case to PHPUnit

 namespace KdybyTests\Doctrine;

 use Tester\TestCase;
 use Tester\Assert;

-require_once __DIR__ . '/../bootstrap.php';
-
-class ExtensionTest extends TestCase
+class ExtensionTest extends \PHPUnit\Framework\TestCase
 {
-    public function setUp()
+    protected function setUp()
     {
     }

     public function testFunctionality()
     {
-        Assert::true($default instanceof Kdyby\Doctrine\EntityManager);
-        Assert::true(5);
-        Assert::same($container->getService('kdyby.doctrine.default.entityManager'), $default);
+        self::assertInstanceOf(\Kdyby\Doctrine\EntityManager::cllass, $default);
+        self::assertTrue(5);
+        self::same($container->getService('kdyby.doctrine.default.entityManager'), $default);
     }
-}
-
-(new \ExtensionTest())->run();
+}

NetteToSymfony

RouterListToControllerAnnotationsRector

  • class: Rector\NetteToSymfony\Rector\ClassMethod\RouterListToControllerAnnotationsRector

Change new Route() from RouteFactory to @Route annotation above controller method

 final class RouterFactory
 {
     public function create(): RouteList
     {
         $routeList = new RouteList();
+
+        // case of single action controller, usually get() or __invoke() method
         $routeList[] = new Route('some-path', SomePresenter::class);

         return $routeList;
     }
 }

 final class SomePresenter
 {
+    /**
+     * @Symfony\Component\Routing\Annotation\Route(path="some-path")
+     */
     public function run()
     {
     }
 }

RenameEventNamesInEventSubscriberRector

  • class: Rector\NetteToSymfony\Rector\ClassMethod\RenameEventNamesInEventSubscriberRector

Changes event names from Nette ones to Symfony ones

 use Symfony\Component\EventDispatcher\EventSubscriberInterface;

 final class SomeClass implements EventSubscriberInterface
 {
     public static function getSubscribedEvents()
     {
-        return ['nette.application' => 'someMethod'];
+        return [\SymfonyEvents::KERNEL => 'someMethod'];
     }
 }

FromRequestGetParameterToAttributesGetRector

  • class: Rector\NetteToSymfony\Rector\MethodCall\FromRequestGetParameterToAttributesGetRector

Changes "getParameter()" to "attributes->get()" from Nette to Symfony

 use Nette\Request;

 final class SomeController
 {
     public static function someAction(Request $request)
     {
-        $value = $request->getParameter('abz');
+        $value = $request->attribute->get('abz');
     }
 }

FromHttpRequestGetHeaderToHeadersGetRector

  • class: Rector\NetteToSymfony\Rector\MethodCall\FromHttpRequestGetHeaderToHeadersGetRector

Changes getHeader() to $request->headers->get()

 use Nette\Request;

 final class SomeController
 {
     public static function someAction(Request $request)
     {
-        $header = $this->httpRequest->getHeader('x');
+        $header = $request->headers->get('x');
     }
 }

WrapTransParameterNameRector

  • class: Rector\NetteToSymfony\Rector\MethodCall\WrapTransParameterNameRector

Adds %% to placeholder name of trans() method if missing

 use Symfony\Component\Translation\Translator;

 final class SomeController
 {
     public function run()
     {
         $translator = new Translator('');
         $translated = $translator->trans(
             'Hello %name%',
-            ['name' => $name]
+            ['%name%' => $name]
         );
     }
 }

PHPStan

PHPStormVarAnnotationRector

  • class: Rector\PHPStan\Rector\Assign\PHPStormVarAnnotationRector

Change various @var annotation formats to one PHPStorm understands

-$config = 5;
-/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+$config = 5;

RecastingRemovalRector

  • class: Rector\PHPStan\Rector\Cast\RecastingRemovalRector

Removes recasting of the same type

 $string = '';
-$string = (string) $string;
+$string = $string;

 $array = [];
-$array = (array) $array;
+$array = $array;

PHPUnit

SimplifyForeachInstanceOfRector

  • class: Rector\PHPUnit\Rector\Foreach_\SimplifyForeachInstanceOfRector

Simplify unnecessary foreach check of instances

-foreach ($foos as $foo) {
-    $this->assertInstanceOf(\SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);

AssertEqualsParameterToSpecificMethodsTypeRector

  • class: Rector\PHPUnit\Rector\MethodCall\AssertEqualsParameterToSpecificMethodsTypeRector

Change assertEquals()/assertNotEquals() method parameters to new specific alternatives

 final class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $value = 'value';
-        $this->assertEquals('string', $value, 'message', 5.0);
+        $this->assertEqualsWithDelta('string', $value, 5.0, 'message');

-        $this->assertEquals('string', $value, 'message', 0.0, 20);
+        $this->assertEquals('string', $value, 'message', 0.0);

-        $this->assertEquals('string', $value, 'message', 0.0, 10, true);
+        $this->assertEqualsCanonicalizing('string', $value, 'message');

-        $this->assertEquals('string', $value, 'message', 0.0, 10, false, true);
+        $this->assertEqualsIgnoringCase('string', $value, 'message');
     }
 }

SpecificAssertContainsRector

  • class: Rector\PHPUnit\Rector\MethodCall\SpecificAssertContainsRector

Change assertContains()/assertNotContains() method to new string and iterable alternatives

 <?php

 final class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
-        $this->assertContains('foo', 'foo bar');
-        $this->assertNotContains('foo', 'foo bar');
+        $this->assertStringContainsString('foo', 'foo bar');
+        $this->assertStringNotContainsString('foo', 'foo bar');
     }
 }

ReplaceAssertArraySubsetRector

  • class: Rector\PHPUnit\Rector\MethodCall\ReplaceAssertArraySubsetRector

Replace deprecated "assertArraySubset()" method with alternative methods

 class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $checkedArray = [];

-        $this->assertArraySubset([
-           'cache_directory' => 'new_value',
-        ], $checkedArray);
+        $this->assertArrayHasKey('cache_directory', $checkedArray);
+        $this->assertSame('new_value', $checkedArray['cache_directory']);
     }
 }

UseSpecificWillMethodRector

  • class: Rector\PHPUnit\Rector\MethodCall\UseSpecificWillMethodRector

Changes ->will($this->xxx()) to one specific method

 class SomeClass extends PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $translator = $this->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')->getMock();
         $translator->expects($this->any())
             ->method('trans')
-            ->with($this->equalTo('old max {{ max }}!'))
-            ->will($this->returnValue('translated max {{ max }}!'));
+            ->with('old max {{ max }}!')
+            ->willReturnValue('translated max {{ max }}!');
     }
 }

SpecificAssertInternalTypeRector

  • class: Rector\PHPUnit\Rector\MethodCall\SpecificAssertInternalTypeRector

Change assertInternalType()/assertNotInternalType() method to new specific alternatives

 final class SomeTest extends \PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $value = 'value';
-        $this->assertInternalType('string', $value);
-        $this->assertNotInternalType('array', $value);
+        $this->assertIsString($value);
+        $this->assertIsNotArray($value);
     }
 }

ExceptionAnnotationRector

  • class: Rector\PHPUnit\Rector\ExceptionAnnotationRector

Takes setExpectedException() 2nd and next arguments to own methods in PHPUnit.

-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
 public function test()
 {
+    $this->expectException('Exception');
+    $this->expectExceptionMessage('Message');
     // tested code
 }

AssertNotOperatorRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertNotOperatorRector

Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
-$this->assertFalse(!$foo, "message");
+$this->assertTrue($foo, "message");

AssertComparisonToSpecificMethodRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertComparisonToSpecificMethodRector

Turns comparison operations to their method name alternatives in PHPUnit TestCase

-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
-$this->assertFalse($foo >= $bar, "message");
+$this->assertLessThanOrEqual($bar, $foo, "message");

AssertPropertyExistsRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertPropertyExistsRector

Turns property_exists comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue(property_exists(new Class, "property"), "message");
+$this->assertClassHasAttribute("property", "Class", "message");
-$this->assertFalse(property_exists(new Class, "property"), "message");
+$this->assertClassNotHasAttribute("property", "Class", "message");

AssertTrueFalseInternalTypeToSpecificMethodRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertTrueFalseInternalTypeToSpecificMethodRector

Turns true/false with internal type comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue(is_{internal_type}($anything), "message");
+$this->assertInternalType({internal_type}, $anything, "message");
-$this->assertFalse(is_{internal_type}($anything), "message");
+$this->assertNotInternalType({internal_type}, $anything, "message");

AssertIssetToSpecificMethodRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertIssetToSpecificMethodRector

Turns isset comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue(isset($anything->foo));
+$this->assertFalse(isset($anything["foo"]), "message");
-$this->assertObjectHasAttribute("foo", $anything);
+$this->assertArrayNotHasKey("foo", $anything, "message");

AssertFalseStrposToContainsRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertFalseStrposToContainsRector

Turns strpos/stripos comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
-$this->assertNotFalse(stripos($anything, "foo"), "message");
+$this->assertContains("foo", $anything, "message");

AssertSameBoolNullToSpecificMethodRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertSameBoolNullToSpecificMethodRector

Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertSame(null, $anything);
+$this->assertNull($anything);
-$this->assertNotSame(false, $anything);
+$this->assertNotFalse($anything);

AssertCompareToSpecificMethodRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertCompareToSpecificMethodRector

Turns vague php-only method in PHPUnit TestCase to more specific

-$this->assertSame(10, count($anything), "message");
+$this->assertCount(10, $anything, "message");
-$this->assertSame($value, {function}($anything), "message");
+$this->assert{function}($value, $anything, "message\");
-$this->assertEquals($value, {function}($anything), "message");
+$this->assert{function}($value, $anything, "message\");
-$this->assertNotSame($value, {function}($anything), "message");
+$this->assertNot{function}($value, $anything, "message")
-$this->assertNotEquals($value, {function}($anything), "message");
+$this->assertNot{function}($value, $anything, "message")

AssertRegExpRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertRegExpRector

Turns preg_match comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertSame(1, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertRegExp("/^Message for ".*"\.$/", $string, $message);
-$this->assertEquals(false, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertNotRegExp("/^Message for ".*"\.$/", $string, $message);

AssertInstanceOfComparisonRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertInstanceOfComparisonRector

Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertFalse($foo instanceof Foo, "message");
-$this->assertInstanceOf("Foo", $foo, "message");
+$this->assertNotInstanceOf("Foo", $foo, "message");

AssertTrueFalseToSpecificMethodRector

  • class: Rector\PHPUnit\Rector\SpecificMethod\AssertTrueFalseToSpecificMethodRector

Turns true/false comparisons to their method name alternatives in PHPUnit TestCase when possible

-$this->assertTrue(is_readable($readmeFile), "message");
+$this->assertIsReadable($readmeFile, "message");

DelegateExceptionArgumentsRector

  • class: Rector\PHPUnit\Rector\DelegateExceptionArgumentsRector

Takes setExpectedException() 2nd and next arguments to own methods in PHPUnit.

-$this->setExpectedException(Exception::class, "Message", "CODE");
+$this->setExpectedException(Exception::class);
+$this->expectExceptionMessage("Message");
+$this->expectExceptionCode("CODE");

TryCatchToExpectExceptionRector

  • class: Rector\PHPUnit\Rector\TryCatchToExpectExceptionRector

Turns try/catch to expectException() call

-try {
-	$someService->run();
-} catch (Throwable $exception) {
-    $this->assertInstanceOf(RuntimeException::class, $e);
-    $this->assertContains('There was an error executing the following script', $e->getMessage());
-}
+$this->expectException(RuntimeException::class);
+$this->expectExceptionMessage('There was an error executing the following script');
+$someService->run();

GetMockRector

  • class: Rector\PHPUnit\Rector\GetMockRector

Turns getMock*() methods to createMock()

-$this->getMock("Class");
+$this->createMock("Class");
-$this->getMockWithoutInvokingTheOriginalConstructor("Class");
+$this->createMock("Class");

Php

AssignArrayToStringRector

  • class: Rector\Php\Rector\Assign\AssignArrayToStringRector

String cannot be turned into array by assignment anymore

-$string = '';
+$string = [];
 $string[] = 1;

NullCoalescingOperatorRector

  • class: Rector\Php\Rector\Assign\NullCoalescingOperatorRector

Use null coalescing operator ??=

 $array = [];
-$array['user_id'] = $array['user_id'] ?? 'value';
+$array['user_id'] ??= 'value';

MysqlAssignToMysqliRector

  • class: Rector\Php\Rector\Assign\MysqlAssignToMysqliRector

Converts more complex mysql functions to mysqli

-$data = mysql_db_name($result, $row);
+mysqli_data_seek($result, $row);
+$fetch = mysql_fetch_row($result);
+$data = $fetch[0];

TernaryToSpaceshipRector

  • class: Rector\Php\Rector\Ternary\TernaryToSpaceshipRector

Use <=> spaceship instead of ternary with same effect

 function order_func($a, $b) {
-    return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
+    return $a <=> $b;
 }

TernaryToNullCoalescingRector

  • class: Rector\Php\Rector\Ternary\TernaryToNullCoalescingRector

Changes unneeded null check to ?? operator

-$value === null ? 10 : $value;
+$value ?? 10;
-isset($value) ? $value : 10;
+$value ?? 10;

StaticCallOnNonStaticToInstanceCallRector

  • class: Rector\Php\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector

Changes static call to instance call, where not useful

 class Something
 {
     public function doWork()
     {
     }
 }

 class Another
 {
     public function run()
     {
-        return Something::doWork();
+        return (new Something)->doWork();
     }
 }

ExportToReflectionFunctionRector

  • class: Rector\Php\Rector\StaticCall\ExportToReflectionFunctionRector

Change export() to ReflectionFunction alternatives

-$reflectionFunction = ReflectionFunction::export('foo');
-$reflectionFunctionAsString = ReflectionFunction::export('foo', true);
+$reflectionFunction = new ReflectionFunction('foo');
+$reflectionFunctionAsString = (string) new ReflectionFunction('foo');

ThisCallOnStaticMethodToStaticCallRector

  • class: Rector\Php\Rector\MethodCall\ThisCallOnStaticMethodToStaticCallRector

Changes $this->call() to static method to static call

 class SomeClass
 {
     public static function run()
     {
-        $this->eat();
+        self::eat();
     }

     public static function eat()
     {
     }
 }

PreferThisOrSelfMethodCallRector

  • class: Rector\Php\Rector\MethodCall\PreferThisOrSelfMethodCallRector

Changes $this->... to self:: or vise versa for specific types

services:
    Rector\Php\Rector\MethodCall\PreferThisOrSelfMethodCallRector:
        PHPUnit\TestCase: self

 class SomeClass extends PHPUnit\TestCase
 {
     public function run()
     {
-        $this->assertThis();
+        self::assertThis();
     }
 }

UnsetCastRector

  • class: Rector\Php\Rector\Unset_\UnsetCastRector

Removes (unset) cast

-$value = (unset) $value;
+$value = null;

ReservedObjectRector

  • class: Rector\Php\Rector\Name\ReservedObjectRector

Changes reserved "Object" name to "Object" where can be configured

-class Object
+class SmartObject
 {
 }

SensitiveHereNowDocRector

  • class: Rector\Php\Rector\String_\SensitiveHereNowDocRector

Changes heredoc/nowdoc that contains closing word to safe wrapper name

-$value = <<<A
+$value = <<<A_WRAP
     A
-A
+A_WRAP

SensitiveConstantNameRector

  • class: Rector\Php\Rector\ConstFetch\SensitiveConstantNameRector

Changes case insensitive constants to sensitive ones.

 define('FOO', 42, true);
 var_dump(FOO);
-var_dump(foo);
+var_dump(FOO);

BarewordStringRector

  • class: Rector\Php\Rector\ConstFetch\BarewordStringRector

Changes unquoted non-existing constants to strings

-var_dump(VAR);
+var_dump("VAR");

RenameConstantRector

  • class: Rector\Php\Rector\ConstFetch\RenameConstantRector

Replace constant by new ones

 final class SomeClass
 {
     public function run()
     {
-        return MYSQL_ASSOC;
+        return MYSQLI_ASSOC;
     }
 }

MultiExceptionCatchRector

  • class: Rector\Php\Rector\TryCatch\MultiExceptionCatchRector

Changes multi catch of same exception to single one | separated.

 try {
    // Some code...
-} catch (ExceptionType1 $exception) {
-   $sameCode;
-} catch (ExceptionType2 $exception) {
+} catch (ExceptionType1 | ExceptionType2 $exception) {
    $sameCode;
 }

CompleteVarDocTypePropertyRector

  • class: Rector\Php\Rector\Property\CompleteVarDocTypePropertyRector

Complete property @var annotations for missing one, yet known.

 final class SomeClass
 {
+    /**
+     * @var EventDispatcher
+     */
     private $eventDispatcher;

     public function __construct(EventDispatcher $eventDispatcher)
     {
         $this->eventDispatcher = $eventDispatcher;
     }
 }

TypedPropertyRector

  • class: Rector\Php\Rector\Property\TypedPropertyRector

Changes property @var annotations from annotation to type.

 final class SomeClass
 {
-    /**
-     * @var int
-     */
-    private count;
+    private int count;
 }

VarToPublicPropertyRector

  • class: Rector\Php\Rector\Property\VarToPublicPropertyRector

Remove unused private method

 final class SomeController
 {
-    var $name = 'Tom';
+    public $name = 'Tom';
 }

ClassConstantToSelfClassRector

  • class: Rector\Php\Rector\MagicConstClass\ClassConstantToSelfClassRector

Change CLASS to self::class

 class SomeClass
 {
    public function callOnMe()
    {
-       var_dump(__CLASS__);
+       var_dump(self::class);
    }
 }

RealToFloatTypeCastRector

  • class: Rector\Php\Rector\Double\RealToFloatTypeCastRector

Change deprecated (real) to (float)

 class SomeClass
 {
     public function run()
     {
-        $number = (real) 5;
+        $number = (float) 5;
         $number = (float) 5;
         $number = (double) 5;
     }
 }

CreateFunctionToAnonymousFunctionRector

  • class: Rector\Php\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector

Use anonymous functions instead of deprecated create_function()

 class ClassWithCreateFunction
 {
     public function run()
     {
-        $callable = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);");
+        $callable = function($matches) use ($delimiter) {
+            return $delimiter . strtolower($matches[1]);
+        };
     }
 }

RandomFunctionRector

  • class: Rector\Php\Rector\FuncCall\RandomFunctionRector

Changes rand, srand and getrandmax by new md_* alternatives.

-rand();
+mt_rand();

PregReplaceEModifierRector

  • class: Rector\Php\Rector\FuncCall\PregReplaceEModifierRector

The /e modifier is no longer supported, use preg_replace_callback instead

 class SomeClass
 {
     public function run()
     {
-        $comment = preg_replace('~\b(\w)(\w+)~e', '"$1".strtolower("$2")', $comment);
+        $comment = preg_replace_callback('~\b(\w)(\w+)~', function ($matches) {
+              return($matches[1].strtolower($matches[2]));
+        }, , $comment);
     }
 }

FilterVarToAddSlashesRector

  • class: Rector\Php\Rector\FuncCall\FilterVarToAddSlashesRector

Change filter_var() with slash escaping to addslashes()

 $var= "Satya's here!";
-filter_var($var, FILTER_SANITIZE_MAGIC_QUOTES);
+addslashes($var);

GetClassOnNullRector

  • class: Rector\Php\Rector\FuncCall\GetClassOnNullRector

Null is no more allowed in get_class()

 final class SomeClass
 {
     public function getItem()
     {
         $value = null;
-        return get_class($value);
+        return $value !== null ? get_class($value) : self::class;
     }
 }

ArrayKeyExistsOnPropertyRector

  • class: Rector\Php\Rector\FuncCall\ArrayKeyExistsOnPropertyRector

Change array_key_exists() on property to property_exists()

 class SomeClass {
      public $value;
 }
 $someClass = new SomeClass;

-array_key_exists('value', $someClass);
+property_exists($someClass, 'value');

ArrayKeyFirstLastRector

  • class: Rector\Php\Rector\FuncCall\ArrayKeyFirstLastRector

Make use of array_key_first() and array_key_last()

-reset($items);
-$firstKey = key($items);
+$firstKey = array_key_first($items);
-end($items);
-$lastKey = key($items);
+$lastKey = array_key_last($items);

CallUserMethodRector

  • class: Rector\Php\Rector\FuncCall\CallUserMethodRector

Changes call_user_method()/call_user_method_array() to call_user_func()/call_user_func_array()

-call_user_method($method, $obj, "arg1", "arg2");
+call_user_func(array(&$obj, "method"), "arg1", "arg2");

StringifyStrNeedlesRector

  • class: Rector\Php\Rector\FuncCall\StringifyStrNeedlesRector

Makes needles explicit strings

 $needle = 5;
-$fivePosition = strpos('725', $needle);
+$fivePosition = strpos('725', (string) $needle);

StringsAssertNakedRector

  • class: Rector\Php\Rector\FuncCall\StringsAssertNakedRector

String asserts must be passed directly to assert()

 function nakedAssert()
 {
-    assert('true === true');
-    assert("true === true");
+    assert(true === true);
+    assert(true === true);
 }

ParseStrWithResultArgumentRector

  • class: Rector\Php\Rector\FuncCall\ParseStrWithResultArgumentRector

Use $result argument in parse_str() function

-parse_str($this->query);
-$data = get_defined_vars();
+parse_str($this->query, $result);
+$data = $result;

RemoveReferenceFromCallRector

  • class: Rector\Php\Rector\FuncCall\RemoveReferenceFromCallRector

Remove & from function and method calls

 final class SomeClass
 {
     public function run($one)
     {
-        return strlen(&$one);
+        return strlen($one);
     }
 }

IsObjectOnIncompleteClassRector

  • class: Rector\Php\Rector\FuncCall\IsObjectOnIncompleteClassRector

Incomplete class returns inverted bool on is_object()

 $incompleteObject = new __PHP_Incomplete_Class;
-$isObject = is_object($incompleteObject);
+$isObject = ! is_object($incompleteObject);

RemoveExtraParametersRector

  • class: Rector\Php\Rector\FuncCall\RemoveExtraParametersRector

Remove extra parameters

-strlen("asdf", 1);
+strlen("asdf");

GetCalledClassToStaticClassRector

  • class: Rector\Php\Rector\FuncCall\GetCalledClassToStaticClassRector

Change CLASS to self::class

 class SomeClass
-{
-   public function callOnMe()
-   {
-       var_dump( get_called_class());
-   }
-}
+    {
+       public function callOnMe()
+       {
+           var_dump( static::class);
+       }
+    }

CountOnNullRector

  • class: Rector\Php\Rector\FuncCall\CountOnNullRector

Changes count() on null to safe ternary check

 $values = null;
-$count = count($values);
+$count = is_array($values) || $values instanceof Countable ? count($values) : 0;

SensitiveDefineRector

  • class: Rector\Php\Rector\FuncCall\SensitiveDefineRector

Changes case insensitive constants to sensitive ones.

-define('FOO', 42, true);
+define('FOO', 42);

RegexDashEscapeRector

  • class: Rector\Php\Rector\FuncCall\RegexDashEscapeRector

Escape - in some cases

-preg_match("#[\w-()]#", 'some text');
+preg_match("#[\w\-()]#", 'some text');

MultiDirnameRector

  • class: Rector\Php\Rector\FuncCall\MultiDirnameRector

Changes multiple dirname() calls to one with nesting level

-dirname(dirname($path));
+dirname($path, 2);

JsonThrowOnErrorRector

  • class: Rector\Php\Rector\FuncCall\JsonThrowOnErrorRector

Adds JSON_THROW_ON_ERROR to json_encode() and json_decode() to throw JsonException on error

-json_encode($content);
-json_decode($json);
+json_encode($content, JSON_THROW_ON_ERROR
+json_decode($json, null, null, JSON_THROW_ON_ERROR););

StringifyDefineRector

  • class: Rector\Php\Rector\FuncCall\StringifyDefineRector

Make first argument of define() string

 class SomeClass
 {
     public function run(int $a)
     {
-         define(CONSTANT_2, 'value');
+         define('CONSTANT_2', 'value');
          define('CONSTANT', 'value');
     }
 }

SwapFuncCallArgumentsRector

  • class: Rector\Php\Rector\FuncCall\SwapFuncCallArgumentsRector

Swap arguments in function calls

 final class SomeClass
 {
     public function run($one, $two)
     {
-        return some_function($one, $two);
+        return some_function($two, $one);
     }
 }

EregToPregMatchRector

  • class: Rector\Php\Rector\FuncCall\EregToPregMatchRector

Changes ereg*() to preg*() calls

-ereg("hi")
+preg_match("#hi#");

MbStrrposEncodingArgumentPositionRector

  • class: Rector\Php\Rector\FuncCall\MbStrrposEncodingArgumentPositionRector

Change mb_strrpos() encoding argument position

-mb_strrpos($text, "abc", "UTF-8");
+mb_strrpos($text, "abc", 0, "UTF-8");

PowToExpRector

  • class: Rector\Php\Rector\FuncCall\PowToExpRector

Changes pow(val, val2) to ** (exp) parameter

-pow(1, 2);
+1**2;

IfToSpaceshipRector

  • class: Rector\Php\Rector\If_\IfToSpaceshipRector

Changes if/else to spaceship <=> where useful

 class SomeClass
 {
     public function run()
     {
         usort($languages, function ($a, $b) {
-            if ($a[0] === $b[0]) {
-                return 0;
-            }
-
-            return ($a[0] < $b[0]) ? 1 : -1;
+            return $b[0] <=> $a[0];
         });
     }
 }

IsCountableRector

  • class: Rector\Php\Rector\BinaryOp\IsCountableRector

Changes is_array + Countable check to is_countable

-is_array($foo) || $foo instanceof Countable;
+is_countable($foo);

IsIterableRector

  • class: Rector\Php\Rector\BinaryOp\IsIterableRector

Changes is_array + Traversable check to is_iterable

-is_array($foo) || $foo instanceof Traversable;
+is_iterable($foo);

PublicConstantVisibilityRector

  • class: Rector\Php\Rector\ClassConst\PublicConstantVisibilityRector

Add explicit public constant visibility.

 class SomeClass
 {
-    const HEY = 'you';
+    public const HEY = 'you';
 }

ExceptionHandlerTypehintRector

  • class: Rector\Php\Rector\FunctionLike\ExceptionHandlerTypehintRector

Changes property @var annotations from annotation to type.

-function handler(Exception $exception) { ... }
+function handler(Throwable $exception) { ... }
 set_exception_handler('handler');

ReturnTypeDeclarationRector

  • class: Rector\Php\Rector\FunctionLike\ReturnTypeDeclarationRector

Change @return types and type from static analysis to type declarations if not a BC-break

 <?php

 class SomeClass
 {
     /**
      * @return int
      */
-    public function getCount()
+    public function getCount(): int
     {
     }
 }

ParamTypeDeclarationRector

  • class: Rector\Php\Rector\FunctionLike\ParamTypeDeclarationRector

Change @param types to type declarations if not a BC-break

 <?php

 class ParentClass
 {
     /**
      * @param int $number
      */
     public function keep($number)
     {
     }
 }

 final class ChildClass extends ParentClass
 {
     /**
      * @param int $number
      */
     public function keep($number)
     {
     }

     /**
      * @param int $number
      */
-    public function change($number)
+    public function change(int $number)
     {
     }
 }

Php4ConstructorRector

  • class: Rector\Php\Rector\FunctionLike\Php4ConstructorRector

Changes PHP 4 style constructor to __construct.

 class SomeClass
 {
-    public function SomeClass()
+    public function __construct()
     {
     }
 }

WhileEachToForeachRector

  • class: Rector\Php\Rector\Each\WhileEachToForeachRector

each() function is deprecated, use foreach() instead.

-while (list($key, $callback) = each($callbacks)) {
+foreach ($callbacks as $key => $callback) {
     // ...
 }
-while (list($key) = each($callbacks)) {
+foreach (array_keys($callbacks) as $key) {
     // ...
 }

ListEachRector

  • class: Rector\Php\Rector\Each\ListEachRector

each() function is deprecated, use foreach() instead.

-list($key, $callback) = each($callbacks);
+$key = key($opt->option);
+$val = current($opt->option);

ListSplitStringRector

  • class: Rector\Php\Rector\List_\ListSplitStringRector

list() cannot split string directly anymore, use str_split()

-list($foo) = "string";
+list($foo) = str_split("string");

EmptyListRector

  • class: Rector\Php\Rector\List_\EmptyListRector

list() cannot be empty

-list() = $values;
+list($generated) = $values;

ListSwapArrayOrderRector

  • class: Rector\Php\Rector\List_\ListSwapArrayOrderRector

list() assigns variables in reverse order - relevant in array assign

-list($a[], $a[]) = [1, 2];
+list($a[], $a[]) = array_reverse([1, 2])];

ReduceMultipleDefaultSwitchRector

  • class: Rector\Php\Rector\Switch_\ReduceMultipleDefaultSwitchRector

Remove first default switch, that is ignored

 switch ($expr) {
     default:
-         echo "Hello World";
-
-    default:
          echo "Goodbye Moon!";
          break;
 }

ContinueToBreakInSwitchRector

  • class: Rector\Php\Rector\Switch_\ContinueToBreakInSwitchRector

Use break instead of continue in switch statements

 function some_run($value)
 {
     switch ($value) {
         case 1:
             echo 'Hi';
-            continue;
+            break;
         case 2:
             echo 'Hello';
             break;
     }
 }

PhpParser

RemoveNodeRector

  • class: Rector\PhpParser\Rector\RemoveNodeRector

Turns integer return to remove node to constant in NodeVisitor of PHP-Parser

 public function leaveNode()
 {
-    return false;
+    return NodeTraverser::REMOVE_NODE;
 }

ParamAndStaticVarNameRector

  • class: Rector\PhpParser\Rector\ParamAndStaticVarNameRector

Turns old string var to var->name sub-variable in Node of PHP-Parser

-$paramNode->name;
+$paramNode->var->name;
-$staticVarNode->name;
+$staticVarNode->var->name;

IdentifierRector

  • class: Rector\PhpParser\Rector\IdentifierRector

Turns node string names to Identifier object in php-parser

 $constNode = new PhpParser\Node\Const_;
-$name = $constNode->name;
+$name = $constNode->name->toString();'

CatchAndClosureUseNameRector

  • class: Rector\PhpParser\Rector\CatchAndClosureUseNameRector

Turns $catchNode->var to its new name property in php-parser

-$catchNode->var;
+$catchNode->var->name

SetLineRector

  • class: Rector\PhpParser\Rector\SetLineRector

Turns standalone line method to attribute in Node of PHP-Parser

-$node->setLine(5);
+$node->setAttribute("line", 5);

UseWithAliasRector

  • class: Rector\PhpParser\Rector\UseWithAliasRector

Turns use property to method and $node->alias to last name in UseAlias Node of PHP-Parser

-$node->alias;
+$node->getAlias();
-$node->name->getLast();
+$node->alias

PhpSpecToPHPUnit

RenameSpecFileToTestFileRector

  • class: Rector\PhpSpecToPHPUnit\Rector\RenameSpecFileToTestFileRector

Rename "*Spec.php" file to "*Test.php" file


PhpSpecClassToPHPUnitClassRector

  • class: Rector\PhpSpecToPHPUnit\Rector\Class_\PhpSpecClassToPHPUnitClassRector

Migrate PhpSpec object behavior spec to PHPUnit test case

-namespace spec\SomeNamespaceForThisTest;
+namespace SomeNamespaceForThisTest;

 use PhpSpec\ObjectBehavior;

-class CartSpec extends ObjectBehavior
+class CartTest extends \PHPUnit\Framework\TestCase
 {
-    public function let()
+    protected function setUp()
     {
-        $this->beConstructedWith(5);
+        $this->cart = new Cart(5);
     }

-    public function it_returns_id()
+    public function testReturnsId()
     {
-        $this->id()->shouldReturn(5);
+        $this->assertSame(5, $this->cart->id());
     }
 }

Sensio

TemplateAnnotationRector

  • class: Rector\Sensio\Rector\FrameworkExtraBundle\TemplateAnnotationRector

Turns @Template annotation to explicit method call in Controller of FrameworkExtraBundle in Symfony

-/**
- * @Template()
- */
 public function indexAction()
 {
+    return $this->render("index.html.twig");
 }

Shopware

ReplaceEnlightResponseWithSymfonyResponseRector

  • class: Rector\Shopware\Rector\MethodCall\ReplaceEnlightResponseWithSymfonyResponseRector

Replace Enlight Response methods with Symfony Response methods

 class FrontendController extends \Enlight_Controller_Action
 {
     public function run()
     {
-        $this->Response()->setHeader('Foo', 'Yea');
+        $this->Response()->headers->set('Foo', 'Yea');
     }
 }

Silverstripe

ConstantToStaticCallRector

  • class: Rector\Silverstripe\Rector\ConstantToStaticCallRector

Turns defined constant to static method call.

-SS_DATABASE_NAME;
+Environment::getEnv("SS_DATABASE_NAME");

DefineConstantToStaticCallRector

  • class: Rector\Silverstripe\Rector\DefineConstantToStaticCallRector

Turns defined function call to static method call.

-defined("SS_DATABASE_NAME");
+Environment::getEnv("SS_DATABASE_NAME");

Sylius

ReplaceCreateMethodWithoutReviewerRector

  • class: Rector\Sylius\Rector\Review\ReplaceCreateMethodWithoutReviewerRector

Turns createForSubjectWithReviewer() with null review to standalone method in Sylius

-$this->createForSubjectWithReviewer($subject, null)
+$this->createForSubject($subject)

Symfony

GetRequestRector

  • class: Rector\Symfony\Rector\HttpKernel\GetRequestRector

Turns fetching of dependencies via $this->get() to constructor injection in Command and Controller in Symfony

+use Symfony\Component\HttpFoundation\Request;
+
 class SomeController
 {
-    public function someAction()
+    public action(Request $request)
     {
-        $this->getRequest()->...();
+        $request->...();
     }
 }

AddFlashRector

  • class: Rector\Symfony\Rector\Controller\AddFlashRector

Turns long flash adding to short helper method in Controller in Symfony

 class SomeController extends Controller
 {
     public function some(Request $request)
     {
-        $request->getSession()->getFlashBag()->add("success", "something");
+        $this->addFlash("success", "something");
     }
 }

RedirectToRouteRector

  • class: Rector\Symfony\Rector\Controller\RedirectToRouteRector

Turns redirect to route to short helper method in Controller in Symfony

-$this->redirect($this->generateUrl("homepage"));
+$this->redirectToRoute("homepage");

ActionSuffixRemoverRector

  • class: Rector\Symfony\Rector\Controller\ActionSuffixRemoverRector

Removes Action suffixes from methods in Symfony Controllers

 class SomeController
 {
-    public function indexAction()
+    public function index()
     {
     }
 }

CascadeValidationFormBuilderRector

  • class: Rector\Symfony\Rector\MethodCall\CascadeValidationFormBuilderRector

Change "cascade_validation" option to specific node attribute

 class SomeController
 {
     public function someMethod()
     {
-        $form = $this->createFormBuilder($article, ['cascade_validation' => true])
-            ->add('author', new AuthorType())
+        $form = $this->createFormBuilder($article)
+            ->add('author', new AuthorType(), [
+                'constraints' => new \Symfony\Component\Validator\Constraints\Valid(),
+            ])
             ->getForm();
     }

     protected function createFormBuilder()
     {
         return new FormBuilder();
     }
 }

ReadOnlyOptionToAttributeRector

  • class: Rector\Symfony\Rector\MethodCall\ReadOnlyOptionToAttributeRector

Change "read_only" option in form to attribute

 use Symfony\Component\Form\FormBuilderInterface;

 function buildForm(FormBuilderInterface $builder, array $options)
 {
-    $builder->add('cuid', TextType::class, ['read_only' => true]);
+    $builder->add('cuid', TextType::class, ['attr' => [read_only' => true]]);
 }

FormTypeInstanceToClassConstRector

  • class: Rector\Symfony\Rector\MethodCall\FormTypeInstanceToClassConstRector

Changes createForm(new FormType), add(new FormType) to ones with "FormType::class"

 class SomeController
 {
     public function action()
     {
-        $form = $this->createForm(new TeamType, $entity, [
+        $form = $this->createForm(TeamType::class, $entity, [
             'action' => $this->generateUrl('teams_update', ['id' => $entity->getId()]),
             'method' => 'PUT',
-        ]);
+        ));
     }
 }

ConstraintUrlOptionRector

  • class: Rector\Symfony\Rector\Validator\ConstraintUrlOptionRector

Turns true value to Url::CHECK_DNS_TYPE_ANY in Validator in Symfony.

-$constraint = new Url(["checkDNS" => true]);
+$constraint = new Url(["checkDNS" => Url::CHECK_DNS_TYPE_ANY]);

ConsoleExceptionToErrorEventConstantRector

  • class: Rector\Symfony\Rector\Console\ConsoleExceptionToErrorEventConstantRector

Turns old event name with EXCEPTION to ERROR constant in Console in Symfony

-"console.exception"
+Symfony\Component\Console\ConsoleEvents::ERROR
-Symfony\Component\Console\ConsoleEvents::EXCEPTION
+Symfony\Component\Console\ConsoleEvents::ERROR

StringToArrayArgumentProcessRector

  • class: Rector\Symfony\Rector\New_\StringToArrayArgumentProcessRector

Changes Process string argument to an array

 use Symfony\Component\Process\Process;
-$process = new Process('ls -l');
+$process = new Process(['ls', '-l']);

RootNodeTreeBuilderRector

  • class: Rector\Symfony\Rector\New_\RootNodeTreeBuilderRector

Changes Process string argument to an array

 use Symfony\Component\Config\Definition\Builder\TreeBuilder;

-$treeBuilder = new TreeBuilder();
-$rootNode = $treeBuilder->root('acme_root');
+$treeBuilder = new TreeBuilder('acme_root');
+$rootNode = $treeBuilder->getRootNode();
 $rootNode->someCall();

ParseFileRector

  • class: Rector\Symfony\Rector\Yaml\ParseFileRector

session > use_strict_mode is true by default and can be removed

-session > use_strict_mode: true
+session:

ContainerBuilderCompileEnvArgumentRector

  • class: Rector\Symfony\Rector\DependencyInjection\ContainerBuilderCompileEnvArgumentRector

Turns old default value to parameter in ContinerBuilder->build() method in DI in Symfony

-$containerBuilder = new Symfony\Component\DependencyInjection\ContainerBuilder(); $containerBuilder->compile();
+$containerBuilder = new Symfony\Component\DependencyInjection\ContainerBuilder(); $containerBuilder->compile(true);

VarDumperTestTraitMethodArgsRector

  • class: Rector\Symfony\Rector\VarDumper\VarDumperTestTraitMethodArgsRector

Adds new $format argument in VarDumperTestTrait->assertDumpEquals() in Validator in Symfony.

-$varDumperTestTrait->assertDumpEquals($dump, $data, $mesage = "");
+$varDumperTestTrait->assertDumpEquals($dump, $data, $context = null, $mesage = "");
-$varDumperTestTrait->assertDumpMatchesFormat($dump, $format, $mesage = "");
+$varDumperTestTrait->assertDumpMatchesFormat($dump, $format, $context = null,  $mesage = "");

GetParameterToConstructorInjectionRector

  • class: Rector\Symfony\Rector\FrameworkBundle\GetParameterToConstructorInjectionRector

Turns fetching of parameters via getParameter() in ContainerAware to constructor injection in Command and Controller in Symfony

-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
 {
+    private $someParameter;
+
+    public function __construct($someParameter)
+    {
+        $this->someParameter = $someParameter;
+    }
+
     public function someMethod()
     {
-        $this->getParameter('someParameter');
+        $this->someParameter;
     }
 }

GetToConstructorInjectionRector

  • class: Rector\Symfony\Rector\FrameworkBundle\GetToConstructorInjectionRector

Turns fetching of dependencies via $this->get() to constructor injection in Command and Controller in Symfony

-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
 {
+    public function __construct(SomeService $someService)
+    {
+        $this->someService = $someService;
+    }
+
     public function someMethod()
     {
-        // ...
-        $this->get('some_service');
+        $this->someService;
     }
 }

ContainerGetToConstructorInjectionRector

  • class: Rector\Symfony\Rector\FrameworkBundle\ContainerGetToConstructorInjectionRector

Turns fetching of dependencies via $container->get() in ContainerAware to constructor injection in Command and Controller in Symfony

-final class SomeCommand extends ContainerAwareCommand
+final class SomeCommand extends Command
 {
+    public function __construct(SomeService $someService)
+    {
+        $this->someService = $someService;
+    }
+
     public function someMethod()
     {
         // ...
-        $this->getContainer()->get('some_service');
-        $this->container->get('some_service');
+        $this->someService;
+        $this->someService;
     }
 }

FormIsValidRector

  • class: Rector\Symfony\Rector\Form\FormIsValidRector

Adds $form->isSubmitted() validatoin to all $form->isValid() calls in Form in Symfony

-if ($form->isValid()) {
+if ($form->isSubmitted() && $form->isValid()) {
 }

OptionNameRector

  • class: Rector\Symfony\Rector\Form\OptionNameRector

Turns old option names to new ones in FormTypes in Form in Symfony

 $builder = new FormBuilder;
-$builder->add("...", ["precision" => "...", "virtual" => "..."];
+$builder->add("...", ["scale" => "...", "inherit_data" => "..."];

StringFormTypeToClassRector

  • class: Rector\Symfony\Rector\Form\StringFormTypeToClassRector

Turns string Form Type references to their CONSTANT alternatives in FormTypes in Form in Symfony

 $formBuilder = new Symfony\Component\Form\FormBuilder;
-$formBuilder->add('name', 'form.type.text');
+$form->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class);

FormTypeGetParentRector

  • class: Rector\Symfony\Rector\Form\FormTypeGetParentRector

Turns string Form Type references to their CONSTANT alternatives in getParent() and getExtendedType() methods in Form in Symfony

-function getParent() { return "collection"; }
+function getParent() { return CollectionType::class; }
-function getExtendedType() { return "collection"; }
+function getExtendedType() { return CollectionType::class; }

ProcessBuilderGetProcessRector

  • class: Rector\Symfony\Rector\Process\ProcessBuilderGetProcessRector

Removes $processBuilder->getProcess() calls to $processBuilder in Process in Symfony, because ProcessBuilder was removed. This is part of multi-step Rector and has very narrow focus.

 $processBuilder = new Symfony\Component\Process\ProcessBuilder;
-$process = $processBuilder->getProcess();
-$commamdLine = $processBuilder->getProcess()->getCommandLine();
+$process = $processBuilder;
+$commamdLine = $processBuilder->getCommandLine();

ProcessBuilderInstanceRector

  • class: Rector\Symfony\Rector\Process\ProcessBuilderInstanceRector

Turns ProcessBuilder::instance() to new ProcessBuilder in Process in Symfony. Part of multi-step Rector.

-$processBuilder = Symfony\Component\Process\ProcessBuilder::instance($args);
+$processBuilder = new Symfony\Component\Process\ProcessBuilder($args);

Twig

SimpleFunctionAndFilterRector

  • class: Rector\Twig\Rector\SimpleFunctionAndFilterRector

Changes Twig_Function_Method to Twig_SimpleFunction calls in TwigExtension.

 class SomeExtension extends Twig_Extension
 {
     public function getFunctions()
     {
         return [
-            'is_mobile' => new Twig_Function_Method($this, 'isMobile'),
+             new Twig_SimpleFunction('is_mobile', [$this, 'isMobile']),
         ];
     }

-    public function getFilters()
+    public function getFilteres()
     {
         return [
-            'is_mobile' => new Twig_Filter_Method($this, 'isMobile'),
+             new Twig_SimpleFilter('is_mobile', [$this, 'isMobile']),
         ];
     }
 }


General

Core

PropertyAssignToMethodCallRector

  • class: Rector\Rector\Assign\PropertyAssignToMethodCallRector

Turns property assign of specific type and property name to method call

services:
    Rector\Rector\Assign\PropertyAssignToMethodCallRector:
        $oldPropertiesToNewMethodCallsByType:
            SomeClass:
                oldPropertyName: oldProperty
                newMethodName: newMethodCall

-$someObject = new SomeClass;
-$someObject->oldProperty = false;
+$someObject = new SomeClass;
+$someObject->newMethodCall(false);

MultipleClassFileToPsr4ClassesRector

  • class: Rector\Rector\Psr4\MultipleClassFileToPsr4ClassesRector

Turns namespaced classes in one file to standalone PSR-4 classes.

+// new file: "app/Exceptions/FirstException.php"
 namespace App\Exceptions;

 use Exception;

 final class FirstException extends Exception
 {

 }
+
+// new file: "app/Exceptions/SecondException.php"
+namespace App\Exceptions;
+
+use Exception;

 final class SecondException extends Exception
 {

 }

StaticCallToFunctionRector

  • class: Rector\Rector\StaticCall\StaticCallToFunctionRector

Turns static call to function call.

services:
    Rector\Rector\StaticCall\StaticCallToFunctionRector:
        $staticCallToFunction:
            OldClass:
                oldMethod: new_function

-OldClass::oldMethod("args");
+new_function("args");

WrapReturnRector

  • class: Rector\Rector\ClassMethod\WrapReturnRector

Wrap return value of specific method

services:
    Rector\Rector\ClassMethod\WrapReturnRector:
        SomeClass:
            getItem: array

 final class SomeClass
 {
     public function getItem()
     {
-        return 1;
+        return [1];
     }
 }

AddReturnTypeDeclarationRector

  • class: Rector\Rector\ClassMethod\AddReturnTypeDeclarationRector

Changes defined return typehint of method and class.

services:
    Rector\Rector\ClassMethod\AddReturnTypeDeclarationRector:
        SomeClass:
            getData: array

 class SomeClass
 {
-    public getData();
+    public getData(): array;
 }

MethodCallToAnotherMethodCallWithArgumentsRector

  • class: Rector\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector

Turns old method call with specfici type to new one with arguments

services:
    Rector\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector:
        Nette\DI\ServiceDefinition:
            setInject:
                -
                    - addTag
                    -
                        - inject

 $serviceDefinition = new Nette\DI\ServiceDefinition;
-$serviceDefinition->setInject();
+$serviceDefinition->addTag('inject');

RenameMethodRector

  • class: Rector\Rector\MethodCall\RenameMethodRector

Turns method names to new ones.

services:
    Rector\Rector\MethodCall\RenameMethodRector:
        SomeExampleClass:
            oldMethod: newMethod

 $someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();

RenameStaticMethodRector

  • class: Rector\Rector\MethodCall\RenameStaticMethodRector

Turns method names to new ones.

services:
    Rector\Rector\MethodCall\RenameStaticMethodRector:
        SomeClass:
            oldMethod:
                - AnotherExampleClass
                - newStaticMethod

-SomeClass::oldStaticMethod();
+AnotherExampleClass::newStaticMethod();
services:
    Rector\Rector\MethodCall\RenameStaticMethodRector:
        $oldToNewMethodByClasses:
            SomeClass:
                oldMethod: newStaticMethod

-SomeClass::oldStaticMethod();
+SomeClass::newStaticMethod();

RenameMethodCallRector

  • class: Rector\Rector\MethodCall\RenameMethodCallRector

Turns method call names to new ones.

services:
    Rector\Rector\MethodCall\RenameMethodCallRector:
        SomeExampleClass:
            oldMethod: newMethod

 $someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();

FluentReplaceRector

  • class: Rector\Rector\MethodBody\FluentReplaceRector

Turns fluent interface calls to classic ones.

services:
    Rector\Rector\MethodBody\FluentReplaceRector:
        -
            - SomeExampleClass

 $someClass = new SomeClass();
-$someClass->someFunction()
-            ->otherFunction();
+$someClass->someFunction();
+$someClass->otherFunction();

NormalToFluentRector

  • class: Rector\Rector\MethodBody\NormalToFluentRector

Turns fluent interface calls to classic ones.

services:
    Rector\Rector\MethodBody\NormalToFluentRector:
        SomeClass:
            - someFunction
            - otherFunction

 $someObject = new SomeClass();
-$someObject->someFunction();
-$someObject->otherFunction();
+$someObject->someFunction()
+    ->otherFunction();

ReturnThisRemoveRector

  • class: Rector\Rector\MethodBody\ReturnThisRemoveRector

Removes "return $this;" from fluent interfaces for specified classes.

services:
    Rector\Rector\MethodBody\ReturnThisRemoveRector:
        -
            - SomeExampleClass

 class SomeClass
 {
     public function someFunction()
     {
-        return $this;
     }

     public function otherFunction()
     {
-        return $this;
     }
 }

ToStringToMethodCallRector

  • class: Rector\Rector\MagicDisclosure\ToStringToMethodCallRector

Turns defined code uses of "__toString()" method to specific method calls.

services:
    Rector\Rector\MagicDisclosure\ToStringToMethodCallRector:
        SomeObject: getPath

 $someValue = new SomeObject;
-$result = (string) $someValue;
-$result = $someValue->__toString();
+$result = $someValue->getPath();
+$result = $someValue->getPath();

GetAndSetToMethodCallRector

  • class: Rector\Rector\MagicDisclosure\GetAndSetToMethodCallRector

Turns defined __get/__set to specific method calls.

services:
    Rector\Rector\MagicDisclosure\GetAndSetToMethodCallRector:
        SomeContainer:
            set: addService

 $container = new SomeContainer;
-$container->someService = $someService;
+$container->setService("someService", $someService);
services:
    Rector\Rector\MagicDisclosure\GetAndSetToMethodCallRector:
        $typeToMethodCalls:
            SomeContainer:
                get: getService

 $container = new SomeContainer;
-$someService = $container->someService;
+$someService = $container->getService("someService");

UnsetAndIssetToMethodCallRector

  • class: Rector\Rector\MagicDisclosure\UnsetAndIssetToMethodCallRector

Turns defined __isset/__unset calls to specific method calls.

services:
    Rector\Rector\MagicDisclosure\UnsetAndIssetToMethodCallRector:
        SomeContainer:
            isset: hasService

 $container = new SomeContainer;
-isset($container["someKey"]);
+$container->hasService("someKey");
services:
    Rector\Rector\MagicDisclosure\UnsetAndIssetToMethodCallRector:
        SomeContainer:
            unset: removeService

 $container = new SomeContainer;
-unset($container["someKey"]);
+$container->removeService("someKey");

ParentTypehintedArgumentRector

  • class: Rector\Rector\Typehint\ParentTypehintedArgumentRector

Changes defined parent class typehints.

services:
    Rector\Rector\Typehint\ParentTypehintedArgumentRector:
        SomeInterface:
            read:
                $content: string

 interface SomeInterface
 {
     public read(string $content);
 }

 class SomeClass implements SomeInterface
 {
-    public read($content);
+    public read(string $content);
 }

StringToClassConstantRector

  • class: Rector\Rector\String_\StringToClassConstantRector

Changes strings to specific constants

services:
    Rector\Rector\String_\StringToClassConstantRector:
        compiler.post_dump:
            - Yet\AnotherClass
            - CONSTANT

 final class SomeSubscriber
 {
     public static function getSubscribedEvents()
     {
-        return ['compiler.post_dump' => 'compile'];
+        return [\Yet\AnotherClass::CONSTANT => 'compile'];
     }
 }

ArgumentAdderRector

  • class: Rector\Rector\Argument\ArgumentAdderRector

This Rector adds new default arguments in calls of defined methods and class types.

services:
    Rector\Rector\Argument\ArgumentAdderRector:
        SomeExampleClass:
            someMethod:
                -
                    name: someArgument
                    default_value: 'true'
                    type: SomeType

 $someObject = new SomeExampleClass;
-$someObject->someMethod();
+$someObject->someMethod(true);
services:
    Rector\Rector\Argument\ArgumentAdderRector:
        SomeExampleClass:
            someMethod:
                -
                    name: someArgument
                    default_value: 'true'
                    type: SomeType

 class MyCustomClass extends SomeExampleClass
 {
-    public function someMethod()
+    public function someMethod($value = true)
     {
     }
 }

ArgumentRemoverRector

  • class: Rector\Rector\Argument\ArgumentRemoverRector

Removes defined arguments in defined methods and their calls.

services:
    Rector\Rector\Argument\ArgumentRemoverRector:
        ExampleClass:
            someMethod:
                -
                    value: 'true'

 $someObject = new SomeClass;
-$someObject->someMethod(true);
+$someObject->someMethod();'

ArgumentDefaultValueReplacerRector

  • class: Rector\Rector\Argument\ArgumentDefaultValueReplacerRector

Replaces defined map of arguments in defined methods and their calls.

services:
    Rector\Rector\Argument\ArgumentDefaultValueReplacerRector:
        SomeExampleClass:
            someMethod:
                -
                    -
                        before: 'SomeClass::OLD_CONSTANT'
                        after: 'false'

 $someObject = new SomeClass;
-$someObject->someMethod(SomeClass::OLD_CONSTANT);
+$someObject->someMethod(false);'

NewToStaticCallRector

  • class: Rector\Rector\New_\NewToStaticCallRector

Change new Object to static call

services:
    Rector\Rector\New_\NewToStaticCallRector:
        Cookie:
            -
                - Cookie
                - create

 class SomeClass
 {
     public function run()
     {
-        new Cookie($name);
+        Cookie::create($name);
     }
 }

PseudoNamespaceToNamespaceRector

  • class: Rector\Rector\Namespace_\PseudoNamespaceToNamespaceRector

Replaces defined Pseudo_Namespaces by Namespace\Ones.

services:
    Rector\Rector\Namespace_\PseudoNamespaceToNamespaceRector:
        -
            Some_: {  }

-$someService = new Some_Object;
+$someService = new Some\Object;
services:
    Rector\Rector\Namespace_\PseudoNamespaceToNamespaceRector:
        -
            Some_:
                - Some_Class_To_Keep

-/** @var Some_Object $someService */
-$someService = new Some_Object;
+/** @var Some\Object $someService */
+$someService = new Some\Object;
 $someClassToKeep = new Some_Class_To_Keep;

RenameNamespaceRector

  • class: Rector\Rector\Namespace_\RenameNamespaceRector

Replaces old namespace by new one.

services:
    Rector\Rector\Namespace_\RenameNamespaceRector:
        $oldToNewNamespaces:
            SomeOldNamespace: SomeNewNamespace

-$someObject = new SomeOldNamespace\SomeClass;
+$someObject = new SomeNewNamespace\SomeClass;

FunctionToMethodCallRector

  • class: Rector\Rector\Function_\FunctionToMethodCallRector

Turns defined function calls to local method calls.

services:
    Rector\Rector\Function_\FunctionToMethodCallRector:
        view:
            - this
            - render

-view("...", []);
+$this->render("...", []);

FunctionToStaticCallRector

  • class: Rector\Rector\Function_\FunctionToStaticCallRector

Turns defined function call to static method call.

services:
    Rector\Rector\Function_\FunctionToStaticCallRector:
        view:
            - SomeStaticClass
            - render

-view("...", []);
+SomeClass::render("...", []);

RenameFunctionRector

  • class: Rector\Rector\Function_\RenameFunctionRector

Turns defined function call new one.

services:
    Rector\Rector\Function_\RenameFunctionRector:
        view: Laravel\Templating\render

-view("...", []);
+Laravel\Templating\render("...", []);

PropertyToMethodRector

  • class: Rector\Rector\Property\PropertyToMethodRector

Replaces properties assign calls be defined methods.

services:
    Rector\Rector\Property\PropertyToMethodRector:
        $perClassPropertyToMethods:
            SomeObject:
                property:
                    get: getProperty
                    set: setProperty

-$result = $object->property;
-$object->property = $value;
+$result = $object->getProperty();
+$object->setProperty($value);
services:
    Rector\Rector\Property\PropertyToMethodRector:
        $perClassPropertyToMethods:
            SomeObject:
                property:
                    get:
                        method: getConfig
                        arguments:
                            - someArg

-$result = $object->property;
+$result = $object->getProperty('someArg');

RenamePropertyRector

  • class: Rector\Rector\Property\RenamePropertyRector

Replaces defined old properties by new ones.

services:
    Rector\Rector\Property\RenamePropertyRector:
        $oldToNewPropertyByTypes:
            SomeClass:
                someOldProperty: someNewProperty

-$someObject->someOldProperty;
+$someObject->someNewProperty;

AnnotatedPropertyInjectToConstructorInjectionRector

  • class: Rector\Rector\Architecture\DependencyInjection\AnnotatedPropertyInjectToConstructorInjectionRector

Turns non-private properties with @annotation to private properties and constructor injection

services:
    Rector\Rector\Architecture\DependencyInjection\AnnotatedPropertyInjectToConstructorInjectionRector:
        $annotation: inject

 /**
  * @var SomeService
- * @inject
  */
-public $someService;
+private $someService;
+
+public function __construct(SomeService $someService)
+{
+    $this->someService = $someService;
+}

ReplaceVariableByPropertyFetchRector

  • class: Rector\Rector\Architecture\DependencyInjection\ReplaceVariableByPropertyFetchRector

Turns variable in controller action to property fetch, as follow up to action injection variable to property change.

 final class SomeController
 {
     /**
      * @var ProductRepository
      */
     private $productRepository;

     public function __construct(ProductRepository $productRepository)
     {
         $this->productRepository = $productRepository;
     }

     public function default()
     {
-        $products = $productRepository->fetchAll();
+        $products = $this->productRepository->fetchAll();
     }
 }

ActionInjectionToConstructorInjectionRector

  • class: Rector\Rector\Architecture\DependencyInjection\ActionInjectionToConstructorInjectionRector

Turns action injection in Controllers to constructor injection

 final class SomeController
 {
-    public function default(ProductRepository $productRepository)
+    /**
+     * @var ProductRepository
+     */
+    private $productRepository;
+    public function __construct(ProductRepository $productRepository)
     {
-        $products = $productRepository->fetchAll();
+        $this->productRepository = $productRepository;
+    }
+
+    public function default()
+    {
+        $products = $this->productRepository->fetchAll();
     }
 }

NewObjectToFactoryCreateRector

  • class: Rector\Rector\Architecture\Factory\NewObjectToFactoryCreateRector

Replaces creating object instances with "new" keyword with factory method.

services:
    Rector\Rector\Architecture\Factory\NewObjectToFactoryCreateRector:
        MyClass:
            class: MyClassFactory
            method: create

 class SomeClass
 {
+	/**
+	 * @var \MyClassFactory
+	 */
+	private $myClassFactory;
+
 	public function example() {
-		new MyClass($argument);
+		$this->myClassFactory->create($argument);
 	}
 }

ReplaceParentRepositoryCallsByRepositoryPropertyRector

  • class: Rector\Rector\Architecture\RepositoryAsService\ReplaceParentRepositoryCallsByRepositoryPropertyRector

Handles method calls in child of Doctrine EntityRepository and moves them to "$this->repository" property.

 <?php

 use Doctrine\ORM\EntityRepository;

 class SomeRepository extends EntityRepository
 {
     public function someMethod()
     {
-        return $this->findAll();
+        return $this->repository->findAll();
     }
 }

ServiceLocatorToDIRector

  • class: Rector\Rector\Architecture\RepositoryAsService\ServiceLocatorToDIRector

Turns "$this->getRepository()" in Symfony Controller to constructor injection and private property access.

 class ProductController extends Controller
 {
+    /**
+     * @var ProductRepository
+     */
+    private $productRepository;
+
+    public function __construct(ProductRepository $productRepository)
+    {
+        $this->productRepository = $productRepository;
+    }
+
     public function someAction()
     {
         $entityManager = $this->getDoctrine()->getManager();
-        $entityManager->getRepository('SomethingBundle:Product')->findSomething(...);
+        $this->productRepository->findSomething(...);
     }
 }

MoveRepositoryFromParentToConstructorRector

  • class: Rector\Rector\Architecture\RepositoryAsService\MoveRepositoryFromParentToConstructorRector

Turns parent EntityRepository class to constructor dependency

services:
    Rector\Rector\Architecture\RepositoryAsService\MoveRepositoryFromParentToConstructorRector:
        $entityRepositoryClass: Doctrine\ORM\EntityRepository
        $entityManagerClass: Doctrine\ORM\EntityManager

 namespace App\Repository;

+use App\Entity\Post;
 use Doctrine\ORM\EntityRepository;

-final class PostRepository extends EntityRepository
+final class PostRepository
 {
+    /**
+     * @var \Doctrine\ORM\EntityRepository
+     */
+    private $repository;
+    public function __construct(\Doctrine\ORM\EntityManager $entityManager)
+    {
+        $this->repository = $entityManager->getRepository(\App\Entity\Post::class);
+    }
 }

FunctionToNewRector

  • class: Rector\Rector\FuncCall\FunctionToNewRector

Change configured function calls to new Instance

 class SomeClass
 {
     public function run()
     {
-        $array = collection([]);
+        $array = new \Collection([]);
     }
 }

RemoveTraitRector

  • class: Rector\Rector\ClassLike\RemoveTraitRector

Remove specific traits from code

 class SomeClass
 {
-    use SomeTrait;
 }

RemoveInterfacesRector

  • class: Rector\Rector\Interface_\RemoveInterfacesRector

Removes interfaces usage from class.

services:
    Rector\Rector\Interface_\RemoveInterfacesRector:
        - SomeInterface

-class SomeClass implements SomeInterface
+class SomeClass
 {
 }

MergeInterfacesRector

  • class: Rector\Rector\Interface_\MergeInterfacesRector

Merges old interface to a new one, that already has its methods

services:
    Rector\Rector\Interface_\MergeInterfacesRector:
        SomeOldInterface: SomeInterface

-class SomeClass implements SomeInterface, SomeOldInterface
+class SomeClass implements SomeInterface
 {
 }

ChangeMethodVisibilityRector

  • class: Rector\Rector\Visibility\ChangeMethodVisibilityRector

Change visibility of method from parent class.

services:
    Rector\Rector\Visibility\ChangeMethodVisibilityRector:
        FrameworkClass:
            someMethod: protected

 class FrameworkClass
 {
     protected someMethod()
     {
     }
 }

 class MyClass extends FrameworkClass
 {
-    public someMethod()
+    protected someMethod()
     {
     }
 }

ChangePropertyVisibilityRector

  • class: Rector\Rector\Visibility\ChangePropertyVisibilityRector

Change visibility of property from parent class.

services:
    Rector\Rector\Visibility\ChangePropertyVisibilityRector:
        FrameworkClass:
            someProperty: protected

 class FrameworkClass
 {
     protected $someProperty;
 }

 class MyClass extends FrameworkClass
 {
-    public $someProperty;
+    protected $someProperty;
 }

ChangeConstantVisibilityRector

  • class: Rector\Rector\Visibility\ChangeConstantVisibilityRector

Change visibility of constant from parent class.

services:
    Rector\Rector\Visibility\ChangeConstantVisibilityRector:
        ParentObject:
            SOME_CONSTANT: protected

 class FrameworkClass
 {
     protected const SOME_CONSTANT = 1;
 }

 class MyClass extends FrameworkClass
 {
-    public const SOME_CONSTANT = 1;
+    protected const SOME_CONSTANT = 1;
 }

RenameAnnotationRector

  • class: Rector\Rector\Annotation\RenameAnnotationRector

Turns defined annotations above properties and methods to their new values.

services:
    Rector\Rector\Annotation\RenameAnnotationRector:
        PHPUnit\Framework\TestCase:
            test: scenario

 class SomeTest extends PHPUnit\Framework\TestCase
 {
-    /**
-     * @test
+    /**
+     * @scenario
      */
     public function someMethod()
     {
     }
 }

RenameClassConstantRector

  • class: Rector\Rector\Constant\RenameClassConstantRector

Replaces defined class constants in their calls.

services:
    Rector\Rector\Constant\RenameClassConstantRector:
        SomeClass:
            OLD_CONSTANT: NEW_CONSTANT
            OTHER_OLD_CONSTANT: 'DifferentClass::NEW_CONSTANT'

-$value = SomeClass::OLD_CONSTANT;
-$value = SomeClass::OTHER_OLD_CONSTANT;
+$value = SomeClass::NEW_CONSTANT;
+$value = DifferentClass::NEW_CONSTANT;

RenameClassConstantsUseToStringsRector

  • class: Rector\Rector\Constant\RenameClassConstantsUseToStringsRector

Replaces constant by value

services:
    Rector\Rector\Constant\RenameClassConstantsUseToStringsRector:
        Nette\Configurator:
            DEVELOPMENT: development
            PRODUCTION: production

-$value === Nette\Configurator::DEVELOPMENT
+$value === "development"

RenameClassRector

  • class: Rector\Rector\Class_\RenameClassRector

Replaces defined classes by new ones.

services:
    Rector\Rector\Class_\RenameClassRector:
        SomeOldClass: SomeNewClass

-use SomeOldClass;
+use SomeNewClass;

-function someFunction(SomeOldClass $someOldClass): SomeOldClass
+function someFunction(SomeNewClass $someOldClass): SomeNewClass
 {
-    if ($someOldClass instanceof SomeOldClass) {
-        return new SomeOldClass;
+    if ($someOldClass instanceof SomeNewClass) {
+        return new SomeNewClass;
     }
 }

ParentClassToTraitsRector

  • class: Rector\Rector\Class_\ParentClassToTraitsRector

Replaces parent class to specific traits

services:
    Rector\Rector\Class_\ParentClassToTraitsRector:
        Nette\Object:
            - Nette\SmartObject

-class SomeClass extends Nette\Object
+class SomeClass
 {
+    use Nette\SmartObject;
 }

You can’t perform that action at this time.