Find the best Rector rule to solve your problem. Searching through 793 rules.

Found 140 rules:

NewMethodCallWithoutParenthesesRector

Remove parentheses on new method call with parentheses

-(new Request())->withMethod('GET')->withUri('/hello-world');
+new Request()->withMethod('GET')->withUri('/hello-world');
SETS:  PHP 8.4

AddEscapeArgumentRector

Add escape argument on CSV function calls

-str_getcsv($string, separator: ',', enclosure: '"');
+str_getcsv($string, separator: ',', enclosure: '"', escape: '\\');
SETS:  PHP 8.4

RoundingModeEnumRector

Replace rounding mode constant to RoundMode enum in round()

-round(1.5, 0, PHP_ROUND_HALF_UP);
+round(1.5, 0, RoundingMode::HalfAwayFromZero);
SETS:  PHP 8.4

ExplicitNullableParamTypeRector

Make implicit nullable param to explicit

-function foo(string $param = null) {}
+function foo(?string $param = null) {}
SETS:  PHP 8.4

ForeachToArrayAnyRector

Replace foreach with boolean assignment + break OR foreach with early return with array_any

-$found = false;
-foreach ($animals as $animal) {
-    if (str_starts_with($animal, 'c')) {
-        $found = true;
-        break;
-    }
-}
+$found = array_any($animals, fn($animal) => str_starts_with($animal, 'c'));
SETS:  PHP 8.4

ForeachToArrayFindKeyRector

Replace foreach with assignment and break with array_find_key

 $animals = ['dog', 'cat', 'cow', 'duck', 'goose'];

-$found = null;
-foreach ($animals as $idx => $animal) {
-    if (str_starts_with($animal, 'c')) {
-        $found = $idx;
-        break;
-    }
-}
+$found = array_find_key($animals, fn($animal) => str_starts_with($animal, 'c'));
SETS:  PHP 8.4

ForeachToArrayAllRector

Replace foreach with boolean assignment and break OR foreach with early return with array_all

-$found = true;
-foreach ($animals as $animal) {
-    if (!str_starts_with($animal, 'c')) {
-        $found = false;
-        break;
-    }
-}
+$found = array_all($animals, fn($animal) => str_starts_with($animal, 'c'));
SETS:  PHP 8.4

ForeachToArrayFindRector

Replace foreach with assignment and break with array_find

-$found = null;
-foreach ($animals as $animal) {
-    if (str_starts_with($animal, 'c')) {
-        $found = $animal;
-        break;
-    }
-}
+$found = array_find($animals, fn($animal) => str_starts_with($animal, 'c'));
SETS:  PHP 8.4

PropertyHookRector

Replace getter/setter with property hook

 final class Product
 {
-    private string $name;
-
-    public function getName(): string
+    public string $name
     {
-        return $this->name;
-    }
-
-    public function setName(string $name): void
-    {
-        $this->name = ucfirst($name);
+        get => $this->name;
+        set($value) => $this->name = ucfirst($value);
     }
 }

DeprecatedAnnotationToDeprecatedAttributeRector

Change @deprecated annotation to Deprecated attribute

-/**
- * @deprecated 1.0.0 Use SomeOtherFunction instead
- */
+#[\Deprecated(message: 'Use SomeOtherFunction instead', since: '1.0.0')]
 function someFunction()
 {
 }
SETS:  PHP 8.4

SetCookieRector

Convert setcookie argument to PHP7.3 option array

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

StringifyStrNeedlesRector

Make needles explicit strings

 $needle = 5;
-$fivePosition = strpos('725', $needle);
+$fivePosition = strpos('725', (string) $needle);
SETS:  PHP 7.3

RegexDashEscapeRector

Escape - in some cases

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

ArrayKeyFirstLastRector

Make use of array_key_first() and array_key_last()

-reset($items);
-$firstKey = key($items);
+$firstKey = array_key_first($items);
SETS:  PHP 7.3 Polyfills

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

