Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
20 contributors

Users who have contributed to this file

@TomasVotruba @github-actions @dobryy @samsonasik @u01jmg3 @mssimi @norberttech @guilliamxavier @zingimmick @simivar @ComiR @Gymnasiast
10084 lines (7284 sloc) 215 KB

413 Rules Overview


Categories


Arguments

ArgumentAdderRector

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

🔧 configure it!

<?php

declare(strict_types=1);

use PHPStan\Type\ObjectType;
use Rector\Arguments\Rector\ClassMethod\ArgumentAdderRector;
use Rector\Arguments\ValueObject\ArgumentAdder;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(ArgumentAdderRector::class, [
        new ArgumentAdder('SomeExampleClass', 'someMethod', 0, 'someArgument', true, new ObjectType('SomeType')),
    ]);
};

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

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

FunctionArgumentDefaultValueReplacerRector

Streamline the operator arguments of version_compare function

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Arguments\Rector\FuncCall\FunctionArgumentDefaultValueReplacerRector;
use Rector\Arguments\ValueObject\ReplaceFuncCallArgumentDefaultValue;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(FunctionArgumentDefaultValueReplacerRector::class, [
        new ReplaceFuncCallArgumentDefaultValue('version_compare', 2, 'gte', 'ge'),
    ]);
};

-version_compare(PHP_VERSION, '5.6', 'gte');
+version_compare(PHP_VERSION, '5.6', 'ge');

RemoveMethodCallParamRector

Remove parameter of method call

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Arguments\Rector\MethodCall\RemoveMethodCallParamRector;
use Rector\Arguments\ValueObject\RemoveMethodCallParam;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(RemoveMethodCallParamRector::class, [
        new RemoveMethodCallParam('Caller', 'process', 1),
    ]);
};

 final class SomeClass
 {
     public function run(Caller $caller)
     {
-        $caller->process(1, 2);
+        $caller->process(1);
     }
 }

ReplaceArgumentDefaultValueRector

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

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Arguments\Rector\ClassMethod\ReplaceArgumentDefaultValueRector;
use Rector\Arguments\ValueObject\ReplaceArgumentDefaultValue;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(ReplaceArgumentDefaultValueRector::class, [
        new ReplaceArgumentDefaultValue('SomeClass', 'someMethod', 0, 'SomeClass::OLD_CONSTANT', false),
    ]);
};

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

SwapFuncCallArgumentsRector

Reorder arguments in function calls

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Arguments\Rector\FuncCall\SwapFuncCallArgumentsRector;
use Rector\Arguments\ValueObject\SwapFuncCallArguments;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(SwapFuncCallArgumentsRector::class, [
        new SwapFuncCallArguments('some_function', [
            2,
            1,
            0,
        ]),
    ]);
};

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

CodeQuality

AbsolutizeRequireAndIncludePathRector

include/require to absolute path. This Rector might introduce backwards incompatible code, when the include/require being changed depends on the current working directory.

 class SomeClass
 {
     public function run()
     {
-        require 'autoload.php';
+        require __DIR__ . '/autoload.php';

         require $variable;
     }
 }

AddPregQuoteDelimiterRector

Add preg_quote delimiter when missing

-'#' . preg_quote('name') . '#';
+'#' . preg_quote('name', '#') . '#';

AndAssignsToSeparateLinesRector

Split 2 assigns ands to separate line

 class SomeClass
 {
     public function run()
     {
         $tokens = [];
-        $token = 4 and $tokens[] = $token;
+        $token = 4;
+        $tokens[] = $token;
     }
 }

ArrayKeyExistsTernaryThenValueToCoalescingRector

Change array_key_exists() ternary to coalescing

 class SomeClass
 {
     public function run($values, $keyToMatch)
     {
-        $result = array_key_exists($keyToMatch, $values) ? $values[$keyToMatch] : null;
+        $result = $values[$keyToMatch] ?? null;
     }
 }

ArrayKeysAndInArrayToArrayKeyExistsRector

Replace array_keys() and in_array() to array_key_exists()

 function run($packageName, $values)
 {
-    $keys = array_keys($values);
-    return in_array($packageName, $keys, true);
+    return array_key_exists($packageName, $values);
 }

ArrayMergeOfNonArraysToSimpleArrayRector

Change array_merge of non arrays to array directly

 class SomeClass
 {
     public function go()
     {
         $value = 5;
         $value2 = 10;

-        return array_merge([$value], [$value2]);
+        return [$value, $value2];
     }
 }

BooleanNotIdenticalToNotIdenticalRector

Negated identical boolean compare to not identical compare (does not apply to non-bool values)

 class SomeClass
 {
     public function run()
     {
         $a = true;
         $b = false;

-        var_dump(! $a === $b); // true
-        var_dump(! ($a === $b)); // true
+        var_dump($a !== $b); // true
+        var_dump($a !== $b); // true
         var_dump($a !== $b); // true
     }
 }

BoolvalToTypeCastRector

Change boolval() to faster and readable (bool) $value

 class SomeClass
 {
     public function run($value)
     {
-        return boolval($value);
+        return (bool) $value;
     }
 }

CallUserFuncWithArrowFunctionToInlineRector

Refactor call_user_func() with arrow function to direct call

 final class SomeClass
 {
     public function run()
     {
-        $result = \call_user_func(fn () => 100);
+        $result = 100;
     }
 }

CallableThisArrayToAnonymousFunctionRector

Convert [$this, "method"] to proper anonymous function

 class SomeClass
 {
     public function run()
     {
         $values = [1, 5, 3];
-        usort($values, [$this, 'compareSize']);
+        usort($values, function ($first, $second) {
+            return $this->compareSize($first, $second);
+        });

         return $values;
     }

     private function compareSize($first, $second)
     {
         return $first <=> $second;
     }
 }

ChangeArrayPushToArrayAssignRector

Change array_push() to direct variable assign

 $items = [];
-array_push($items, $item);
+$items[] = $item;

CombineIfRector

Merges nested if statements

 class SomeClass
 {
     public function run()
     {
-        if ($cond1) {
-            if ($cond2) {
-                return 'foo';
-            }
+        if ($cond1 && $cond2) {
+            return 'foo';
         }
     }
 }

CombinedAssignRector

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

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

CommonNotEqualRector

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

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

CompactToVariablesRector

Change compact() call to own array

 class SomeClass
 {
     public function run()
     {
         $checkout = 'one';
         $form = 'two';

-        return compact('checkout', 'form');
+        return ['checkout' => $checkout, 'form' => $form];
     }
 }

CompleteDynamicPropertiesRector

Add missing dynamic properties

 class SomeClass
 {
+    /**
+     * @var int
+     */
+    public $value;
+
     public function set()
     {
         $this->value = 5;
     }
 }

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;
     }
 }

ConvertStaticPrivateConstantToSelfRector

Replaces static::* access to private constants with self::*

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\ClassConstFetch\ConvertStaticPrivateConstantToSelfRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(ConvertStaticPrivateConstantToSelfRector::class, [
        ConvertStaticPrivateConstantToSelfRector::ENABLE_FOR_NON_FINAL_CLASSES => false,
    ]);
};

 final class Foo {
     private const BAR = 'bar';
     public function run()
     {
-        $bar = static::BAR;
+        $bar = self::BAR;
     }
 }

ExplicitBoolCompareRector

Make if conditions more explicit

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

ExplicitMethodCallOverMagicGetSetRector

Replace magic property fetch using __get() and __set() with existing method get*()/set*() calls

 class MagicCallsObject
 {
     // adds magic __get() and __set() methods
     use \Nette\SmartObject;

     private $name;

     public function getName()
     {
         return $this->name;
     }
 }

 class SomeClass
 {
     public function run(MagicObject $magicObject)
     {
-        return $magicObject->name;
+        return $magicObject->getName();
     }
 }

FlipTypeControlToUseExclusiveTypeRector

Flip type control to use exclusive type

-/** @var PhpDocInfo|null $phpDocInfo */
 $phpDocInfo = $functionLike->getAttribute(AttributeKey::PHP_DOC_INFO);
