Find the best Rector rule to solve your problem


Configurable

DisallowedEmptyRuleFixerRector

Fixer for PHPStan reports by strict type rule - "PHPStan\Rules\DisallowedConstructs\DisallowedEmptyRule"

 final class SomeEmptyArray
 {
     public function run(array $items)
     {
-        return empty($items);
+        return $items === [];
     }
 }

RemoveExtraParametersRector

Remove extra parameters

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

VarToPublicPropertyRector

Change property modifier from var to public

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

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

CountArrayToEmptyArrayComparisonRector

Change count array comparison to empty array comparison to improve performance

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

FuncGetArgsToVariadicParamRector

Refactor func_get_args() in to a variadic param

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

Configurable

RenameFunctionRector

Turns defined function call new one.

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

SimplifyInArrayValuesRector

Removes unneeded array_values() in in_array() call

-in_array("key", array_values($array), true);
+in_array("key", $array, true);
SETS:  Code Quality

RemoveSoleValueSprintfRector

Remove sprintf() wrapper if not needed

 class SomeClass
 {
     public function run()
     {
         $welcome = 'hello';
-        $value = sprintf('%s', $welcome);
+        $value = $welcome;
     }
 }
SETS:  Code Quality

SimplifyStrposLowerRector

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

-strpos(strtolower($var), "...")
+stripos($var, "...")
SETS:  Code Quality

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);
     }
 }
SETS:  Code Quality

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];
     }
 }
SETS:  Code Quality

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);
     }
 }
SETS:  Code Quality

UnwrapSprintfOneArgumentRector

unwrap sprintf() with one argument

-echo sprintf('value');
+echo 'value';
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

ChangeArrayPushToArrayAssignRector

Change array_push() to direct variable assign

 $items = [];
-array_push($items, $item);
+$items[] = $item;
SETS:  Code Quality

SimplifyFuncGetArgsCountRector

Simplify count of func_get_args() to func_num_args()

-count(func_get_args());
+func_num_args();
SETS:  Code Quality

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

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);
         }
     }
 }
SETS:  Code Quality

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];
     }
 }
SETS:  Code Quality

RemoveUselessIsObjectCheckRector

Remove useless is_object() check on combine with instanceof check

-is_object($obj) && $obj instanceof DateTime
+$obj instanceof DateTime
SETS:  Code Quality

SimplifyEmptyArrayCheckRector

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

-is_array($values) && empty($values)
+$values === []
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

ConvertStaticPrivateConstantToSelfRector

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

 final class Foo
 {
     private const BAR = 'bar';

     public function run()
     {
-        $bar = static::BAR;
+        $bar = self::BAR;
     }
 }
SETS:  Code Quality

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);
         }
     }
 }
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

CombinedAssignRector

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

-$value = $value + 5;
+$value += 5;
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

SimplifyDeMorganBinaryRector

Simplify negated conditions with de Morgan theorem

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

ReplaceMultipleBooleanNotRector

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

-$bool = !!$var;
+$bool = (bool) $var;
SETS:  Code Quality

CleanupUnneededNullsafeOperatorRector

Cleanup unneeded nullsafe operator

 class HelloWorld {
     public function getString(): string
     {
          return 'hello world';
     }
 }

 function get(): HelloWorld
 {
      return new HelloWorld();
 }

-echo get()?->getString();
+echo get()->getString();
SETS:  Code Quality

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];
         }
     }
 }
SETS:  Code Quality

SimplifyEmptyCheckOnEmptyArrayRector

Simplify empty() functions calls on empty arrays

 $array = [];

-if (empty($values)) {
+if ([] === $values) {
 }
SETS:  Code Quality

SimplifyConditionsRector

Simplify conditions

-if (! ($foo !== 'bar')) {...
+if ($foo === 'bar') {...
SETS:  Code Quality

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
     }
 }
SETS:  Code Quality

StrlenZeroToIdenticalEmptyStringRector

Changes strlen comparison to 0 to direct empty string compare

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

SimplifyArraySearchRector

Simplify array_search to in_array

-array_search("searching", $array) !== false;
+in_array("searching", $array);
SETS:  Code Quality

FlipTypeControlToUseExclusiveTypeRector

Flip type control from null compare to use exclusive instanceof object

 function process(?DateTime $dateTime)
 {
-    if ($dateTime === null) {
+    if (! $dateTime instanceof DateTime) {
         return;
     }
 }

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

-         $match = in_array($value, $items, TRUE) !== FALSE;
+         $match = in_array($value, $items, TRUE);
     }
 }