SensitiveDefineRector

Change case insensitive constant definition to sensitive one

-define('FOO', 42, true);
+define('FOO', 42);
SETS:  PHP 7.3

SensitiveConstantNameRector

Change case insensitive constants to sensitive ones

 define('FOO', 42, true);
 var_dump(FOO);
-var_dump(foo);
+var_dump(FOO);
SETS:  PHP 7.3

SensitiveHereNowDocRector

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

-$value = <<<A
+$value = <<<A_WRAP
     A
-A
+A_WRAP
SETS:  PHP 7.3

IsCountableRector

Changes is_array + Countable check to is_countable

-is_array($foo) || $foo instanceof Countable;
+is_countable($foo);
SETS:  PHP 7.3 Polyfills

MyCLabsMethodCallToEnumConstRector

Refactor MyCLabs enum fetch to Enum const

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

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;
SETS:  PHP 8.1

RemoveReflectionSetAccessibleCallsRector

Remove Reflection::setAccessible() calls

 $reflectionProperty = new ReflectionProperty($object, 'property');
-$reflectionProperty->setAccessible(true);
 $value = $reflectionProperty->getValue($object);

 $reflectionMethod = new ReflectionMethod($object, 'method');
-$reflectionMethod->setAccessible(false);
 $reflectionMethod->invoke($object);
SETS:  PHP 8.1

NullToStrictStringFuncCallArgRector

Change null to strict string defined function call args

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

NullToStrictIntPregSlitFuncCallLimitArgRector

Change null to strict int defined preg_split limit arg function call argument

 class SomeClass
 {
     public function run()
     {
-        preg_split('/\s/', $output, NULL, PREG_SPLIT_NO_EMPTY)
+        preg_split('/\s/', $output, 0, PREG_SPLIT_NO_EMPTY)
     }
 }
SETS:  PHP 8.1

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;
     }
 }
SETS:  PHP 8.1

MyCLabsConstructorCallToEnumFromRector

Refactor MyCLabs Enum using constructor for instantiation

-$enum = new Enum($args);
+$enum = Enum::from($args);
SETS:  PHP 8.1

ArrayToFirstClassCallableRector

Upgrade array callable to first class callable

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

     public function name()
     {
     }
 }
SETS:  PHP 8.1

Configurable

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';
 }
SETS:  PHP 8.1

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';
 }
SETS:  PHP 8.1

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;
     }
 }
SETS:  PHP 8.1

DynamicClassConstFetchRector

constant(Example::class . '::' . $constName) to dynamic class const fetch Example::{$constName}

-constant(Example::class . '::' . $constName);
+Example::{$constName};
SETS:  PHP 8.3

CombineHostPortLdapUriRector

Combine separated host and port on ldap_connect() args

-ldap_connect('ldap://ldap.example.com', 389);
+ldap_connect('ldap://ldap.example.com:389');
SETS:  PHP 8.3

RemoveGetClassGetParentClassNoArgsRector

Replace calls to get_class() and get_parent_class() without arguments with self::class and parent::class

 class Example extends StdClass {
     public function whoAreYou() {
-        return get_class() . ' daughter of ' . get_parent_class();
+        return self::class . ' daughter of ' . parent::class;
     }
 }
SETS:  PHP 8.3

JsonValidateRector

Replace json_decode($json, true) !== null && json_last_error() === JSON_ERROR_NONE with json_validate()