-if ($phpDocInfo === null) {
+if (! $phpDocInfo instanceof PhpDocInfo) {
     return;
 }

FloatvalToTypeCastRector

Change floatval() and doubleval() to faster and readable (float) $value

 class SomeClass
 {
     public function run($value)
     {
-        $a = floatval($value);
-        $b = doubleval($value);
+        $a = (float) $value;
+        $b = (float) $value;
     }
 }

ForRepeatedCountToOwnVariableRector

Change count() in for function to own variable

 class SomeClass
 {
     public function run($items)
     {
-        for ($i = 5; $i <= count($items); $i++) {
+        $itemsCount = count($items);
+        for ($i = 5; $i <= $itemsCount; $i++) {
             echo $items[$i];
         }
     }
 }

ForToForeachRector

Change for() to foreach() where useful

 class SomeClass
 {
     public function run($tokens)
     {
-        for ($i = 0, $c = count($tokens); $i < $c; ++$i) {
-            if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'fn') {
+        foreach ($tokens as $i => $token) {
+            if ($token[0] === T_STRING && $token[1] === 'fn') {
                 $tokens[$i][0] = self::T_FN;
             }
         }
     }
 }

ForeachItemsAssignToEmptyArrayToAssignRector

Change foreach() items assign to empty array to direct assign

 class SomeClass
 {
     public function run($items)
     {
         $collectedItems = [];

-        foreach ($items as $item) {
-             $collectedItems[] = $item;
-        }
+        $collectedItems = $items;
     }
 }

ForeachToInArrayRector

Simplify foreach loops into in_array when possible

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

GetClassToInstanceOfRector

Changes comparison with get_class to instanceof

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

InlineArrayReturnAssignRector

Inline just in time array dim fetch assigns to direct return

 function getPerson()
 {
-    $person = [];
-    $person['name'] = 'Timmy';
-    $person['surname'] = 'Back';
-
-    return $person;
+    return [
+        'name' => 'Timmy',
+        'surname' => 'Back',
+    ];
 }

InlineConstructorDefaultToPropertyRector

Move property default from constructor to property default

 final class SomeClass
 {
-    private $name;
+    private $name = 'John';

     public function __construct()
     {
-        $this->name = 'John';
     }
 }

InlineIfToExplicitIfRector

Change inline if to explicit if

 class SomeClass
 {
     public function run()
     {
         $userId = null;

-        is_null($userId) && $userId = 5;
+        if (is_null($userId)) {
+            $userId = 5;
+        }
     }
 }

InlineIsAInstanceOfRector

Change is_a() with object and class name check to instanceof

 class SomeClass
 {
     public function run(object $object)
     {
-        return is_a($object, SomeType::class);
+        return $object instanceof SomeType;
     }
 }

IntvalToTypeCastRector

Change intval() to faster and readable (int) $value

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

IsAWithStringWithThirdArgumentRector

Complete missing 3rd argument in case is_a() function in case of strings

 class SomeClass
 {
     public function __construct(string $value)
     {
-        return is_a($value, 'stdClass');
+        return is_a($value, 'stdClass', true);
     }
 }

IssetOnPropertyObjectToPropertyExistsRector

Change isset on property object to property_exists() and not null check

 class SomeClass
 {
     private $x;

     public function run(): void
     {
-        isset($this->x);
+        property_exists($this, 'x') && $this->x !== null;
     }
 }

JoinStringConcatRector

Joins concat of 2 strings, unless the length is too long

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

LogicalToBooleanRector

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

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

NarrowUnionTypeDocRector

Changes docblock by narrowing type

 class SomeClass {
     /**
-     * @param object|DateTime $message
+     * @param DateTime $message
      */
     public function getMessage(object $message)
     {
     }
 }

NewStaticToNewSelfRector

Change unsafe new static() to new self()

 class SomeClass
 {
     public function build()
     {
-        return new static();
+        return new self();
     }
 }

OptionalParametersAfterRequiredRector

Move required parameters after optional ones

 class SomeObject
 {
-    public function run($optional = 1, $required)
+    public function run($required, $optional = 1)
     {
     }
 }

RemoveAlwaysTrueConditionSetInConstructorRector

If conditions is always true, perform the content right away

 final class SomeClass
 {
     private $value;

     public function __construct(stdClass $value)
     {
         $this->value = $value;
     }

     public function go()
     {
-        if ($this->value) {
-            return 'yes';
-        }
+        return 'yes';
     }
 }

RemoveSoleValueSprintfRector

Remove sprintf() wrapper if not needed

 class SomeClass
 {
     public function run()
     {
-        $value = sprintf('%s', 'hi');
+        $value = 'hi';

         $welcome = 'hello';
-        $value = sprintf('%s', $welcome);
+        $value = $welcome;
     }
 }

ReplaceMultipleBooleanNotRector

Replace the Double not operator (!!) by type-casting to boolean

-$bool = !!$var;
+$bool = (bool) $var;

ReturnTypeFromStrictScalarReturnExprRector

Change return type based on strict scalar returns - string, int, float or bool

 final class SomeClass
 {
-    public function run($value)
+    public function run($value): string
     {
         if ($value) {
             return 'yes';
         }

         return 'no';
     }
 }

SetTypeToCastRector

Changes settype() to (type) where possible

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

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

ShortenElseIfRector

Shortens else/if to elseif

 class SomeClass
 {
     public function run()
     {
         if ($cond1) {
             return $action1;
-        } else {
-            if ($cond2) {
-                return $action2;
-            }
+        } elseif ($cond2) {
+            return $action2;
         }
     }
 }

SimplifyArraySearchRector

Simplify array_search to in_array

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

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

SimplifyBoolIdenticalTrueRector

Simplify 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

Simplify conditions

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

SimplifyDeMorganBinaryRector

Simplify negated conditions with de Morgan theorem

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

SimplifyEmptyArrayCheckRector

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

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

SimplifyEmptyCheckOnEmptyArrayRector

Simplify empty functions calls on empty arrays

-$array = []; if(empty($values))
+$array = []; if([] === $values)

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

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;

SimplifyFuncGetArgsCountRector

Simplify count of func_get_args() to func_num_args()

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

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;
     }
 }

SimplifyIfExactValueReturnValueRector

Changes compared to value and return of expr to direct return

 $value = 'something';
-if ($value === 52) {
-    return 52;
-}
-
 return $value;

SimplifyIfNotNullReturnRector

Changes redundant null check to instant return

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

SimplifyIfNullableReturnRector

Direct return on if nullable check before return

 class SomeClass
 {
     public function run()
     {
-        /** @var \stdClass|null $value */
-        $value = $this->foo->bar();
-        if (! $value instanceof \stdClass) {
-            return null;
-        }
-
-        return $value;
+        return $this->foo->bar();
     }
 }

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;

SimplifyInArrayValuesRector

Removes unneeded array_values() in in_array() call

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

SimplifyRegexPatternRector

Simplify regex pattern to known ranges

 class SomeClass
 {
     public function run($value)
     {
-        preg_match('#[a-zA-Z0-9+]#', $value);
+        preg_match('#[\w\d+]#', $value);
     }
 }

SimplifyStrposLowerRector

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

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

SimplifyTautologyTernaryRector

Simplify tautology ternary to value

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

SimplifyUselessLastVariableAssignRector

Removes the latest useless variable assigns before a variable will return.

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

SimplifyUselessVariableRector

Removes useless variable assigns

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

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);
         }
     }
 }

SingularSwitchToIfRector

Change switch with only 1 check to if

 class SomeObject
 {
     public function run($value)
     {
         $result = 1;
-        switch ($value) {
-            case 100:
+        if ($value === 100) {
             $result = 1000;
         }

         return $result;
     }
 }

SplitListAssignToSeparateLineRector

Splits [$a, $b] = [5, 10] scalar assign to standalone lines

 final class SomeClass
 {
     public function run(): void
     {
-        [$a, $b] = [1, 2];
+        $a = 1;
+        $b = 2;
     }
 }

StrlenZeroToIdenticalEmptyStringRector

Changes strlen comparison to 0 to direct empty string compare

 class SomeClass
 {
     public function run(string $value)
     {
-        $empty = strlen($value) === 0;
+        $empty = $value === '';
     }
 }

StrvalToTypeCastRector

Change strval() to faster and readable (string) $value

 class SomeClass
 {
     public function run($value)
     {
-        return strval($value);
+        return (string) $value;
     }
 }

SwitchNegatedTernaryRector

Switch negated ternary condition rector

 class SomeClass
 {
     public function run(bool $upper, string $name)
     {
-        return ! $upper
-            ? $name
-            : strtoupper($name);
+        return $upper
+            ? strtoupper($name)
+            : $name;
     }
 }

TernaryEmptyArrayArrayDimFetchToCoalesceRector

Change ternary empty on array property with array dim fetch to coalesce operator

 final class SomeClass
 {
     private array $items = [];

     public function run()
     {
-        return ! empty($this->items) ? $this->items[0] : 'default';
+        return $this->items[0] ?? 'default';
     }
 }

TernaryFalseExpressionToIfRector

Change ternary with false to if and explicit call

 final class SomeClass
 {
     public function run($value, $someMethod)
     {
-        $value ? $someMethod->call($value) : false;
+        if ($value) {
+            $someMethod->call($value);
+        }
     }
 }

ThrowWithPreviousExceptionRector

When throwing into a catch block, checks that the previous exception is passed to the new throw clause

 class SomeClass
 {
     public function run()
     {
         try {
             $someCode = 1;
         } catch (Throwable $throwable) {
-            throw new AnotherException('ups');
+            throw new AnotherException('ups', $throwable->getCode(), $throwable);
         }
     }
 }

UnnecessaryTernaryExpressionRector

Remove unnecessary ternary expressions

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

UnusedForeachValueToArrayKeysRector

Change foreach with unused $value but only $key, to array_keys()

 class SomeClass
 {
     public function run()
     {
         $items = [];
-        foreach ($values as $key => $value) {
+        foreach (array_keys($values) as $key) {
             $items[$key] = null;
         }
     }
 }

UnwrapSprintfOneArgumentRector

unwrap sprintf() with one argument

-echo sprintf('value');
+echo 'value';

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;
     }
 }