SETS:  Code Quality

CommonNotEqualRector

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

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

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;
     }
 }
SETS:  Code Quality

NumberCompareToMaxFuncCallRector

Ternary number compare to max() call

 class SomeClass
 {
     public function run($value)
     {
-        return $value > 100 ? $value : 100;
+        return max($value, 100);
     }
 }
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

UnnecessaryTernaryExpressionRector

Remove unnecessary ternary expressions

-$foo === $bar ? true : false;
+$foo === $bar;
SETS:  Code Quality

SimplifyTautologyTernaryRector

Simplify tautology ternary to value

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

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';
     }
 }
SETS:  Code Quality

NewStaticToNewSelfRector

Change unsafe new static() to new self()

 final class SomeClass
 {
     public function build()
     {
-        return new static();
+        return new self();
     }
 }
SETS:  Code Quality

SwitchTrueToIfRector

Change switch (true) to if statements

 class SomeClass
 {
     public function run()
     {
-        switch (true) {
-            case $value === 0:
-                return 'no';
-            case $value === 1:
-                return 'yes';
-            case $value === 2:
-                return 'maybe';
-        };
+        if ($value === 0) {
+            return 'no';
+        }
+
+        if ($value === 1) {
+            return 'yes';
+        }
+
+        if ($value === 2) {
+            return 'maybe';
+        }
     }
 }
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

JoinStringConcatRector

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

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

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);
+        }
     }
 }
SETS:  Code Quality

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;
+        }
     }
 }
SETS:  Code Quality

CombineIfRector

Merges nested if statements

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

ExplicitBoolCompareRector

Make if conditions more explicit

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

SimplifyIfNullableReturnRector

Direct return on if nullable check before return

 class SomeClass
 {
     public function run()
     {
-        $value = $this->get();
-        if (! $value instanceof \stdClass) {
-            return null;
-        }
-
-        return $value;
+        return $this->get();
     }

     public function get(): ?stdClass {
     }
 }
SETS:  Code Quality

SimplifyIfNotNullReturnRector

Changes redundant null check to instant return

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

CompleteMissingIfElseBracketRector

Complete missing if/else brackets

 class SomeClass
 {
     public function run($value)
     {
-        if ($value)
+        if ($value) {
             return 1;
+        }
     }
 }
SETS:  Code Quality

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;
SETS:  Code Quality

ConsecutiveNullCompareReturnsToNullCoalesceQueueRector

Change multiple null compares to ?? queue

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

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;
     }
 }
SETS:  Code Quality

ShortenElseIfRector

Shortens else/if to elseif

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

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);
SETS:  Code Quality

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;
SETS:  Code Quality

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;
     }
 }
SETS:  Code Quality

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;
         }
     }
 }
SETS:  Code Quality

InlineConstructorDefaultToPropertyRector

Move property default from constructor to property default

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

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

CompleteDynamicPropertiesRector

Add missing dynamic properties

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

StaticToSelfStaticMethodCallOnFinalClassRector

Change static::methodCall() to self::methodCall() on final class

 final class SomeClass
 {
     public function d()
     {
-        echo static::run();
+        echo self::run();
     }

     private static function run()
     {
         echo 'test';
     }
 }
SETS:  Code Quality

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',
+    ];
 }
SETS:  Code Quality

LocallyCalledStaticMethodToNonStaticRector

Change static method and local-only calls to non-static

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

-    private static function someStatic()
+    private function someStatic()
     {
     }
 }
SETS:  Code Quality

OptionalParametersAfterRequiredRector

Move required parameters after optional ones

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

ExplicitReturnNullRector

Add explicit return null to method/function that returns a value, but missed main return

 class SomeClass
 {
     /**
-     * @return string|void
+     * @return string|null
      */
     public function run(int $number)
     {
         if ($number > 50) {
             return 'yes';
         }
+
+        return null;
     }
 }
SETS:  Code Quality

LogicalToBooleanRector

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

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

AndAssignsToSeparateLinesRector

Split 2 assigns ands to separate line

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