-if (json_decode($json, true) !== null && json_last_error() === JSON_ERROR_NONE) {
+if (json_validate($json)) {
 }
SETS:  PHP 8.3

AddTypeToConstRector

Add type to constants based on their value

 final class SomeClass
 {
-    public const TYPE = 'some_type';
+    public const string TYPE = 'some_type';
 }
SETS:  PHP 8.3

ReadOnlyAnonymousClassRector

Decorate read-only anonymous class with readonly attribute

-new class
+new readonly class
 {
     public function __construct(
-        private readonly string $name
+        private string $name
     ) {
     }
 };
SETS:  PHP 8.3

Configurable

AddOverrideAttributeToOverriddenMethodsRector

Add override attribute to overridden methods

 class ParentClass
 {
     public function foo()
     {
         echo 'default';
     }
 }

 final class ChildClass extends ParentClass
 {
+    #[\Override]
     public function foo()
     {
         echo 'override default';
     }
 }
SETS:  PHP 8.3

WhileEachToForeachRector

Use foreach() instead of deprecated each()

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

StringsAssertNakedRector

String asserts must be passed directly to assert()

 function nakedAssert()
 {
-    assert('true === true');
-    assert("true === true");
+    assert(true === true);
+    assert(true === true);
 }
SETS:  PHP 7.2

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');
     }
 }
SETS:  PHP 7.2

ParseStrWithResultArgumentRector

Use $result argument in parse_str() function

-parse_str($this->query);
-$data = get_defined_vars();
+parse_str($this->query, $result);
+$data = $result;
SETS:  PHP 7.2

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]);
+        };
     }
 }
SETS:  PHP 7.2

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;
     }
 }
SETS:  PHP 7.2

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);
SETS:  PHP 7.2

ListEachRector

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

-list($key, $callback) = each($callbacks);
+$key = key($callbacks);
+$callback = current($callbacks);
+next($callbacks);
SETS:  PHP 7.2

UnsetCastRector

Remove (unset) cast

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

-$value = (unset) $value;
+unset($value);
SETS:  PHP 7.2

PowToExpRector

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

-pow(1, 2);
+1**2;
SETS:  PHP 5.6

ArrayKeyExistsNullToEmptyStringRector

Replace null key in array_key_exists with empty string

-array_key_exists(null, $array);
+array_key_exists('', $array);
SETS:  PHP 8.5

ChrArgModuloRector

Wrap chr() argument with % 256 to avoid deprecated out-of-range integers

-echo chr(300);
+echo chr(300 % 256);
SETS:  PHP 8.5

RemoveFinfoBufferContextArgRector

Remove argument by position by function name

-finfo_buffer($finfo, $fileContents, FILEINFO_NONE, []);
+finfo_buffer($finfo, $fileContents, FILEINFO_NONE);
SETS:  PHP 8.5

OrdSingleByteRector

Replace ord($str) with ord($str[0])

-echo ord('abc');
+echo ord('a');
SETS:  PHP 8.5

SequentialAssignmentsToPipeOperatorRector

Transform sequential assignments to pipe operator syntax

 $value = "hello world";
-$result1 = function1($value);
-$result2 = function2($result1);

-$result = function3($result2);
+$result = $value
+    |> function1(...)
+    |> function2(...)
+    |> function3(...);

ColonAfterSwitchCaseRector

Change deprecated semicolon to colon after switch case

 switch ($value) {
-    case 'baz';
+    case 'baz':
         echo 'baz';
 }
SETS:  PHP 8.5

ShellExecFunctionCallOverBackticksRector

Replace backticks based with shell_exec() function calls

-$output = `ls -al`;
+$output = shell_exec('ls -al');
 echo "<pre>$output</pre>";
SETS:  PHP 8.5

NestedFuncCallsToPipeOperatorRector

Convert multiple nested function calls in single line to |> pipe operator

 class SomeClass
 {
     public function run($input)
     {
-        $result = trim(strtolower(htmlspecialchars($input)));
+        $result = $input
+            |> htmlspecialchars(...)
+            |> strtolower(...)
+            |> trim(...);
     }
 }

DeprecatedAnnotationToDeprecatedAttributeRector

Change @deprecated annotation to Deprecated attribute

-/**
- * @deprecated 1.0.0 Use SomeOtherConstant instead
- */
+#[\Deprecated(message: 'Use SomeOtherConstant instead', since: '1.0.0')]
 const SomeConstant = 'irrelevant';