CodingStyle

AddArrayDefaultToArrayPropertyRector

Adds array default value to property to prevent foreach over null error

 class SomeClass
 {
     /**
      * @var int[]
      */
-    private $values;
+    private $values = [];

     public function isEmpty()
     {
-        return $this->values === null;
+        return $this->values === [];
     }
 }

AddFalseDefaultToBoolPropertyRector

Add false default to bool properties, to prevent null compare errors

 class SomeClass
 {
     /**
      * @var bool
      */
-    private $isDisabled;
+    private $isDisabled = false;
 }

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';
 }

CallUserFuncArrayToVariadicRector

Replace call_user_func_array() with variadic

 class SomeClass
 {
     public function run()
     {
-        call_user_func_array('some_function', $items);
+        some_function(...$items);
     }
 }

CallUserFuncToMethodCallRector

Refactor call_user_func() on known class method to a method call

 final class SomeClass
 {
     public function run()
     {
-        $result = \call_user_func([$this->property, 'method'], $args);
+        $result = $this->property->method($args);
     }
 }

CatchExceptionNameMatchingTypeRector

Type and name of catch exception should match

 class SomeClass
 {
     public function run()
     {
         try {
             // ...
-        } catch (SomeException $typoException) {
-            $typoException->getMessage();
+        } catch (SomeException $someException) {
+            $someException->getMessage();
         }
     }
 }

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);
     }
 }

ConsistentPregDelimiterRector

Replace PREG delimiter with configured one

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(ConsistentPregDelimiterRector::class, [
        ConsistentPregDelimiterRector::DELIMITER => '#',
    ]);
};

 class SomeClass
 {
     public function run()
     {
-        preg_match('~value~', $value);
-        preg_match_all('~value~im', $value);
+        preg_match('#value#', $value);
+        preg_match_all('#value#im', $value);
     }
 }

CountArrayToEmptyArrayComparisonRector

Change count array comparison to empty array comparison to improve performance

-count($array) === 0;
-count($array) > 0;
-! count($array);
+$array === [];
+$array !== [];
+$array === [];

DataProviderArrayItemsNewlinedRector

Change data provider in PHPUnit test case to newline per item

 use PHPUnit\Framework\TestCase;

 final class ImageBinaryTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function testGetBytesSize(string $content, int $number): void
     {
         // ...
     }

     public static function provideData(): array
     {
-        return [['content', 8], ['content123', 11]];
+        return [
+            ['content', 8],
+            ['content123', 11]
+        ];
     }
 }

EncapsedStringsToSprintfRector

Convert enscaped {$string} to more readable sprintf

 final class SomeClass
 {
     public function run(string $format)
     {
-        return "Unsupported format {$format}";
+        return sprintf('Unsupported format %s', $format);
     }
 }

FuncGetArgsToVariadicParamRector

Refactor func_get_args() in to a variadic param

-function run()
+function run(...$args)
 {
-    $args = \func_get_args();
 }

InlineSimplePropertyAnnotationRector

Inline simple @var annotations (or other annotations) when they are the only thing in the phpdoc

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\CodingStyle\Rector\Property\InlineSimplePropertyAnnotationRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(InlineSimplePropertyAnnotationRector::class, [
        'var',
        'phpstan-var',
    ]);
};

 final class SomeClass
 {
-    /**
-     * @phpstan-var string
-     */
+    /** @phpstan-var string */
     private const TEXT = 'text';

-    /**
-     * @var DateTime[]
-     */
+    /** @var DateTime[] */
     private ?array $dateTimes;
 }

MakeInheritedMethodVisibilitySameAsParentRector

Make method visibility same as parent one

 class ChildClass extends ParentClass
 {
-    public function run()
+    protected function run()
     {
     }
 }

 class ParentClass
 {
     protected function run()
     {
     }
 }

NewlineAfterStatementRector

Add new line after statements to tidify code

 class SomeClass
 {
     public function first()
     {
     }
+
     public function second()
     {
     }
 }

NewlineBeforeNewAssignSetRector

Add extra space before new assign set

 final class SomeClass
 {
     public function run()
     {
         $value = new Value;
         $value->setValue(5);
+
         $value2 = new Value;
         $value2->setValue(1);
     }
 }

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) {
 }

NullifyUnionNullableRector

Changes already typed Type|null to ?Type

 final class SomeClass
 {

-    private null|stdClass $property;
+    private ?stdClass $property;
 }

OrderAttributesRector

Order attributes by desired names

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\CodingStyle\Rector\ClassMethod\OrderAttributesRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(OrderAttributesRector::class, [
        'First',
        'Second',
    ]);
};

+#[First]
 #[Second]
-#[First]
 class Someclass
 {
 }

<?php

declare(strict_types=1);

use Rector\CodingStyle\Rector\ClassMethod\OrderAttributesRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(OrderAttributesRector::class, [
        'alphabetically',
    ]);
};

+#[AAttribute]
 #[BAttribute]
-#[AAttribute]
 class Someclass
 {
 }

PostIncDecToPreIncDecRector

Use ++$value or --$value instead of $value++ or $value--

 class SomeClass
 {
     public function run($value = 1)
     {
-        $value++; echo $value;
-        $value--; echo $value;
+        ++$value; echo $value;
+        --$value; echo $value;
     }
 }

PreferThisOrSelfMethodCallRector

Changes $this->... and static:: to self:: or vise versa for given types

🔧 configure it!

<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;
use Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(PreferThisOrSelfMethodCallRector::class, [
        TestCase::class => 'prefer_self',
    ]);
};

 use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
     public function run()
     {
-        $this->assertEquals('a', 'a');
+        self::assertEquals('a', 'a');
     }
 }

RemoveDoubleUnderscoreInMethodNameRector

Non-magic PHP object methods cannot start with "__"

 class SomeClass
 {
-    public function __getName($anotherObject)
+    public function getName($anotherObject)
     {
-        $anotherObject->__getSurname();
+        $anotherObject->getSurname();
     }
 }

RemoveFinalFromConstRector

Remove final from constants in classes defined as final

 final class SomeClass
 {
-    final public const NAME = 'value';
+    public const NAME = 'value';
 }

ReturnArrayClassMethodToYieldRector

Turns array return to yield return in specific type and method

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector;
use Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(ReturnArrayClassMethodToYieldRector::class, [
        new ReturnArrayClassMethodToYield('PHPUnit\Framework\TestCase', '*provide*'),
    ]);
};

 use PHPUnit\Framework\TestCase;

 final class SomeTest implements TestCase
 {
     public static function provideData()
     {
-        return [['some text']];
+        yield ['some text'];
     }
 }

SeparateMultiUseImportsRector

Split multi use imports and trait statements to standalone lines

-use A, B;
+use A;
+use B;

 class SomeClass
 {
-    use SomeTrait, AnotherTrait;
+    use SomeTrait;
+    use AnotherTrait;
 }

SplitDoubleAssignRector

Split multiple inline assigns to each own lines default value, to prevent undefined array issues

 class SomeClass
 {
     public function run()
     {
-        $one = $two = 1;
+        $one = 1;
+        $two = 1;
     }
 }

SplitGroupedClassConstantsRector

Separate class constant to own lines

 class SomeClass
 {
-    const HI = true, HELLO = 'true';
+    const HI = true;
+    const HELLO = 'true';
 }

SplitGroupedPropertiesRector

Separate grouped properties to own lines

 class SomeClass
 {
     /**
      * @var string
      */
-    public $isIt, $isIsThough;
+    public $isIt;
+
+    /**
+     * @var string
+     */
+    public $isIsThough;
 }

StaticArrowFunctionRector

Changes ArrowFunction to be static when possible

