Find the best Rector rule to solve your problem
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 === [];
}
}
Remove extra parameters
-strlen("asdf", 1);
+strlen("asdf");
Change property modifier from var
to public
final class SomeController
{
- var $name = 'Tom';
+ public $name = 'Tom';
}
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);
}
}
Change count array comparison to empty array comparison to improve performance
-count($array) === 0;
-count($array) > 0;
-! count($array);
+$array === [];
+$array !== [];
+$array === [];
Refactor func_get_args() in to a variadic param
-function run()
+function run(...$args)
{
- $args = \func_get_args();
}
Turns defined function call new one.
-view("...", []);
+Laravel\Templating\render("...", []);
Removes unneeded array_values() in in_array() call
-in_array("key", array_values($array), true);
+in_array("key", $array, true);
Remove sprintf() wrapper if not needed
class SomeClass
{
public function run()
{
$welcome = 'hello';
- $value = sprintf('%s', $welcome);
+ $value = $welcome;
}
}
Simplify strpos(strtolower(), "...") calls
-strpos(strtolower($var), "...")
+stripos($var, "...")
Simplify regex pattern to known ranges
class SomeClass
{
public function run($value)
{
- preg_match('#[a-zA-Z0-9+]#', $value);
+ preg_match('#[\w\d+]#', $value);
}
}
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];
}
}
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);
}
}
unwrap sprintf() with one argument
-echo sprintf('value');
+echo 'value';
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;
}
}
Refactor call_user_func() with arrow function to direct call
final class SomeClass
{
public function run()
{
- $result = \call_user_func(fn () => 100);
+ $result = 100;
}
}
Change array_push() to direct variable assign
$items = [];
-array_push($items, $item);
+$items[] = $item;
Simplify count of func_get_args() to func_num_args()
-count(func_get_args());
+func_num_args();
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;
}
}
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);
}
}
}
Change compact() call to own array
class SomeClass
{
public function run()
{
$checkout = 'one';
$form = 'two';
- return compact('checkout', 'form');
+ return ['checkout' => $checkout, 'form' => $form];
}
}
Remove useless is_object() check on combine with instanceof check
-is_object($obj) && $obj instanceof DateTime
+$obj instanceof DateTime
Simplify is_array
and empty
functions combination into a simple identical check for an empty array
-is_array($values) && empty($values)
+$values === []
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;
}
}
Replaces static::* access to private constants with self::*
final class Foo
{
private const BAR = 'bar';
public function run()
{
- $bar = static::BAR;
+ $bar = self::BAR;
}
}
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);
}
}
}
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;
}
}
Simplify $value = $value + 5; assignments to shorter ones
-$value = $value + 5;
+$value += 5;
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;
}
}
Simplify negated conditions with de Morgan theorem
$a = 5;
$b = 10;
-$result = !($a > 20 || $b <= 50);
+$result = $a <= 20 && $b > 50;
Replace the Double not operator (!!) by type-casting to boolean
-$bool = !!$var;
+$bool = (bool) $var;
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();
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];
}
}
}
Simplify empty() functions calls on empty arrays
$array = [];
-if (empty($values)) {
+if ([] === $values) {
}
Simplify conditions
-if (! ($foo !== 'bar')) {...
+if ($foo === 'bar') {...
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
}
}
Changes strlen comparison to 0 to direct empty string compare
class SomeClass
{
public function run(string $value)
{
- $empty = strlen($value) === 0;
+ $empty = $value === '';
}
}
Simplify array_search to in_array
-array_search("searching", $array) !== false;
+in_array("searching", $array);
Flip type control from null compare to use exclusive instanceof object
function process(?DateTime $dateTime)
{
- if ($dateTime === null) {
+ if (! $dateTime instanceof DateTime) {
return;
}
}
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);
}
}
Use common != instead of less known <> with same meaning
final class SomeClass
{
public function run($one, $two)
{
- return $one <> $two;
+ return $one != $two;
}
}
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;
}
}
Ternary number compare to max() call
class SomeClass
{
public function run($value)
{
- return $value > 100 ? $value : 100;
+ return max($value, 100);
}
}
Switch negated ternary condition rector
class SomeClass
{
public function run(bool $upper, string $name)
{
- return ! $upper
- ? $name
- : strtoupper($name);
+ return $upper
+ ? strtoupper($name)
+ : $name;
}
}
Remove unnecessary ternary expressions
-$foo === $bar ? true : false;
+$foo === $bar;
Simplify tautology ternary to value
-$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;
+$value = $fullyQualifiedTypeHint;
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';
}
}
Change unsafe new static() to new self()
final class SomeClass
{
public function build()
{
- return new static();
+ return new self();
}
}
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';
+ }
}
}
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;
}
}
Joins concat of 2 strings, unless the length is too long
class SomeClass
{
public function run()
{
- $name = 'Hi' . ' Tom';
+ $name = 'Hi Tom';
}
}
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);
+ }
}
}
Change inline if to explicit if
class SomeClass
{
public function run()
{
$userId = null;
- is_null($userId) && $userId = 5;
+ if (is_null($userId)) {
+ $userId = 5;
+ }
}
}
Merges nested if statements
class SomeClass
{
public function run()
{
- if ($cond1) {
- if ($cond2) {
- return 'foo';
- }
+ if ($cond1 && $cond2) {
+ return 'foo';
}
}
}
Make if conditions more explicit
final class SomeController
{
public function run($items)
{
- if (!count($items)) {
+ if (count($items) === 0) {
return 'no items';
}
}
}
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 {
}
}
Changes redundant null check to instant return
$newNode = 'something';
-if ($newNode !== null) {
- return $newNode;
-}
-
-return null;
+return $newNode;
Complete missing if/else brackets
class SomeClass
{
public function run($value)
{
- if ($value)
+ if ($value) {
return 1;
+ }
}
}
Shortens if return false/true to direct return
-if (strpos($docToken->getContent(), "\n") === false) {
- return true;
-}
-
-return false;
+return strpos($docToken->getContent(), "\n") === false;
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;
}
}
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;
}
}
Shortens else/if to elseif
class SomeClass
{
public function run()
{
if ($cond1) {
return $action1;
- } else {
- if ($cond2) {
- return $action2;
- }
+ } elseif ($cond2) {
+ return $action2;
}
}
}
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);
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;
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;
}
}
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;
}
}
}
Move property default from constructor to property default
final class SomeClass
{
- private $name;
+ private $name = 'John';
public function __construct()
{
- $this->name = 'John';
}
}
Add missing dynamic properties
class SomeClass
{
+ /**
+ * @var int
+ */
+ public $value;
+
public function set()
{
$this->value = 5;
}
}
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';
}
}
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',
+ ];
}
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()
{
}
}
Move required parameters after optional ones
class SomeObject
{
- public function run($optional = 1, $required)
+ public function run($required, $optional = 1)
{
}
}
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;
}
}
Change OR, AND to ||, && with more common understanding
-if ($f = false or true) {
+if (($f = false) || true) {
return $f;
}
Split 2 assigns ands to separate line
class SomeClass
{
public function run()
{
$tokens = [];
- $token = 4 and $tokens[] = $token;
+ $token = 4;
+ $tokens[] = $token;
}
}