SETS:  PHP 8.5

WakeupToUnserializeRector

Change __wakeup() to __unserialize()

 class User {
-    public function __wakeup() {
+    public function __unserialize(array $data): void{
+        foreach ($data as $property => $value) {
+            if (property_exists($this, $property)) {
+                $this->{$property} = $value;
+            }
+        }
     }
 }
SETS:  PHP 8.5

SleepToSerializeRector

Change __sleep() to __serialize() with correct return values

 class User {
     private $id;
     private $name;

-    public function __sleep() {
-        return ['id', 'name'];
+    public function __serialize(): array {
+        return [
+            'id' => $this->id,
+            'name' => $this->name,
+        ];
     }
 }
SETS:  PHP 8.5

NullDebugInfoReturnRector

Replaces null return value with empty array in __debugInfo methods

 new class
 {
     public function __debugInfo() {
-        return null;
+        return [];
     }
 };
SETS:  PHP 8.5

ArrayFirstLastRector

Make use of array_first() and array_last()

-echo $array[array_key_first($array)];
-echo $array[array_key_last($array)];
+echo array_first($array);
+echo array_last($array);
SETS:  PHP 8.5

RemoveExtraParametersRector

Remove extra parameters

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

AssignArrayToStringRector

String cannot be turned into array by assignment anymore

-$string = '';
+$string = [];
 $string[] = 1;
SETS:  PHP 7.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.0;
     }
 }
SETS:  PHP 7.1

MultiExceptionCatchRector

Change multiple catch statements of the same exception to a single one | separated

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

IsIterableRector

Changes is_array + Traversable check to is_iterable

-is_array($foo) || $foo instanceof Traversable;
+is_iterable($foo);
SETS:  PHP 7.1

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]) {
         }
     }
 }
SETS:  PHP 7.1

DirNameFileConstantToDirConstantRector

Convert dirname(__FILE__) to __DIR__

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

ReplaceHttpServerVarsByServerRector

Rename old $HTTP_* variable names to new replacements

-$serverVars = $HTTP_SERVER_VARS;
+$serverVars = $_SERVER;
SETS:  PHP 5.3

TernaryToElvisRector

Use ?: instead of ?, where useful

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

VarToPublicPropertyRector

Change property modifier from var to public

 final class SomeController
 {
-    var $name = 'Tom';
+    public $name = 'Tom';
 }
SETS:  Code Quality

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

ExceptionHandlerTypehintRector

Change typehint from Exception to Throwable

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

ThisCallOnStaticMethodToStaticCallRector

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

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

     public static function eat()
     {
     }
 }
SETS:  PHP 7.0

EregToPregMatchRector

Changes ereg*() to preg*() calls

-ereg("hi")
+preg_match("#hi#");
SETS:  PHP 7.0

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");
SETS:  PHP 7.0

RenameMktimeWithoutArgsToTimeRector

Renames mktime() without arguments to time()

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

MultiDirnameRector

Changes multiple dirname() calls to one with nesting level

-dirname(dirname($path));
+dirname($path, 2);
SETS:  PHP 7.0

RandomFunctionRector

Changes rand, srand, and getrandmax to newer alternatives

-rand();
+random_int();
SETS:  PHP 7.0

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();
     }
 }
SETS:  PHP 7.0

ListSwapArrayOrderRector

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

-list($a[], $a[]) = [1, 2];
+list($a[], $a[]) = array_reverse([1, 2]);
SETS:  PHP 7.0

ListSplitStringRector

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

-list($foo) = "string";
+list($foo) = str_split("string");
SETS:  PHP 7.0

WrapVariableVariableNameInCurlyBracesRector

Ensure variable variables are wrapped in curly braces

 function run($foo)
 {
-    global $$foo->bar;
+    global ${$foo->bar};
 }
SETS:  PHP 7.0