-fn (): string => 'test';
+static fn (): string => 'test';

StaticClosureRector

Changes Closure to be static when possible

-function () {
+static function () {
     if (rand(0, 1)) {
         return 1;
     }

     return 2;
 }

StrictArraySearchRector

Makes array_search search for identical elements

-array_search($value, $items);
+array_search($value, $items, true);

SymplifyQuoteEscapeRector

Prefer quote that are not inside the string

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

TernaryConditionVariableAssignmentRector

Assign outcome of ternary condition to variable, where applicable

 function ternary($value)
 {
-    $value ? $a = 1 : $a = 0;
+    $a = $value ? 1 : 0;
 }

UnSpreadOperatorRector

Remove spread operator

 class SomeClass
 {
-    public function run(...$array)
+    public function run(array $array)
     {
     }

     public function execute(array $data)
     {
-        $this->run(...$data);
+        $this->run($data);
     }
 }

UseClassKeywordForClassNameResolutionRector

Use class keyword for class name resolution in string instead of hardcoded string reference

-$value = 'App\SomeClass::someMethod()';
+$value = \App\SomeClass::class . '::someMethod()';

UseIncrementAssignRector

Use ++ increment instead of $var += 1

 class SomeClass
 {
     public function run()
     {
-        $style += 1;
+        ++$style;
     }
 }

VarConstantCommentRector

Constant should have a @var comment with type

 class SomeClass
 {
+    /**
+     * @var string
+     */
     const HI = 'hi';
 }

VersionCompareFuncCallToConstantRector

Changes use of call to version compare function to use of PHP version constant

 class SomeClass
 {
     public function run()
     {
-        version_compare(PHP_VERSION, '5.3.0', '<');
+        PHP_VERSION_ID < 50300;
     }
 }

WrapEncapsedVariableInCurlyBracesRector

Wrap encapsed variables in curly braces

 function run($world)
 {
-    echo "Hello $world!";
+    echo "Hello {$world}!";
 }

Compatibility

AttributeCompatibleAnnotationRector

Change annotation to attribute compatible form, see https://tomasvotruba.com/blog/doctrine-annotations-and-attributes-living-together-in-peace/

-use Doctrine\Common\Annotations\Annotation\Required;
+use Doctrine\Common\Annotations\Annotation\NamedArgumentConstructor;

 /**
  * @annotation
+ * @NamedArgumentConstructor
  */
 class SomeAnnotation
 {
     /**
-     * @var string[]
-     * @Required()
+     * @param string[] $enum
      */
-    public array $enum;
+    public function __construct(
+        public array $enum
+    ) {
+    }
 }

DeadCode

RecastingRemovalRector

Removes recasting of the same type

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

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

RemoveAlwaysTrueIfConditionRector

Remove if condition that is always true

 final class SomeClass
 {
     public function go()
     {
-        if (1 === 1) {
-            return 'yes';
-        }
+        return 'yes';

         return 'no';
     }
 }

RemoveAndTrueRector

Remove and true that has no added value

 class SomeClass
 {
     public function run()
     {
-        return true && 5 === 1;
+        return 5 === 1;
     }
 }

RemoveAnnotationRector

Remove annotation by names

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\ClassLike\RemoveAnnotationRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(RemoveAnnotationRector::class, [
        'method',
    ]);
};

-/**
- * @method getName()
- */
 final class SomeClass
 {
 }

RemoveConcatAutocastRector

Remove (string) casting when it comes to concat, that does this by default

 class SomeConcatingClass
 {
     public function run($value)
     {
-        return 'hi ' . (string) $value;
+        return 'hi ' . $value;
     }
 }

RemoveDeadConditionAboveReturnRector

Remove dead condition above return

 final class SomeClass
 {
     public function go()
     {
-        if (1 === 1) {
-            return 'yes';
-        }
-
         return 'yes';
     }
 }

RemoveDeadContinueRector

Remove useless continue at the end of loops

 while ($i < 10) {
     ++$i;
-    continue;
 }

RemoveDeadIfForeachForRector

Remove if, foreach and for that does not do anything

 class SomeClass
 {
     public function run($someObject)
     {
         $value = 5;
-        if ($value) {
-        }
-
         if ($someObject->run()) {
-        }
-
-        foreach ($values as $value) {
         }

         return $value;
     }
 }

RemoveDeadInstanceOfRector

Remove dead instanceof check on type hinted variable

 final class SomeClass
 {
     public function go(stdClass $stdClass)
     {
-        if (! $stdClass instanceof stdClass) {
-            return false;
-        }
-
         return true;
     }
 }

RemoveDeadLoopRector

Remove loop with no body

 class SomeClass
 {
     public function run($values)
     {
-        for ($i=1; $i<count($values); ++$i) {
-        }
     }
 }

RemoveDeadReturnRector

Remove last return in the functions, since does not do anything

 class SomeClass
 {
     public function run()
     {
         $shallWeDoThis = true;

         if ($shallWeDoThis) {
             return;
         }
-
-        return;
     }
 }

RemoveDeadStmtRector

Removes dead code statements

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

RemoveDeadTryCatchRector

Remove dead try/catch

 class SomeClass
 {
     public function run()
     {
-        try {
-            // some code
-        }
-        catch (Throwable $throwable) {
-            throw $throwable;
-        }
     }
 }

RemoveDeadZeroAndOneOperationRector

Remove operation with 1 and 0, that have no effect on the value

 class SomeClass
 {
     public function run()
     {
-        $value = 5 * 1;
-        $value = 5 + 0;
+        $value = 5;
+        $value = 5;
     }
 }

RemoveDelegatingParentCallRector

Removed dead parent call, that does not change anything

 class SomeClass
 {
-    public function prettyPrint(array $stmts): string
-    {
-        return parent::prettyPrint($stmts);
-    }
 }

RemoveDoubleAssignRector

Simplify useless double assigns

-$value = 1;
 $value = 1;

RemoveDuplicatedArrayKeyRector

Remove duplicated key in defined arrays.

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

RemoveDuplicatedCaseInSwitchRector

2 following switch keys with identical will be reduced to one result

 class SomeClass
 {
     public function run()
     {
         switch ($name) {
              case 'clearHeader':
                  return $this->modifyHeader($node, 'remove');
              case 'clearAllHeaders':
-                 return $this->modifyHeader($node, 'replace');
              case 'clearRawHeaders':
                  return $this->modifyHeader($node, 'replace');
              case '...':
                  return 5;
         }
     }
 }

RemoveDuplicatedIfReturnRector

Remove duplicated if stmt with return in function/method body

 class SomeClass
 {
     public function run($value)
     {
         if ($value) {
             return true;
         }

         $value2 = 100;
-
-        if ($value) {
-            return true;
-        }
     }
 }

RemoveDuplicatedInstanceOfRector

Remove duplicated instanceof in one call

 class SomeClass
 {
-    public function run($value)
+    public function run($value): void
     {
-        $isIt = $value instanceof A || $value instanceof A;
-        $isIt = $value instanceof A && $value instanceof A;
+        $isIt = $value instanceof A;
+        $isIt = $value instanceof A;
     }
 }

RemoveEmptyClassMethodRector

Remove empty class methods not required by parents

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

RemoveEmptyMethodCallRector

Remove empty method call

 class SomeClass
 {
     public function callThis()
     {
     }
 }

-$some = new SomeClass();
-$some->callThis();
+$some = new SomeClass();

RemoveJustPropertyFetchForAssignRector

Remove assign of property, just for value assign

 class SomeClass
 {
     private $items = [];

     public function run()
     {
-        $items = $this->items;
-        $items[] = 1000;
-        $this->items = $items ;
+        $this->items[] = 1000;
     }
 }

RemoveJustPropertyFetchRector

Inline property fetch assign to a variable, that has no added value

 final class SomeClass
 {
     private $name;

     public function run()
     {
-        $name = $this->name;
-
-        return $name;
+        return $this->name;
     }
 }

RemoveJustVariableAssignRector

Remove variable just to assign value or return value

 final class SomeClass
 {
     public function run()
     {
-        $result = 100;
-
-        $this->temporaryValue = $result;
+        $this->temporaryValue = 100;
     }
 }

RemoveLastReturnRector

Remove very last return that has no meaning

 function some_function($value)
 {
     if ($value === 1000) {
         return;
     }

     if ($value) {
-        return;
     }
 }

RemoveNonExistingVarAnnotationRector

Removes non-existing @var annotations above the code

 class SomeClass
 {
     public function get()
     {
-        /** @var Training[] $trainings */
         return $this->getData();
     }
 }

RemoveNullPropertyInitializationRector

Remove initialization with null value from property declarations

 class SunshineCommand extends ParentClassWithNewConstructor
 {
-    private $myVar = null;
+    private $myVar;
 }

RemoveParentCallWithoutParentRector

Remove unused parent call with no parent class

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

RemovePhpVersionIdCheckRector

Remove unneeded PHP_VERSION_ID conditional checks

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\ConstFetch\RemovePhpVersionIdCheckRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(RemovePhpVersionIdCheckRector::class, [
        80000,
    ]);
};

 class SomeClass
 {
     public function run()
     {
-        if (PHP_VERSION_ID < 80000) {
-            return;
-        }
-
         echo 'do something';
     }
 }

RemoveUnreachableStatementRector

Remove unreachable statements

 class SomeClass
 {
     public function run()
     {
         return 5;
-
-        $removeMe = 10;
     }
 }

RemoveUnusedConstructorParamRector

Remove unused parameter in constructor

 final class SomeClass
 {
     private $hey;

-    public function __construct($hey, $man)
+    public function __construct($hey)
     {
         $this->hey = $hey;
     }
 }

RemoveUnusedForeachKeyRector

Remove unused key in foreach

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

RemoveUnusedNonEmptyArrayBeforeForeachRector

Remove unused if check to non-empty array before foreach of the array

 class SomeClass
 {
     public function run()
     {
         $values = [];
-        if ($values !== []) {
-            foreach ($values as $value) {
-                echo $value;
-            }
+        foreach ($values as $value) {
+            echo $value;
         }
     }
 }

RemoveUnusedPrivateClassConstantRector

Remove unused class constants

 class SomeClass
 {
-    private const SOME_CONST = 'dead';
-
     public function run()
     {
     }
 }

RemoveUnusedPrivateMethodParameterRector

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

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

RemoveUnusedPrivateMethodRector

Remove unused private method

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

RemoveUnusedPrivatePropertyRector

Remove unused private properties

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(RemoveUnusedPrivatePropertyRector::class, [
        RemoveUnusedPrivatePropertyRector::REMOVE_ASSIGN_SIDE_EFFECT => true,
    ]);
};

 class SomeClass
 {
-    private $property;
 }

RemoveUnusedPromotedPropertyRector

Remove unused promoted property

 class SomeClass
 {
     public function __construct(
-        private $someUnusedDependency,
         private $usedDependency
     ) {
     }

     public function getUsedDependency()
     {
         return $this->usedDependency;
     }
 }

RemoveUnusedVariableAssignRector

Remove unused assigns to variables

 class SomeClass
 {
     public function run()
     {
-        $value = 5;
     }
 }

RemoveUselessParamTagRector

Remove @param docblock with same type as parameter type

 class SomeClass
 {
     /**
-     * @param string $a
      * @param string $b description
      */
     public function foo(string $a, string $b)
     {
     }
 }

RemoveUselessReturnTagRector

Remove @return docblock with same type as defined in PHP

 use stdClass;

 class SomeClass
 {
-    /**
-     * @return stdClass
-     */
     public function foo(): stdClass
     {
     }
 }

RemoveUselessVarTagRector

Remove unused @var annotation for properties

 final class SomeClass
 {
-    /**
-     * @var string
-     */
     public string $name = 'name';
 }

SimplifyIfElseWithSameContentRector

Remove if/else if they have same content

 class SomeClass
 {
     public function run()
     {
-        if (true) {
-            return 1;
-        } else {
-            return 1;
-        }
+        return 1;
     }
 }

SimplifyMirrorAssignRector

Removes unneeded $value = $value assigns

 function run() {
-    $result = $result;
 }

TargetRemoveClassMethodRector

Remove defined class method

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\Class_\TargetRemoveClassMethodRector;
use Rector\DeadCode\ValueObject\TargetRemoveClassMethod;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(TargetRemoveClassMethodRector::class, [
        new TargetRemoveClassMethod('SomeClass', 'run'),
    ]);
};

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

TernaryToBooleanOrFalseToBooleanAndRector

Change ternary of bool : false to && bool

 class SomeClass
 {
     public function go()
     {
-        return $value ? $this->getBool() : false;
+        return $value && $this->getBool();
     }

     private function getBool(): bool
     {
         return (bool) 5;
     }
 }

UnwrapFutureCompatibleIfPhpVersionRector

Remove php version checks if they are passed

 // current PHP: 7.2
-if (version_compare(PHP_VERSION, '7.2', '<')) {
-    return 'is PHP 7.1-';
-} else {
-    return 'is PHP 7.2+';
-}
+return 'is PHP 7.2+';

DependencyInjection

ActionInjectionToConstructorInjectionRector

Turns action injection in Controllers to constructor injection

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

AddMethodParentCallRector

Add method parent call, in case new parent method is added

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DependencyInjection\Rector\ClassMethod\AddMethodParentCallRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(AddMethodParentCallRector::class, [
        'ParentClassWithNewConstructor' => '__construct',
    ]);
};

 class SunshineCommand extends ParentClassWithNewConstructor
 {
     public function __construct()
     {
         $value = 5;
+
+        parent::__construct();
     }
 }

EarlyReturn

ChangeAndIfToEarlyReturnRector