BreakNotInLoopOrSwitchToReturnRector

Convert break outside for/foreach/switch context to return

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

IfIssetToCoalescingRector

Change if with isset and return to coalesce

 class SomeClass
 {
     private $items = [];

     public function resolve($key)
     {
-        if (isset($this->items[$key])) {
-            return $this->items[$key];
-        }
-
-        return 'fallback value';
+        return $this->items[$key] ?? 'fallback value';
     }
 }
SETS:  PHP 7.0

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;
 }
SETS:  PHP 7.0

TernaryToNullCoalescingRector

Changes unneeded null check to ?? operator

-$value === null ? 10 : $value;
+$value ?? 10;
SETS:  PHP 7.0

ReduceMultipleDefaultSwitchRector

Remove first default switch, that is ignored

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

EmptyListRector

list() cannot be empty

-'list() = $values;'
+'list($unusedGenerated) = $values;'
SETS:  PHP 7.0

IfToSpaceshipRector

Changes if/else to spaceship <=> where useful

 usort($languages, function ($first, $second) {
-if ($first[0] === $second[0]) {
-    return 0;
-}
-
-return ($first[0] < $second[0]) ? 1 : -1;
+return $second[0] <=> $first[0];
 });
SETS:  PHP 7.0

Php4ConstructorRector

Change PHP 4 style constructor to __construct

 class SomeClass
 {
-    public function SomeClass()
+    public function __construct()
     {
     }
 }
SETS:  PHP 7.0

ClosureDelegatingCallToFirstClassCallableRector

Convert closure with sole nested call to first class callable

-function ($parameter) {
-    return AnotherClass::someMethod($parameter);
-}
+AnotherClass::someMethod(...);
SETS:  PHP 8.1

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

FunctionFirstClassCallableRector

Upgrade string callback functions to first class callable

 final class SomeClass
 {
     public function run(array $data)
     {
-        return array_map('trim', $data);
+        return array_map(trim(...), $data);
     }
 }
SETS:  PHP 8.1

ClosureFromCallableToFirstClassCallableRector

Change Closure::fromCallable() to first class callable syntax

-Closure::fromCallable([$obj, 'method']);
+$obj->method(...);
SETS:  PHP 8.1

ArrowFunctionDelegatingCallToFirstClassCallableRector

Convert nested arrow function call to first class callable

-fn ($parameter) => Call::to($parameter);
+Call::to(...);
SETS:  PHP 8.1

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));
     }
 }
SETS:  PHP 7.4

FilterVarToAddSlashesRector

Change filter_var() with slash escaping to addslashes()

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

MoneyFormatToNumberFormatRector

Change money_format() to equivalent number_format()

-$value = money_format('%i', $value);
+$value = number_format(round($value, 2, PHP_ROUND_HALF_ODD), 2, '.', '');
SETS:  PHP 7.4

MbStrrposEncodingArgumentPositionRector

Change mb_strrpos() encoding argument position

-mb_strrpos($text, "abc", "UTF-8");
+mb_strrpos($text, "abc", 0, "UTF-8");
SETS:  PHP 7.4

HebrevcToNl2brHebrevRector

Change hebrevc($str) to nl2br(hebrev($str))

-hebrevc($str);
+nl2br(hebrev($str));
SETS:  PHP 7.4

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');
SETS:  PHP 7.4

RestoreIncludePathToIniRestoreRector

Change restore_include_path() to ini_restore("include_path")

-restore_include_path();
+ini_restore('include_path');
SETS:  PHP 7.4

ExportToReflectionFunctionRector

Change export() to ReflectionFunction alternatives

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

RestoreDefaultNullToNullableTypePropertyRector

Add null default to properties with PHP 7.4 property nullable type

 class SomeClass
 {
-    public ?string $name;
+    public ?string $name = null;
 }
SETS:  PHP 7.4

NullCoalescingOperatorRector

Use null coalescing operator ??=

 $array = [];