Changes if && to early return

 class SomeClass
 {
     public function canDrive(Car $car)
     {
-        if ($car->hasWheels && $car->hasFuel) {
-            return true;
+        if (! $car->hasWheels) {
+            return false;
         }

-        return false;
+        if (! $car->hasFuel) {
+            return false;
+        }
+
+        return true;
     }
 }

ChangeIfElseValueAssignToEarlyReturnRector

Change if/else value to early return

 class SomeClass
 {
     public function run()
     {
         if ($this->hasDocBlock($tokens, $index)) {
-            $docToken = $tokens[$this->getDocBlockIndex($tokens, $index)];
-        } else {
-            $docToken = null;
+            return $tokens[$this->getDocBlockIndex($tokens, $index)];
         }
-
-        return $docToken;
+        return null;
     }
 }

ChangeNestedForeachIfsToEarlyContinueRector

Change nested ifs to foreach with continue

 class SomeClass
 {
     public function run()
     {
         $items = [];

         foreach ($values as $value) {
-            if ($value === 5) {
-                if ($value2 === 10) {
-                    $items[] = 'maybe';
-                }
+            if ($value !== 5) {
+                continue;
             }
+            if ($value2 !== 10) {
+                continue;
+            }
+
+            $items[] = 'maybe';
         }
     }
 }

ChangeNestedIfsToEarlyReturnRector

Change nested ifs to early return

 class SomeClass
 {
     public function run()
     {
-        if ($value === 5) {
-            if ($value2 === 10) {
-                return 'yes';
-            }
+        if ($value !== 5) {
+            return 'no';
+        }
+
+        if ($value2 === 10) {
+            return 'yes';
         }

         return 'no';
     }
 }

ChangeOrIfContinueToMultiContinueRector

Changes if || to early return

 class SomeClass
 {
     public function canDrive(Car $newCar)
     {
         foreach ($cars as $car) {
-            if ($car->hasWheels() || $car->hasFuel()) {
+            if ($car->hasWheels()) {
+                continue;
+            }
+            if ($car->hasFuel()) {
                 continue;
             }

             $car->setWheel($newCar->wheel);
             $car->setFuel($newCar->fuel);
         }
     }
 }

ChangeOrIfReturnToEarlyReturnRector

Changes if || with return to early return

 class SomeClass
 {
     public function run($a, $b)
     {
-        if ($a || $b) {
+        if ($a) {
+            return null;
+        }
+        if ($b) {
             return null;
         }

         return 'another';
     }
 }

PreparedValueToEarlyReturnRector

Return early prepared value in ifs

 class SomeClass
 {
     public function run()
     {
-        $var = null;
-
         if (rand(0,1)) {
-            $var = 1;
+            return 1;
         }

         if (rand(0,1)) {
-            $var = 2;
+            return 2;
         }

-        return $var;
+        return null;
     }
 }

RemoveAlwaysElseRector

Split if statement, when if condition always break execution flow

 class SomeClass
 {
     public function run($value)
     {
         if ($value) {
             throw new \InvalidStateException;
-        } else {
-            return 10;
         }
+
+        return 10;
     }
 }

ReturnBinaryAndToEarlyReturnRector

Changes Single return of && to early returns

 class SomeClass
 {
     public function accept()
     {
-        return $this->something() && $this->somethingelse();
+        if (! $this->something()) {
+            return false;
+        }
+
+        return (bool) $this->somethingelse();
     }
 }

ReturnBinaryOrToEarlyReturnRector

Changes Single return of || to early returns

 class SomeClass
 {
     public function accept()
     {
-        return $this->something() || $this->somethingElse();
+        if ($this->something()) {
+            return true;
+        }
+        return (bool) $this->somethingElse();
     }
 }

ReturnEarlyIfVariableRector

Replace if conditioned variable override with direct return

 final class SomeClass
 {
     public function run($value)
     {
         if ($value === 50) {
-            $value = 100;
+            return 100;
         }

         return $value;
     }
 }

MysqlToMysqli

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

Converts more complex mysql functions to mysqli

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

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);
     }
 }

MysqlQueryMysqlErrorWithLinkRector

Add mysql_query and mysql_error with connection

 class SomeClass
 {
     public function run()
     {
         $conn = mysqli_connect('host', 'user', 'pass');

-        mysql_error();
+        mysqli_error($conn);
         $sql = 'SELECT';

-        return mysql_query($sql);
+        return mysqli_query($conn, $sql);
     }
 }

Naming

RenameForeachValueVariableToMatchExprVariableRector

Renames value variable name in foreach loop to match expression variable

 class SomeClass
 {
     public function run()
     {
         $array = [];
-        foreach ($variables as $property) {
-            $array[] = $property;
+        foreach ($variables as $variable) {
+            $array[] = $variable;
         }
     }
 }

RenameForeachValueVariableToMatchMethodCallReturnTypeRector

Renames value variable name in foreach loop to match method type

 class SomeClass
 {
     public function run()
     {
         $array = [];
-        foreach ($object->getMethods() as $property) {
-            $array[] = $property;
+        foreach ($object->getMethods() as $method) {
+            $array[] = $method;
         }
     }
 }

RenameParamToMatchTypeRector

Rename param to match ClassType

 final class SomeClass
 {
-    public function run(Apple $pie)
+    public function run(Apple $apple)
     {
-        $food = $pie;
+        $food = $apple;
     }
 }

RenamePropertyToMatchTypeRector

Rename property and method param to match its type

 class SomeClass
 {
     /**
      * @var EntityManager
      */
-    private $eventManager;
+    private $entityManager;

-    public function __construct(EntityManager $eventManager)
+    public function __construct(EntityManager $entityManager)
     {
-        $this->eventManager = $eventManager;
+        $this->entityManager = $entityManager;
     }
 }

RenameVariableToMatchMethodCallReturnTypeRector

Rename variable to match method return type

 class SomeClass
 {
 public function run()
 {
-    $a = $this->getRunner();
+    $runner = $this->getRunner();
 }

 public function getRunner(): Runner
 {
     return new Runner();
 }
 }

RenameVariableToMatchNewTypeRector

Rename variable to match new ClassType

 final class SomeClass
 {
     public function run()
     {
-        $search = new DreamSearch();
-        $search->advance();
+        $dreamSearch = new DreamSearch();
+        $dreamSearch->advance();
     }
 }

PSR4

MultipleClassFileToPsr4ClassesRector

Change multiple 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
 {
 }

NormalizeNamespaceByPSR4ComposerAutoloadRector

Adds namespace to namespace-less files or correct namespace to match PSR-4 in composer.json autoload section. Run with combination with "Rector\PSR4\Rector\Namespace_\MultipleClassFileToPsr4ClassesRector"

{
    "autoload": {
        "psr-4": {
            "App\\CustomNamespace\\": "src"
        }
    }
}

 // src/SomeClass.php

+namespace App\CustomNamespace;
+
 class SomeClass
 {
 }

Php52

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;
     }
 }

VarToPublicPropertyRector

Change property modifier from var to public

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

Php53

DirNameFileConstantToDirConstantRector

Convert dirname(FILE) to DIR

 class SomeClass
 {
     public function run()
     {
-        return dirname(__FILE__);
+        return __DIR__;
     }
 }

ReplaceHttpServerVarsByServerRector

Rename old $HTTP_* variable names to new replacements

-$serverVars = $HTTP_SERVER_VARS;
+$serverVars = $_SERVER;

TernaryToElvisRector

Use ?: instead of ?, where useful

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

Php54

LongArrayToShortArrayRector

Long array to short array

 class SomeClass
 {
     public function run()
     {
-        return array();
+        return [];
     }
 }

RemoveReferenceFromCallRector

Remove & from function and method calls

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

RemoveZeroBreakContinueRector

Remove 0 from break and continue

 class SomeClass
 {
     public function run($random)
     {
-        continue 0;
-        break 0;
+        continue;
+        break;

         $five = 5;
-        continue $five;
+        continue 5;

-        break $random;
+        break;
     }
 }

Php55

ClassConstantToSelfClassRector

Change __CLASS__ to self::class

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

GetCalledClassToSelfClassRector

Change get_called_class() to self::class on final class

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

GetCalledClassToStaticClassRector

Change get_called_class() to static::class on non-final class

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

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);
     }
 }

StringClassNameToClassConstantRector

Replace string class names by ::class constant

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php55\Rector\String_\StringClassNameToClassConstantRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(StringClassNameToClassConstantRector::class, [
        'ClassName',
        'AnotherClassName',
    ]);
};

 class AnotherClass
 {
 }

 class SomeClass
 {
     public function run()
     {
-        return 'AnotherClass';
+        return \AnotherClass::class;
     }
 }

Php56

AddDefaultValueForUndefinedVariableRector

Adds default value for undefined variable

 class SomeClass
 {
     public function run()
     {
+        $a = null;
         if (rand(0, 1)) {
             $a = 5;
         }
         echo $a;
     }
 }

PowToExpRector

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

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

Php70

BreakNotInLoopOrSwitchToReturnRector

Convert break outside for/foreach/switch context to return

 class SomeClass
 {
     public function run()
     {
         if ($isphp5)
             return 1;
         else
             return 2;
-        break;
+        return;
     }
 }

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");

EmptyListRector

list() cannot be empty

-'list() = $values;'
+'list($unusedGenerated) = $values;'

EregToPregMatchRector

Changes ereg*() to preg*() calls

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

ExceptionHandlerTypehintRector

Change typehint from Exception to Throwable.

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

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];
         });
     }
 }

ListSplitStringRector

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

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

ListSwapArrayOrderRector

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

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

MultiDirnameRector

Changes multiple dirname() calls to one with nesting level

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

Php4ConstructorRector

Changes PHP 4 style constructor to __construct.

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

RandomFunctionRector

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

-rand();
+mt_rand();

ReduceMultipleDefaultSwitchRector

Remove first default switch, that is ignored

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

RenameMktimeWithoutArgsToTimeRector

Renames mktime() without arguments to time()

 class SomeClass
 {
     public function run()
     {
         $time = mktime(1, 2, 3);
-        $nextTime = mktime();
+        $nextTime = time();
     }
 }

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();
     }
 }

TernaryToNullCoalescingRector

Changes unneeded null check to ?? operator

-$value === null ? 10 : $value;
+$value ?? 10;

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

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;
 }

ThisCallOnStaticMethodToStaticCallRector

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

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

     public static function eat()
     {
     }
 }

WrapVariableVariableNameInCurlyBracesRector

Ensure variable variables are wrapped in curly braces

 function run($foo)
 {
-    global $$foo->bar;
+    global ${$foo->bar};
 }

Php71

AssignArrayToStringRector

String cannot be turned into array by assignment anymore

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

BinaryOpBetweenNumberAndStringRector

Change binary operation between some number + string to PHP 7.1 compatible version

 class SomeClass
 {
     public function run()
     {
-        $value = 5 + '';
-        $value = 5.0 + 'hi';
+        $value = 5 + 0;
+        $value = 5.0 + 0;
     }
 }

CountOnNullRector

Changes count() on null to safe ternary check

 $values = null;
-$count = count($values);
+$count = $values === null ? 0 : count($values);

IsIterableRector

Changes is_array + Traversable check to is_iterable

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

ListToArrayDestructRector

Change list() to array destruct

 class SomeClass
 {
     public function run()
     {
-        list($id1, $name1) = $data;
+        [$id1, $name1] = $data;

-        foreach ($data as list($id, $name)) {
+        foreach ($data as [$id, $name]) {
         }
     }
 }

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;
 }

PublicConstantVisibilityRector

Add explicit public constant visibility.

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

RemoveExtraParametersRector

Remove extra parameters

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

ReservedObjectRector

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

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php71\Rector\Name\ReservedObjectRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(ReservedObjectRector::class, [
        'ReservedObject' => 'SmartObject',
        'Object' => 'AnotherSmartObject',
    ]);
};

-class Object
+class SmartObject
 {
 }

Php72

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]);
+        };
     }
 }

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;
     }
 }

IsObjectOnIncompleteClassRector

Incomplete class returns inverted bool on is_object()

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

ListEachRector

each() function is deprecated, use key() and current() instead

-list($key, $callback) = each($callbacks);
+$key = key($callbacks);
+$callback = current($callbacks);
+next($callbacks);

ParseStrWithResultArgumentRector

Use $result argument in parse_str() function

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

ReplaceEachAssignmentWithKeyCurrentRector

Replace each() assign outside loop

 $array = ['b' => 1, 'a' => 2];
-$eachedArray = each($array);
+$eachedArray[1] = current($array);
+$eachedArray['value'] = current($array);
+$eachedArray[0] = key($array);
+$eachedArray['key'] = key($array);
+next($array);

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');
     }
 }

StringsAssertNakedRector

String asserts must be passed directly to assert()

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

UnsetCastRector

Removes (unset) cast

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

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

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) {
     // ...
 }

Php73

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);

IsCountableRector

Changes is_array + Countable check to is_countable

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

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, 512, JSON_THROW_ON_ERROR);

RegexDashEscapeRector

Escape - in some cases

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

SensitiveConstantNameRector

Changes case insensitive constants to sensitive ones.

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

SensitiveDefineRector

Changes case insensitive constants to sensitive ones.

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

SensitiveHereNowDocRector

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

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

SetCookieRector

Convert setcookie argument to PHP7.3 option array

-setcookie('name', $value, 360);
+setcookie('name', $value, ['expires' => 360]);

-setcookie('name', $name, 0, '', '', true, true);
+setcookie('name', $name, ['expires' => 0, 'path' => '', 'domain' => '', 'secure' => true, 'httponly' => true]);

StringifyStrNeedlesRector

Makes needles explicit strings

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

Php74

AddLiteralSeparatorToNumberRector

Add "_" as thousands separator in numbers for higher or equals to limitValue config

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(AddLiteralSeparatorToNumberRector::class, [
        AddLiteralSeparatorToNumberRector::LIMIT_VALUE => 1000000,
    ]);
};

 class SomeClass
 {
     public function run()
     {
-        $int = 500000;
-        $float = 1000500.001;
+        $int = 500_000;
+        $float = 1_000_500.001;
     }
 }

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');

ArraySpreadInsteadOfArrayMergeRector

Change array_merge() to spread operator

 class SomeClass
 {
     public function run($iter1, $iter2)
     {
-        $values = array_merge(iterator_to_array($iter1), iterator_to_array($iter2));
+        $values = [...$iter1, ...$iter2];

         // Or to generalize to all iterables
-        $anotherValues = array_merge(
-            is_array($iter1) ? $iter1 : iterator_to_array($iter1),
-            is_array($iter2) ? $iter2 : iterator_to_array($iter2)
-        );
+        $anotherValues = [...$iter1, ...$iter2];
     }
 }

ChangeReflectionTypeToStringToGetNameRector

Change string calls on ReflectionType

 class SomeClass
 {
     public function go(ReflectionFunction $reflectionFunction)
     {
         $parameterReflection = $reflectionFunction->getParameters()[0];

-        $paramType = (string) $parameterReflection->getType();
+        $paramType = (string) ($parameterReflection->getType() ? $parameterReflection->getType()->getName() : null);

-        $stringValue = 'hey' . $reflectionFunction->getReturnType();
+        $stringValue = 'hey' . ($reflectionFunction->getReturnType() ? $reflectionFunction->getReturnType()->getName() : null);

         // keep
         return $reflectionFunction->getReturnType();
     }
 }

ClosureToArrowFunctionRector

Change closure to arrow function

 class SomeClass
 {
     public function run($meetups)
     {
-        return array_filter($meetups, function (Meetup $meetup) {
-            return is_object($meetup);
-        });
+        return array_filter($meetups, fn(Meetup $meetup) => is_object($meetup));
     }
 }

CurlyToSquareBracketArrayStringRector

Change curly based array and string to square bracket

 $string = 'test';
-echo $string{0};
+echo $string[0];
 $array = ['test'];
-echo $array{0};
+echo $array[0];

ExportToReflectionFunctionRector

Change export() to ReflectionFunction alternatives

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

FilterVarToAddSlashesRector

Change filter_var() with slash escaping to addslashes()

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

MbStrrposEncodingArgumentPositionRector

Change mb_strrpos() encoding argument position

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

MoneyFormatToNumberFormatRector

Change money_format() to equivalent number_format()

-$value = money_format('%i', $value);
+$roundedValue = round($value, 2, PHP_ROUND_HALF_ODD);
+$value = number_format($roundedValue, 2, '.', '');

NullCoalescingOperatorRector

Use null coalescing operator ??=

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

ParenthesizeNestedTernaryRector

Add parentheses to nested ternary

-$value = $a ? $b : $a ?: null;
+$value = ($a ? $b : $a) ?: null;

RealToFloatTypeCastRector

Change deprecated (real) to (float)

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

RestoreDefaultNullToNullableTypePropertyRector

Add null default to properties with PHP 7.4 property nullable type

 class SomeClass
 {
-    public ?string $name;
+    public ?string $name = null;
 }

Php80

AddParamBasedOnParentClassMethodRector

Add missing parameter based on parent class method

 class A
 {
     public function execute($foo)
     {
     }
 }

 class B extends A{
-    public function execute()
+    public function execute($foo)
     {
     }
 }

AnnotationToAttributeRector

Change annotation to attribute

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php80\Rector\Class_\AnnotationToAttributeRector;
use Rector\Php80\ValueObject\AnnotationToAttribute;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(AnnotationToAttributeRector::class, [
        new AnnotationToAttribute('Symfony\Component\Routing\Annotation\Route'),
    ]);
};

 use Symfony\Component\Routing\Annotation\Route;

 class SymfonyRoute
 {
-    /**
-     * @Route("/path", name="action")
-     */
+    #[Route(path: '/path', name: 'action')]
     public function action()
     {
     }
 }

ChangeSwitchToMatchRector

Change switch() to match()

-switch ($input) {
-    case Lexer::T_SELECT:
-        $statement = 'select';
-        break;
-    case Lexer::T_UPDATE:
-        $statement = 'update';
-        break;
-    default:
-        $statement = 'error';
-}
+$statement = match ($input) {
+    Lexer::T_SELECT => 'select',
+    Lexer::T_UPDATE => 'update',
+    default => 'error',
+};

ClassOnObjectRector

Change get_class($object) to faster $object::class

 class SomeClass
 {
     public function run($object)
     {
-        return get_class($object);
+        return $object::class;
     }
 }

ClassOnThisVariableObjectRector

Change $this::class to static::class or self::class depends on class modifier

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

ClassPropertyAssignToConstructorPromotionRector

Change simple property init and assign to constructor promotion

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(ClassPropertyAssignToConstructorPromotionRector::class, [
        ClassPropertyAssignToConstructorPromotionRector::INLINE_PUBLIC => false,
    ]);
};

 class SomeClass
 {
-    public float $someVariable;
-
     public function __construct(
-        float $someVariable = 0.0
+        public float $someVariable = 0.0
     ) {
-        $this->someVariable = $someVariable;
     }
 }

DoctrineAnnotationClassToAttributeRector

Refactor Doctrine @annotation annotated class to a PHP 8.0 attribute class

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php80\Rector\Class_\DoctrineAnnotationClassToAttributeRector;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(DoctrineAnnotationClassToAttributeRector::class, [
        DoctrineAnnotationClassToAttributeRector::REMOVE_ANNOTATIONS => true,
    ]);
};

-use Doctrine\Common\Annotations\Annotation\Target;
+use Attribute;

-/**
- * @Annotation
- * @Target({"METHOD"})
- */
+#[Attribute(Attribute::TARGET_METHOD)]
 class SomeAnnotation
 {
 }

FinalPrivateToPrivateVisibilityRector