-$array['user_id'] = $array['user_id'] ?? 'value';
+$array['user_id'] ??= 'value';
SETS:  PHP 7.4

ParenthesizeNestedTernaryRector

Add parentheses to nested ternary

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

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];
SETS:  PHP 7.4

RemoveReferenceFromCallRector

Remove & from function and method calls

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

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;
     }
 }
SETS:  PHP 5.4

LongArrayToShortArrayRector

Long array to short array

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

RemoveParentCallWithoutParentRector

Remove unused parent call with no parent class

 class OrphanClass
 {
     public function __construct()
     {
-         parent::__construct();
     }
 }
SETS:  PHP 8.0 Dead Code

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);
    }
 }
SETS:  PHP 5.5

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);
    }
 }
SETS:  PHP 5.5

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);
     }
 }
SETS:  PHP 5.5

StaticToSelfOnFinalClassRector

Change static::class to self::class on final class

 final class SomeClass
 {
    public function callOnMe()
    {
-       var_dump(static::class);
+       var_dump(self::class);
    }
 }
SETS:  PHP 5.5

Configurable

StringClassNameToClassConstantRector

Replace string class names by ::class constant

 class AnotherClass
 {
 }

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

ClassConstantToSelfClassRector

Change __CLASS__ to self::class

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

ClassOnObjectRector

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

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

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;
     }
 }
SETS:  PHP 8.0

RemoveUnusedVariableInCatchRector

Remove unused variable in catch()

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

Configurable

NestedAnnotationToAttributeRector

Change nested annotations to attributes

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

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);
     }
 }
SETS:  PHP 8.0 Polyfills

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);
     }
 }
SETS:  PHP 8.0 Polyfills

StrContainsRector

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

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

MbStrContainsRector

Replace mb_strpos() !== false and mb_strstr() with str_contains()

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

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);
     }
 }
SETS:  PHP 8.0 Polyfills

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',
+};
SETS:  PHP 8.0

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';
     }
 }
SETS:  PHP 8.0

Configurable

AnnotationToAttributeRector

Change annotation to attribute

 use Symfony\Component\Routing\Annotation\Route;

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

Configurable

ClassPropertyAssignToConstructorPromotionRector

Change simple property init and assign to constructor promotion

 class SomeClass
 {
-    public float $price;
-
     public function __construct(
-        float $price = 0.0
+        public float $price = 0.0
     ) {
-        $this->price = $price;
     }
 }
SETS:  PHP 8.0

FinalPrivateToPrivateVisibilityRector

Change method visibility from final private to only private

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

SetStateToStaticRector

Add static visibility to __set_state() methods

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

     }
 }
SETS:  PHP 8.0

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)
     {
     }
 }
SETS:  PHP 8.0

OptionalParametersAfterRequiredRector

Add reasonable default value when a required parameter follows an optional one

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

ReturnNeverTypeRector

Add "never" return-type for methods that never return anything

 final class SomeClass
 {
-    public function run()
+    public function run(): never
     {
         throw new InvalidException();
     }
 }

Utf8DecodeEncodeToMbConvertEncodingRector

Change deprecated utf8_decode() and utf8_encode() to mb_convert_encoding()

-utf8_decode($value);
-utf8_encode($value);
+mb_convert_encoding($value, 'ISO-8859-1');
+mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1');
SETS:  PHP 8.2

VariableInStringInterpolationFixerRector

Replace deprecated ${var} to {$var}

 $c = "football";
-echo "I like playing ${c}";
+echo "I like playing {$c}";
SETS:  PHP 8.2

Configurable

AddSensitiveParameterAttributeRector

Add SensitiveParameter attribute to method and function configured parameters

 class SomeClass
 {
-    public function run(string $password)
+    public function run(#[\SensitiveParameter] string $password)
     {
     }
 }

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);
SETS:  PHP 8.2

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
     ) {
     }
 }
SETS:  PHP 8.2