Changes method visibility from final private to only private

 class SomeClass
 {
-    final private function getter() {
+    private function getter() {
         return $this;
     }
 }

GetDebugTypeRector

Change ternary type resolve to get_debug_type()

 class SomeClass
 {
     public function run($value)
     {
-        return is_object($value) ? get_class($value) : gettype($value);
+        return get_debug_type($value);
     }
 }

MixedTypeRector

Change mixed docs type to mixed typed

 class SomeClass
 {
-    /**
-     * @param mixed $param
-     */
-    public function run($param)
+    public function run(mixed $param)
     {
     }
 }

NestedAnnotationToAttributeRector

Changed nested annotations to attributes

🔧 configure it!

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php80\Rector\Property\NestedAnnotationToAttributeRector;
use Rector\Php80\ValueObject\AnnotationPropertyToAttributeClass;
use Rector\Php80\ValueObject\NestedAnnotationToAttribute;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->ruleWithConfiguration(NestedAnnotationToAttributeRector::class, [
        [
            new NestedAnnotationToAttribute([
                new AnnotationPropertyToAttributeClass('Doctrine\ORM\Mapping\JoinColumn', 'joinColumns', false),
                new AnnotationPropertyToAttributeClass('Doctrine\ORM\Mapping\InverseJoinColumn', 'inverseJoinColumns', false),
            ], 'Doctrine\ORM\Mapping\JoinTable', false),
        ],
    ]);
};

 use Doctrine\ORM\Mapping as ORM;

 class SomeEntity
 {
-    /**
-     * @ORM\JoinTable(name="join_table_name",
-     *     joinColumns={@ORM\JoinColumn(name="origin_id")},
-     *     inverseJoinColumns={@ORM\JoinColumn(name="target_id")}
-     * )
-     */
+    #[ORM\JoinTable(name: 'join_table_name')]
+    #[ORM\JoinColumn(name: 'origin_id')]
+    #[ORM\InverseJoinColumn(name: 'target_id')]
     private $collection;
 }

Php8ResourceReturnToObjectRector

Change is_resource() to instanceof Object

 class SomeClass
 {
     public function run()
     {
         $ch = curl_init();
-        is_resource($ch);
+        $ch instanceof \CurlHandle;
     }
 }

RemoveUnusedVariableInCatchRector

Remove unused variable in catch()

 final class SomeClass
 {
     public function run()
     {
         try {
-        } catch (Throwable $notUsedThrowable) {
+        } catch (Throwable) {
         }
     }
 }

SetStateToStaticRector

Adds static visibility to __set_state() methods

 class SomeClass
 {
-    public function __set_state($properties) {
+    public static function __set_state($properties) {

     }
 }

StrContainsRector

Replace strpos() !== false and strstr() with str_contains()

 class SomeClass
 {
     public function run()
     {
-        return strpos('abc', 'a') !== false;
+        return str_contains('abc', 'a');
     }
 }

StrEndsWithRector

Change helper functions to str_ends_with()

 class SomeClass
 {
     public function run()
     {
-        $isMatch = substr($haystack, -strlen($needle)) === $needle;
+        $isMatch = str_ends_with($haystack, $needle);

-        $isNotMatch = substr($haystack, -strlen($needle)) !== $needle;
+        $isNotMatch = !str_ends_with($haystack, $needle);
     }
 }

 class SomeClass
 {
     public function run()
     {
-        $isMatch = substr($haystack, -9) === 'hardcoded;
+        $isMatch = str_ends_with($haystack, 'hardcoded');

-        $isNotMatch = substr($haystack, -9) !== 'hardcoded';
+        $isNotMatch = !str_ends_with($haystack, 'hardcoded');
     }
 }

StrStartsWithRector

Change helper functions to str_starts_with()

 class SomeClass
 {
     public function run()
     {
-        $isMatch = substr($haystack, 0, strlen($needle)) === $needle;
+        $isMatch = str_starts_with($haystack, $needle);

-        $isNotMatch = substr($haystack, 0, strlen($needle)) !== $needle;
+        $isNotMatch = ! str_starts_with($haystack, $needle);
     }
 }

StringableForToStringRector

Add Stringable interface to classes with __toString() method

-class SomeClass
+class SomeClass implements Stringable
 {
-    public function __toString()
+    public function __toString(): string
     {
         return 'I can stringz';
     }
 }

TokenGetAllToObjectRector

Convert token_get_all to PhpToken::tokenize

 final class SomeClass
 {
     public function run()
     {
-        $tokens = token_get_all($code);
-        foreach ($tokens as $token) {
-            if (is_array($token)) {
-               $name = token_name($token[0]);
-               $text = $token[1];
-            } else {
-               $name = null;
-               $text = $token;
-            }
+        $tokens = \PhpToken::tokenize($code);
+        foreach ($tokens as $phpToken) {
+           $name = $phpToken->getTokenName();
+           $text = $phpToken->text;
         }
     }
 }

UnionTypesRector

Change docs types to union types, where possible (properties are covered by TypedPropertiesRector)

 class SomeClass
 {
-    /**
-     * @param array|int $number
-     * @return bool|float
-     */
-    public function go($number)
+    public function go(array|int $number): bool|float
     {
     }
 }

Php81

ConstantListClassToEnumRector

Upgrade constant list classes to full blown enum

-class Direction
+enum Direction
 {
-    public const LEFT = 'left';
+    case LEFT;

-    public const RIGHT = 'right';
+    case RIGHT;
 }

FinalizePublicClassConstantRector

Add final to constants that does not have children

 class SomeClass
 {
-    public const NAME = 'value';
+    final public const NAME = 'value';
 }

FirstClassCallableRector

Upgrade array callable to first class callable

 final class SomeClass
 {
     public function run()
     {
-        $name = [$this, 'name'];
+        $name = $this->name(...);
     }

     public function name()
     {
     }
 }

IntersectionTypesRector

Change docs to intersection types, where possible (properties are covered by TypedPropertyRector (@todo))

 final class SomeClass
 {
-    /**
-     * @param Foo&Bar $types
-     */
-    public function process($types)
+    public function process(Foo&Bar $types)
     {
     }
 }

MyCLabsClassToEnumRector

Refactor MyCLabs enum class to native Enum

-use MyCLabs\Enum\Enum;
-
-final class Action extends Enum
+enum Action : string
 {
-    private const VIEW = 'view';
-    private const EDIT = 'edit';
+    case VIEW = 'view';
+    case EDIT = 'edit';
 }

MyCLabsMethodCallToEnumConstRector

Refactor MyCLabs enum fetch to Enum const

-$name = SomeEnum::VALUE()->getKey();
+$name = SomeEnum::VALUE;

NewInInitializerRector

Replace property declaration of new state with direct new

 class SomeClass
 {
-    private Logger $logger;
-
     public function __construct(
-        ?Logger $logger = null,
+        private Logger $logger = new NullLogger,
     ) {
-        $this->logger = $logger ?? new NullLogger;
     }
 }

NullToStrictStringFuncCallArgRector

Change null to strict string defined function call args

 class SomeClass
 {
     public function run()
     {
-        preg_split("#a#", null);
+        preg_split("#a#", '');
     }
 }

Php81ResourceReturnToObjectRector

Change is_resource() to instanceof Object

 class SomeClass
 {
     public function run()
     {
         $f = finfo_open();
-        is_resource($f);
+        $f instanceof \finfo;
     }
 }

ReadOnlyPropertyRector

Decorate read-only property with readonly attribute

 class SomeClass
 {
     public function __construct(
-        private string $name
+        private readonly string $name
     ) {
     }

     public function getName()
     {
         return $this->name;
     }
 }

SpatieEnumClassToEnumRector

Refactor Spatie enum class to native Enum

-use \Spatie\Enum\Enum;
-
-/**
- * @method static self draft()
- * @method static self published()
- * @method static self archived()
- */
-class StatusEnum extends Enum
+enum StatusEnum : string
 {
+    case DRAFT = 'draft';
+    case PUBLISHED = 'published';
+    case ARCHIVED = 'archived';
 }

SpatieEnumMethodCallToEnumConstRector

Refactor Spatie enum method calls

-$value1 = SomeEnum::SOME_CONSTANT()->getValue();
-$value2 = SomeEnum::SOME_CONSTANT()->value;
-$name1 = SomeEnum::SOME_CONSTANT()->getName();
-$name2 = SomeEnum::SOME_CONSTANT()->name;
+$value1 = SomeEnum::SOME_CONSTANT->value;
+$value2 = SomeEnum::SOME_CONSTANT->value;
+$name1 = SomeEnum::SOME_CONSTANT->name;
+$name2 = SomeEnum::SOME_CONSTANT->name;

Php82

FilesystemIteratorSkipDotsRector

Prior PHP 8.2 FilesystemIterator::SKIP_DOTS was always set and could not be removed, therefore FilesystemIterator::SKIP_DOTS is added in order to keep this behaviour.

-new FilesystemIterator(__DIR__, FilesystemIterator::KEY_AS_FILENAME);
+new FilesystemIterator(__DIR__, FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::SKIP_DOTS);

ReadOnlyClassRector

Decorate read-only class with readonly attribute

-final class SomeClass
+final readonly class SomeClass
 {
     public function __construct(
-        private readonly string $name
+        private string $name
     ) {
     }
 }

Utf8DecodeEncodeToMbConvertEncodingRector

Change deprecated utf8_decode and utf8_encode to mb_convert_encoding

-utf8_decode($value);