e9d1172717
[automated] Re-Generate Nodes/Rectors Documentation (#683)
278 KiB
476 Rules Overview
Categories
-
Arguments (4)
-
Autodiscovery (4)
-
Carbon (2)
-
CodeQuality (68)
-
CodingStyle (38)
-
Composer (6)
-
DeadCode (49)
-
Defluent (9)
-
DowngradePhp53 (1)
-
DowngradePhp70 (10)
-
DowngradePhp71 (9)
-
DowngradePhp72 (4)
-
DowngradePhp73 (6)
-
DowngradePhp74 (10)
-
DowngradePhp80 (18)
-
DowngradePhp81 (1)
-
EarlyReturn (11)
-
LeagueEvent (1)
-
MysqlToMysqli (4)
-
Naming (6)
-
Order (1)
-
PSR4 (2)
-
Php52 (2)
-
Php53 (4)
-
Php54 (2)
-
Php55 (3)
-
Php56 (2)
-
Php70 (19)
-
Php71 (9)
-
Php72 (10)
-
Php73 (9)
-
Php74 (14)
-
Php80 (17)
-
Php81 (5)
-
PhpSpecToPHPUnit (7)
-
PostRector (7)
-
Privatization (10)
-
Removing (6)
-
RemovingStatic (8)
-
Renaming (11)
-
Restoration (6)
-
Transform (34)
-
TypeDeclaration (20)
-
Visibility (2)
Arguments
ArgumentAdderRector
This Rector adds new default arguments in calls of defined methods and class types.
🔧 configure it!
use Rector\Arguments\Rector\ClassMethod\ArgumentAdderRector;
use Rector\Arguments\ValueObject\ArgumentAdder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentAdderRector::class)
->call('configure', [[
ArgumentAdderRector::ADDED_ARGUMENTS => ValueObjectInliner::inline([
new ArgumentAdder('SomeExampleClass', 'someMethod', 0, 'someArgument', true, 'SomeType', null),
]),
]]);
};
↓
$someObject = new SomeExampleClass;
-$someObject->someMethod();
+$someObject->someMethod(true);
use Rector\Arguments\Rector\ClassMethod\ArgumentAdderRector;
use Rector\Arguments\ValueObject\ArgumentAdder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentAdderRector::class)
->call('configure', [[
ArgumentAdderRector::ADDED_ARGUMENTS => ValueObjectInliner::inline([
new ArgumentAdder('SomeExampleClass', 'someMethod', 0, 'someArgument', true, 'SomeType', null),
]),
]]);
};
↓
class MyCustomClass extends SomeExampleClass
{
- public function someMethod()
+ public function someMethod($value = true)
{
}
}
FunctionArgumentDefaultValueReplacerRector
Streamline the operator arguments of version_compare function
🔧 configure it!
use Rector\Arguments\Rector\FuncCall\FunctionArgumentDefaultValueReplacerRector;
use Rector\Arguments\ValueObject\ReplaceFuncCallArgumentDefaultValue;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(FunctionArgumentDefaultValueReplacerRector::class)
->call('configure', [[
FunctionArgumentDefaultValueReplacerRector::REPLACED_ARGUMENTS => ValueObjectInliner::inline([
new ReplaceFuncCallArgumentDefaultValue('version_compare', 2, 'gte', 'ge'),
]),
]]);
};
↓
-version_compare(PHP_VERSION, '5.6', 'gte');
+version_compare(PHP_VERSION, '5.6', 'ge');
ReplaceArgumentDefaultValueRector
Replaces defined map of arguments in defined methods and their calls.
🔧 configure it!
use Rector\Arguments\Rector\ClassMethod\ReplaceArgumentDefaultValueRector;
use Rector\Arguments\ValueObject\ReplaceArgumentDefaultValue;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReplaceArgumentDefaultValueRector::class)
->call('configure', [[
ReplaceArgumentDefaultValueRector::REPLACED_ARGUMENTS => ValueObjectInliner::inline([
new ReplaceArgumentDefaultValue('SomeClass', 'someMethod', 0, 'SomeClass::OLD_CONSTANT', false),
]),
]]);
};
↓
$someObject = new SomeClass;
-$someObject->someMethod(SomeClass::OLD_CONSTANT);
+$someObject->someMethod(false);
SwapFuncCallArgumentsRector
Swap arguments in function calls
🔧 configure it!
use Rector\Arguments\Rector\FuncCall\SwapFuncCallArgumentsRector;
use Rector\Arguments\ValueObject\SwapFuncCallArguments;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SwapFuncCallArgumentsRector::class)
->call('configure', [[
SwapFuncCallArgumentsRector::FUNCTION_ARGUMENT_SWAPS => ValueObjectInliner::inline([
new SwapFuncCallArguments('some_function', [1, 0]), ]
),
]]);
};
↓
final class SomeClass
{
public function run($one, $two)
{
- return some_function($one, $two);
+ return some_function($two, $one);
}
}
Autodiscovery
MoveEntitiesToEntityDirectoryRector
Move entities to Entity namespace
-// file: app/Controller/Product.php
+// file: app/Entity/Product.php
-namespace App\Controller;
+namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Product
{
}
MoveInterfacesToContractNamespaceDirectoryRector
Move interface to "Contract" namespace
-// file: app/Exception/Rule.php
+// file: app/Contract/Rule.php
-namespace App\Exception;
+namespace App\Contract;
interface Rule
{
}
MoveServicesBySuffixToDirectoryRector
Move classes by their suffix to their own group/directory
🔧 configure it!
use Rector\Autodiscovery\Rector\Class_\MoveServicesBySuffixToDirectoryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MoveServicesBySuffixToDirectoryRector::class)
->call('configure', [[
MoveServicesBySuffixToDirectoryRector::GROUP_NAMES_BY_SUFFIX => ['Repository'],
]]);
};
↓
-// file: app/Entity/ProductRepository.php
+// file: app/Repository/ProductRepository.php
-namespace App\Entity;
+namespace App\Repository;
class ProductRepository
{
}
MoveValueObjectsToValueObjectDirectoryRector
Move value object to ValueObject namespace/directory
🔧 configure it!
use Rector\Autodiscovery\Rector\Class_\MoveValueObjectsToValueObjectDirectoryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MoveValueObjectsToValueObjectDirectoryRector::class)
->call('configure', [[
MoveValueObjectsToValueObjectDirectoryRector::TYPES => ['ValueObjectInterfaceClassName'],
MoveValueObjectsToValueObjectDirectoryRector::SUFFIXES => ['Search'],
MoveValueObjectsToValueObjectDirectoryRector::ENABLE_VALUE_OBJECT_GUESSING => true,
]]);
};
↓
-// app/Exception/Name.php
+// app/ValueObject/Name.php
class Name
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
Carbon
ChangeCarbonSingularMethodCallToPluralRector
Change setter methods with args to their plural names on Carbon\Carbon
use Carbon\Carbon;
final class SomeClass
{
public function run(Carbon $carbon, $value): void
{
- $carbon->addMinute($value);
+ $carbon->addMinutes($value);
}
}
ChangeDiffForHumansArgsRector
Change methods arguments of diffForHumans()
on Carbon\Carbon
use Carbon\Carbon;
final class SomeClass
{
public function run(Carbon $carbon): void
{
- $carbon->diffForHumans(null, true);
+ $carbon->diffForHumans(null, \Carbon\CarbonInterface::DIFF_ABSOLUTE);
- $carbon->diffForHumans(null, false);
+ $carbon->diffForHumans(null, \Carbon\CarbonInterface::DIFF_RELATIVE_AUTO);
}
}
CodeQuality
AbsolutizeRequireAndIncludePathRector
include/require to absolute path. This Rector might introduce backwards incompatible code, when the include/require beeing 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 coalesing
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()
class SomeClass
{
public 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];
}
}
ArrayThisCallToThisMethodCallRector
Change [$this, someMethod]
without any args to $this->someMethod()
class SomeClass
{
public function run()
{
- $values = [$this, 'giveMeMore'];
+ $values = $this->giveMeMore();
}
public function giveMeMore()
{
return 'more';
}
}
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
}
}
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
class SomeClass
{
public function run()
{
$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;
}
}
DateTimeToDateTimeInterfaceRector
Changes DateTime type-hint to DateTimeInterface
class SomeClass {
- public function methodWithDateTime(\DateTime $dateTime)
+ /**
+ * @param \DateTime|\DateTimeImmutable $dateTime
+ */
+ public function methodWithDateTime(\DateTimeInterface $dateTime)
{
return true;
}
}
ExplicitBoolCompareRector
Make if conditions more explicit
final class SomeController
{
public function run($items)
{
- if (!count($items)) {
+ if (count($items) === 0) {
return 'no items';
}
}
}
FixClassCaseSensitivityNameRector
Change miss-typed case sensitivity name to correct one
final class SomeClass
{
public function run()
{
- $anotherClass = new anotherclass;
+ $anotherClass = new AnotherClass;
}
}
final class AnotherClass
{
}
FlipTypeControlToUseExclusiveTypeRector
Flip type control to use exclusive type
class SomeClass
{
public function __construct(array $values)
{
- /** @var PhpDocInfo|null $phpDocInfo */
$phpDocInfo = $functionLike->getAttribute(AttributeKey::PHP_DOC_INFO);
- if ($phpDocInfo === null) {
+ if (! $phpDocInfo instanceof PhpDocInfo) {
return;
}
}
}
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) { }
InArrayAndArrayKeysToArrayKeyExistsRector
Simplify in_array
and array_keys
functions combination into array_key_exists
when array_keys
has one argument only
-in_array("key", array_keys($array), true);
+array_key_exists("key", $array);
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;
+ }
}
}
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();
}
}
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;
}
}
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
Symplify bool value compare to true or false
class SomeClass
{
public function run(bool $value, string $items)
{
- $match = in_array($value, $items, TRUE) === TRUE;
- $match = in_array($value, $items, TRUE) !== FALSE;
+ $match = in_array($value, $items, TRUE);
+ $match = in_array($value, $items, TRUE);
}
}
SimplifyConditionsRector
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;
SimplifyDuplicatedTernaryRector
Remove ternary that duplicated return value of true : false
class SomeClass
{
public function run(bool $value, string $name)
{
- $isTrue = $value ? true : false;
+ $isTrue = $value;
$isName = $name ? true : false;
}
}
SimplifyEmptyArrayCheckRector
Simplify is_array
and empty
functions combination into a simple identical check for an empty array
-is_array($values) && empty($values)
+$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;
}
}
SimplifyIfIssetToNullCoalescingRector
Simplify binary if to null coalesce
final class SomeController
{
public function run($possibleStatieYamlFile)
{
- if (isset($possibleStatieYamlFile['import'])) {
- $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'], $filesToImport);
- } else {
- $possibleStatieYamlFile['import'] = $filesToImport;
- }
+ $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'] ?? [], $filesToImport);
}
}
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;
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($value)
{
- $empty = strlen($value) === 0;
+ $empty = $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;
}
}
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!
use Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ConsistentPregDelimiterRector::class)
->call('configure', [[
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 === [];
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);
}
}
FollowRequireByDirRector
include/require should be followed by absolute path
class SomeClass
{
public function run()
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
}
}
FuncGetArgsToVariadicParamRector
Refactor func_get_args()
in to a variadic param
-function run()
+function run(...$args)
{
- $args = \func_get_args();
}
MakeInheritedMethodVisibilitySameAsParentRector
Make method visibility same as parent one
class ChildClass extends ParentClass
{
- public function run()
+ protected function run()
{
}
}
class ParentClass
{
protected function run()
{
}
}
ManualJsonStringToJsonEncodeArrayRector
Convert manual JSON string to JSON::encode array
+use Nette\Utils\Json;
+
final class SomeClass
{
public function run()
{
- $someJsonAsString = '{"role_name":"admin","numberz":{"id":"10"}}';
+ $data = [
+ 'role_name' => 'admin',
+ 'numberz' => ['id' => 10]
+ ];
+ $someJsonAsString = Json::encode($data);
}
}
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) {
}
OrderAttributesRector
Order attributes by desired names
🔧 configure it!
use Rector\CodingStyle\Rector\ClassMethod\OrderAttributesRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(OrderAttributesRector::class)
->call('configure', [[
OrderAttributesRector::ATTRIBUTES_ORDER => ['First', 'Second'],
]]);
};
↓
+#[First]
#[Second]
-#[First]
class Someclass
{
}
PHPStormVarAnnotationRector
Change various @var
annotation formats to one PHPStorm understands
-$config = 5;
-/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+$config = 5;
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!
use PHPUnit\Framework\TestCase;
use Rector\CodingStyle\Enum\PreferenceSelfThis;
use Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PreferThisOrSelfMethodCallRector::class)
->call('configure', [[
PreferThisOrSelfMethodCallRector::TYPE_TO_PREFERENCE => [
TestCase::class => ValueObjectInliner::inline(PreferenceSelfThis::PREFER_SELF()),
], ]]);
};
↓
class SomeClass extends \PHPUnit\Framework\TestCase
{
public function run()
{
- $this->assertEquals('a', 'a');
+ self::assertEquals('a', 'a');
}
}
PreslashSimpleFunctionRector
Add pre-slash to short named functions to improve performance
class SomeClass
{
public function shorten($value)
{
- return trim($value);
+ return \trim($value);
}
}
RemoveDoubleUnderscoreInMethodNameRector
Non-magic PHP object methods cannot start with "__"
class SomeClass
{
- public function __getName($anotherObject)
+ public function getName($anotherObject)
{
- $anotherObject->__getSurname();
+ $anotherObject->getSurname();
}
}
RemoveUnusedAliasRector
Removes unused use aliases. Keep annotation aliases like "Doctrine\ORM\Mapping as ORM" to keep convention format
-use Symfony\Kernel as BaseKernel;
+use Symfony\Kernel;
-class SomeClass extends BaseKernel
+class SomeClass extends Kernel
{
}
ReturnArrayClassMethodToYieldRector
Turns array return to yield return in specific type and method
🔧 configure it!
use Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector;
use Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReturnArrayClassMethodToYieldRector::class)
->call('configure', [[
ReturnArrayClassMethodToYieldRector::METHODS_TO_YIELDS => ValueObjectInliner::inline([
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;
}
}
SplitGroupedConstantsAndPropertiesRector
Separate constant and properties to own lines
class SomeClass
{
- const HI = true, AHOJ = 'true';
+ const HI = true;
+ const AHOJ = 'true';
/**
* @var string
*/
- public $isIt, $isIsThough;
+ public $isIt;
+
+ /**
+ * @var string
+ */
+ public $isIsThough;
}
SplitStringClassConstantToClassConstFetchRector
Separate class constant in a string to class constant fetch and string
class SomeClass
{
const HI = true;
}
class AnotherClass
{
public function get()
{
- return 'SomeClass::HI';
+ return SomeClass::class . '::HI';
}
}
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 . '::someMethod()';
UseIncrementAssignRector
Use ++ increment instead of $var += 1
class SomeClass
{
public function run()
{
- $style += 1;
+ ++$style;
}
}
UseMessageVariableForSprintfInSymfonyStyleRector
Decouple $message
property from sprintf()
calls in $this->symfonyStyle->method()
use Symfony\Component\Console\Style\SymfonyStyle;
final class SomeClass
{
public function run(SymfonyStyle $symfonyStyle)
{
- $symfonyStyle->info(sprintf('Hi %s', 'Tom'));
+ $message = sprintf('Hi %s', 'Tom');
+ $symfonyStyle->info($message);
}
}
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}!";
}
Composer
AddPackageToRequireComposerRector
Add package to "require" in composer.json
🔧 configure it!
use Rector\Composer\Rector\AddPackageToRequireComposerRector;
use Rector\Composer\ValueObject\PackageAndVersion;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddPackageToRequireComposerRector::class)
->call('configure', [[
AddPackageToRequireComposerRector::PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new PackageAndVersion('symfony/console', '^3.4'),
]),
]]);
};
↓
{
+ "require": {
+ "symfony/console": "^3.4"
+ }
}
AddPackageToRequireDevComposerRector
Add package to "require-dev" in composer.json
🔧 configure it!
use Rector\Composer\Rector\AddPackageToRequireDevComposerRector;
use Rector\Composer\ValueObject\PackageAndVersion;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddPackageToRequireDevComposerRector::class)
->call('configure', [[
AddPackageToRequireDevComposerRector::PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new PackageAndVersion('symfony/console', '^3.4'),
]),
]]);
};
↓
{
+ "require-dev": {
+ "symfony/console": "^3.4"
+ }
}
ChangePackageVersionComposerRector
Change package version composer.json
🔧 configure it!
use Rector\Composer\Rector\ChangePackageVersionComposerRector;
use Rector\Composer\ValueObject\PackageAndVersion;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangePackageVersionComposerRector::class)
->call('configure', [[
ChangePackageVersionComposerRector::PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new PackageAndVersion('symfony/console', '^4.4'),
]),
]]);
};
↓
{
- "require-dev": {
- "symfony/console": "^3.4"
+ "require": {
+ "symfony/console": "^4.4"
}
}
RemovePackageComposerRector
Remove package from "require" and "require-dev" in composer.json
🔧 configure it!
use Rector\Composer\Rector\RemovePackageComposerRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemovePackageComposerRector::class)
->call('configure', [[
RemovePackageComposerRector::PACKAGE_NAMES => ['symfony/console'],
]]);
};
↓
{
- "require": {
- "symfony/console": "^3.4"
- }
}
RenamePackageComposerRector
Change package name in composer.json
🔧 configure it!
use Rector\Composer\Rector\RenamePackageComposerRector;
use Rector\Composer\ValueObject\RenamePackage;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenamePackageComposerRector::class)
->call('configure', [[
RenamePackageComposerRector::RENAME_PACKAGES => ValueObjectInliner::inline([
new RenamePackage('rector/rector', 'rector/rector-src'),
]),
]]);
};
↓
{
"require": {
- "rector/rector": "dev-main"
+ "rector/rector-src": "dev-main"
}
}
ReplacePackageAndVersionComposerRector
Change package name and version composer.json
🔧 configure it!
use Rector\Composer\Rector\ReplacePackageAndVersionComposerRector;
use Rector\Composer\ValueObject\ReplacePackageAndVersion;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReplacePackageAndVersionComposerRector::class)
->call('configure', [[
ReplacePackageAndVersionComposerRector::REPLACE_PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([
new ReplacePackageAndVersion('symfony/console', 'symfony/http-kernel', '^4.4'),
]),
]]);
};
↓
{
"require-dev": {
- "symfony/console": "^3.4"
+ "symfony/http-kernel": "^4.4"
}
}
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!
use Rector\DeadCode\Rector\ClassLike\RemoveAnnotationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveAnnotationRector::class)
->call('configure', [[
RemoveAnnotationRector::ANNOTATIONS_TO_REMOVE => ['method'],
]]);
};
↓
-/**
- * @method getName()
- */
final class SomeClass
{
}
RemoveAssignOfVoidReturnFunctionRector
Remove assign of void function/method to variable
class SomeClass
{
public function run()
{
- $value = $this->getOne();
+ $this->getOne();
}
private function getOne(): void
{
}
}
RemoveCodeAfterReturnRector
Remove dead code after return statement
class SomeClass
{
public function run(int $a)
{
return $a;
- $a++;
}
}
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';
}
}
RemoveDeadConstructorRector
Remove empty constructor
class SomeClass
{
- public function __construct()
- {
- }
}
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;
- }
+ // some code
}
}
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();
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;
}
RemoveOverriddenValuesRector
Remove initial assigns of overridden values
final class SomeController
{
public function run()
{
- $directories = [];
$possibleDirectories = [];
$directories = array_filter($possibleDirectories, 'file_exists');
}
}
RemoveParentCallWithoutParentRector
Remove unused parent call with no parent class
class OrphanClass
{
public function __construct()
{
- parent::__construct();
}
}
RemovePhpVersionIdCheckRector
Remove unneded PHP_VERSION_ID check
🔧 configure it!
use Rector\DeadCode\Rector\ConstFetch\RemovePhpVersionIdCheckRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemovePhpVersionIdCheckRector::class)
->call('configure', [[
RemovePhpVersionIdCheckRector::PHP_VERSION_CONSTRAINT => 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;
}
}
RemoveUnusedAssignVariableRector
Remove assigned unused variable
class SomeClass
{
public function run()
{
- $value = $this->process();
+ $this->process();
}
public function process()
{
// something going on
return 5;
}
}
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
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 $a = $a assigns
-$a = $a;
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;
}
}
UnwrapFutureCompatibleIfFunctionExistsRector
Remove functions exists if with else for always existing
class SomeClass
{
public function run()
{
// session locking trough other addons
- if (function_exists('session_abort')) {
- session_abort();
- } else {
- session_write_close();
- }
+ session_abort();
}
}
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+';
Defluent
DefluentReturnMethodCallRector
Turns return of fluent, to standalone call line and return of value
$someClass = new SomeClass();
-return $someClass->someFunction();
+$someClass->someFunction();
+return $someClass;
FluentChainMethodCallToNormalMethodCallRector
Turns fluent interface calls to classic ones.
$someClass = new SomeClass();
-$someClass->someFunction()
- ->otherFunction();
+$someClass->someFunction();
+$someClass->otherFunction();
InArgFluentChainMethodCallToStandaloneMethodCallRector
Turns fluent interface calls to classic ones.
class UsedAsParameter
{
public function someFunction(FluentClass $someClass)
{
- $this->processFluentClass($someClass->someFunction()->otherFunction());
+ $someClass->someFunction();
+ $someClass->otherFunction();
+ $this->processFluentClass($someClass);
}
public function processFluentClass(FluentClass $someClass)
{
}
}
MethodCallOnSetterMethodCallToStandaloneAssignRector
Change method call on setter to standalone assign before the setter
class SomeClass
{
public function some()
{
- $this->anotherMethod(new AnotherClass())
- ->someFunction();
+ $anotherClass = new AnotherClass();
+ $anotherClass->someFunction();
+ $this->anotherMethod($anotherClass);
}
public function anotherMethod(AnotherClass $anotherClass)
{
}
}
NewFluentChainMethodCallToNonFluentRector
Turns fluent interface calls to classic ones.
-(new SomeClass())->someFunction()
- ->otherFunction();
+$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
NormalToFluentRector
Turns fluent interface calls to classic ones.
🔧 configure it!
use Rector\Defluent\Rector\ClassMethod\NormalToFluentRector;
use Rector\Defluent\ValueObject\NormalToFluent;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NormalToFluentRector::class)
->call('configure', [[
NormalToFluentRector::CALLS_TO_FLUENT => ValueObjectInliner::inline([
new NormalToFluent('SomeClass', ['someFunction', 'otherFunction']), ]
),
]]);
};
↓
$someObject = new SomeClass();
-$someObject->someFunction();
-$someObject->otherFunction();
+$someObject->someFunction()
+ ->otherFunction();
ReturnFluentChainMethodCallToNormalMethodCallRector
Turns fluent interface calls to classic ones.
$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
-return $someClass->someFunction()
- ->otherFunction();
+return $someClass;
ReturnNewFluentChainMethodCallToNonFluentRector
Turns fluent interface calls to classic ones.
-return (new SomeClass())->someFunction()
- ->otherFunction();
+$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
+return $someClass;
ReturnThisRemoveRector
Removes "return $this;"
from fluent interfaces for specified classes.
class SomeExampleClass
{
public function someFunction()
{
- return $this;
}
public function otherFunction()
{
- return $this;
}
}
DependencyInjection
ActionInjectionToConstructorInjectionRector
Turns action injection in Controllers to constructor injection
final class SomeController
{
- public function default(ProductRepository $productRepository)
+ /**
+ * @var ProductRepository
+ */
+ private $productRepository;
+ public function __construct(ProductRepository $productRepository)
{
- $products = $productRepository->fetchAll();
+ $this->productRepository = $productRepository;
+ }
+
+ public function default()
+ {
+ $products = $this->productRepository->fetchAll();
}
}
AddMethodParentCallRector
Add method parent call, in case new parent method is added
🔧 configure it!
use Rector\DependencyInjection\Rector\ClassMethod\AddMethodParentCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddMethodParentCallRector::class)
->call('configure', [[
AddMethodParentCallRector::METHODS_BY_PARENT_TYPES => [
'ParentClassWithNewConstructor' => '__construct',
], ]]);
};
↓
class SunshineCommand extends ParentClassWithNewConstructor
{
public function __construct()
{
$value = 5;
+
+ parent::__construct();
}
}
ReplaceVariableByPropertyFetchRector
Turns variable in controller action to property fetch, as follow up to action injection variable to property change.
final class SomeController
{
/**
* @var ProductRepository
*/
private $productRepository;
public function __construct(ProductRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public function default()
{
- $products = $productRepository->fetchAll();
+ $products = $this->productRepository->fetchAll();
}
}
DowngradePhp53
DirConstToFileConstRector
Refactor DIR to dirname(FILE)
final class SomeClass
{
public function run()
{
- return __DIR__;
+ return dirname(__FILE__);
}
}
DowngradePhp70
DowngradeAnonymousClassRector
Remove anonymous class
+class Anonymous
+{
+ public function execute()
+ {
+ }
+}
class SomeClass
{
public function run()
{
- return new class {
- public function execute()
- {
- }
- };
+ return new Anonymous();
}
}
DowngradeDefineArrayConstantRector
Change array contant definition via define to const
-define('ANIMALS', [
+const ANIMALS = [
'dog',
'cat',
'bird'
-]);
+];
DowngradeGeneratedScalarTypesRector
Refactor scalar types in PHP code in string snippets, e.g. generated container code from symfony/dependency-injection
$code = <<<'EOF'
- public function getParameter(string $name)
+ /**
+ * @param string $name
+ */
+ public function getParameter($name)
{
return $name;
}
EOF;
DowngradeNullCoalesceRector
Change null coalesce to isset ternary check
-$username = $_GET['user'] ?? 'nobody';
+$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
DowngradeScalarTypeDeclarationRector
Remove the type params and return type, add @param
and @return
tags instead
class SomeClass
{
- public function run(string $input): string
+ /**
+ * @param string $input
+ * @return string
+ */
+ public function run($input)
{
}
}
DowngradeSelfTypeDeclarationRector
Remove "self" return type, add a "@return
self" tag instead
class SomeClass
{
- public function foo(): self
+ public function foo()
{
return $this;
}
}
DowngradeSessionStartArrayOptionsRector
Move array option of session_start($options) to before statement's ini_set()
-session_start([
- 'cache_limiter' => 'private',
-]);
+ini_set('session.cache_limiter', 'private');
+session_start();
DowngradeSpaceshipRector
Change spaceship with check equal, and ternary to result 0, -1, 1
-return $a <=> $b;
+$battleShipcompare = function ($left, $right) {
+ if ($left === $right) {
+ return 0;
+ }
+ return $left < $right ? -1 : 1;
+};
+return $battleShipcompare($a, $b);
DowngradeStrictTypeDeclarationRector
Remove the declare(strict_types=1)
-declare(strict_types=1);
SplitGroupedUseImportsRector
Refactor grouped use imports to standalone lines
-use SomeNamespace\{
- First,
- Second
-};
+use SomeNamespace\First;
+use SomeNamespace\Second;
DowngradePhp71
DowngradeClassConstantVisibilityRector
Downgrade class constant visibility
class SomeClass
{
- public const PUBLIC_CONST_B = 2;
- protected const PROTECTED_CONST = 3;
- private const PRIVATE_CONST = 4;
+ const PUBLIC_CONST_B = 2;
+ const PROTECTED_CONST = 3;
+ const PRIVATE_CONST = 4;
}
DowngradeIsIterableRector
Change is_iterable with array and Traversable object type check
class SomeClass
{
public function run($obj)
{
- is_iterable($obj);
+ is_array($obj) || $obj instanceof \Traversable;
}
}
DowngradeIterablePseudoTypeDeclarationRector
Remove the iterable pseudo type params and returns, add @param
and @return
tags instead
class SomeClass
{
- public function run(iterable $iterator): iterable
+ /**
+ * @param mixed[]|\Traversable $iterator
+ * @return mixed[]|\Traversable
+ */
+ public function run($iterator)
{
// do something
}
}
DowngradeKeysInListRector
Extract keys in list to its own variable assignment
class SomeClass
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
- list("id" => $id1, "name" => $name1) = $data[0];
+ $id1 = $data[0]["id"];
+ $name1 = $data[0]["name"];
}
}
DowngradeNegativeStringOffsetToStrlenRector
Downgrade negative string offset to strlen
-echo 'abcdef'[-2];
-echo strpos('aabbcc', 'b', -3);
-echo strpos($var, 'b', -3);
+echo 'abcdef'[strlen('abcdef') - 2];
+echo strpos('aabbcc', 'b', strlen('aabbcc') - 3);
+echo strpos($var, 'b', strlen($var) - 3);
DowngradeNullableTypeDeclarationRector
Remove the nullable type params, add @param
tags instead
class SomeClass
{
- public function run(?string $input): ?string
+ /**
+ * @param string|null $input
+ * @return string|null
+ */
+ public function run($input)
{
}
}
DowngradePipeToMultiCatchExceptionRector
Downgrade single one | separated to multi catch exception
try {
// Some code...
-} catch (ExceptionType1 | ExceptionType2 $exception) {
+} catch (ExceptionType1 $exception) {
+ $sameCode;
+} catch (ExceptionType2 $exception) {
$sameCode;
}
DowngradeVoidTypeDeclarationRector
Remove "void" return type, add a "@return
void" tag instead
class SomeClass
{
- public function run(): void
+ /**
+ * @return void
+ */
+ public function run()
{
}
}
SymmetricArrayDestructuringToListRector
Downgrade Symmetric array destructuring to list()
function
-[$id1, $name1] = $data;
+list($id1, $name1) = $data;
DowngradePhp72
DowngradeObjectTypeDeclarationRector
Remove the "object" param and return type, add a @param
and @return
tags instead
class SomeClass
{
- public function someFunction(object $someObject): object
+ /**
+ * @param object $someObject
+ * @return object
+ */
+ public function someFunction($someObject)
{
}
}
DowngradeParameterTypeWideningRector
Change param type to match the lowest type in whole family tree
🔧 configure it!
use Rector\DowngradePhp72\Rector\ClassMethod\DowngradeParameterTypeWideningRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeParameterTypeWideningRector::class)
->call('configure', [[
DowngradeParameterTypeWideningRector::SAFE_TYPES => [],
DowngradeParameterTypeWideningRector::SAFE_TYPES_TO_METHODS => [],
]]);
};
↓
interface SomeInterface
{
- public function test(array $input);
+ /**
+ * @param mixed[] $input
+ */
+ public function test($input);
}
final class SomeClass implements SomeInterface
{
public function test($input)
{
}
}
DowngradePregUnmatchedAsNullConstantRector
Remove PREG_UNMATCHED_AS_NULL from preg_match and set null value on empty string matched on each match
class SomeClass
{
public function run()
{
- preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL);
+ preg_match('/(a)(b)*(c)/', 'ac', $matches);
+ array_walk_recursive($matches, function (&$value) {
+ if ($value === '') {
+ $value = null;
+ }
+ });
}
}
DowngradeStreamIsattyRector
Downgrade stream_isatty()
function
class SomeClass
{
public function run($stream)
{
- $isStream = stream_isatty($stream);
+ $streamIsatty = function ($stream) {
+ if (\function_exists('stream_isatty')) {
+ return stream_isatty($stream);
+ }
+
+ if (!\is_resource($stream)) {
+ trigger_error('stream_isatty() expects parameter 1 to be resource, '.\gettype($stream).' given', \E_USER_WARNING);
+
+ return false;
+ }
+
+ if ('\\' === \DIRECTORY_SEPARATOR) {
+ $stat = @fstat($stream);
+ // Check if formatted mode is S_IFCHR
+ return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
+ }
+
+ return \function_exists('posix_isatty') && @posix_isatty($stream);
+ };
+ $isStream = $streamIsatty($stream);
}
}
DowngradePhp73
DowngradeArrayKeyFirstLastRector
Downgrade array_key_first()
and array_key_last()
functions
class SomeClass
{
public function run($items)
{
- $firstItemKey = array_key_first($items);
+ reset($items);
+ $firstItemKey = key($items);
}
}
DowngradeFlexibleHeredocSyntaxRector
Remove indentation from heredoc/nowdoc
$query = <<<SQL
- SELECT *
- FROM `table`
- WHERE `column` = true;
- SQL;
+SELECT *
+FROM `table`
+WHERE `column` = true;
+SQL;
DowngradeIsCountableRector
Downgrade is_countable()
to former version
$items = [];
-return is_countable($items);
+return is_array($items) || $items instanceof Countable;
DowngradeListReferenceAssignmentRector
Convert the list reference assignment to its equivalent PHP 7.2 code
class SomeClass
{
public function run($string)
{
- $array = [1, 2, 3];
- list($a, &$b) = $array;
+ $array = [1, 2];
+ list($a) = $array;
+ $b =& $array[1];
- [&$c, $d, &$e] = $array;
+ [$c, $d, $e] = $array;
+ $c =& $array[0];
+ $e =& $array[2];
- list(&$a, &$b) = $array;
+ $a =& $array[0];
+ $b =& $array[1];
}
}
DowngradeTrailingCommasInFunctionCallsRector
Remove trailing commas in function calls
class SomeClass
{
public function __construct(string $value)
{
$compacted = compact(
'posts',
- 'units',
+ 'units'
);
}
}
SetCookieOptionsArrayToArgumentsRector
Convert setcookie option array to arguments
-setcookie('name', $value, ['expires' => 360]);
+setcookie('name', $value, 360);
DowngradePhp74
ArrowFunctionToAnonymousFunctionRector
Replace arrow functions with anonymous functions
class SomeClass
{
public function run()
{
$delimiter = ",";
- $callable = fn($matches) => $delimiter . strtolower($matches[1]);
+ $callable = function ($matches) use ($delimiter) {
+ return $delimiter . strtolower($matches[1]);
+ };
}
}
DowngradeArrayMergeCallWithoutArgumentsRector
Add missing param to array_merge
and array_merge_recursive
class SomeClass
{
public function run()
{
- array_merge();
- array_merge_recursive();
+ array_merge([]);
+ array_merge_recursive([]);
}
}
DowngradeArraySpreadRector
Replace array spread with array_merge function
class SomeClass
{
public function run()
{
$parts = ['apple', 'pear'];
- $fruits = ['banana', 'orange', ...$parts, 'watermelon'];
+ $fruits = array_merge(['banana', 'orange'], $parts, ['watermelon']);
}
public function runWithIterable()
{
- $fruits = ['banana', 'orange', ...new ArrayIterator(['durian', 'kiwi']), 'watermelon'];
+ $item0Unpacked = new ArrayIterator(['durian', 'kiwi']);
+ $fruits = array_merge(['banana', 'orange'], is_array($item0Unpacked) ? $item0Unpacked : iterator_to_array($item0Unpacked), ['watermelon']);
}
}
DowngradeContravariantArgumentTypeRector
Remove contravariant argument type declarations
class ParentType {}
class ChildType extends ParentType {}
class A
{
public function contraVariantArguments(ChildType $type)
{
}
}
class B extends A
{
- public function contraVariantArguments(ParentType $type)
+ /**
+ * @param ParentType $type
+ */
+ public function contraVariantArguments($type)
{
}
}
DowngradeCovariantReturnTypeRector
Make method return same type as parent
class ParentType {}
class ChildType extends ParentType {}
class A
{
public function covariantReturnTypes(): ParentType
{
}
}
class B extends A
{
- public function covariantReturnTypes(): ChildType
+ /**
+ * @return ChildType
+ */
+ public function covariantReturnTypes(): ParentType
{
}
}
DowngradeFreadFwriteFalsyToNegationRector
Changes fread()
or fwrite()
compare to false to negation check
-fread($handle, $length) === false;
-fwrite($fp, '1') === false;
+!fread($handle, $length);
+!fwrite($fp, '1');
DowngradeNullCoalescingOperatorRector
Remove null coalescing operator ??=
$array = [];
-$array['user_id'] ??= 'value';
+$array['user_id'] = $array['user_id'] ?? 'value';
DowngradeNumericLiteralSeparatorRector
Remove "_" as thousands separator in numbers
class SomeClass
{
public function run()
{
- $int = 1_000;
- $float = 1_000_500.001;
+ $int = 1000;
+ $float = 1000500.001;
}
}
DowngradeStripTagsCallWithArrayRector
Convert 2nd param to strip_tags
from array to string
class SomeClass
{
public function run($string)
{
// Arrays: change to string
- strip_tags($string, ['a', 'p']);
+ strip_tags($string, '<' . implode('><', ['a', 'p']) . '>');
// Variables/consts/properties: if array, change to string
$tags = ['a', 'p'];
- strip_tags($string, $tags);
+ strip_tags($string, $tags !== null && is_array($tags) ? '<' . implode('><', $tags) . '>' : $tags);
// Default case (eg: function call): externalize to var, then if array, change to string
- strip_tags($string, getTags());
+ $expr = getTags();
+ strip_tags($string, is_array($expr) ? '<' . implode('><', $expr) . '>' : $expr);
}
}
DowngradeTypedPropertyRector
Changes property type definition from type definitions to @var
annotations.
class SomeClass
{
- private string $property;
+ /**
+ * @var string
+ */
+ private $property;
}
DowngradePhp80
DowngradeAbstractPrivateMethodInTraitRector
Remove "abstract" from private methods in traits and adds an empty function body
trait SomeTrait
{
- abstract private function someAbstractPrivateFunction();
+ private function someAbstractPrivateFunction() {}
}
DowngradeAttributeToAnnotationRector
Refactor PHP attribute markers to annotations notation
🔧 configure it!
use Rector\DowngradePhp80\Rector\Class_\DowngradeAttributeToAnnotationRector;
use Rector\DowngradePhp80\ValueObject\DowngradeAttributeToAnnotation;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeAttributeToAnnotationRector::class)
->call('configure', [[
DowngradeAttributeToAnnotationRector::ATTRIBUTE_TO_ANNOTATION => ValueObjectInliner::inline([
new DowngradeAttributeToAnnotation('Symfony\Component\Routing\Annotation\Route', null),
]),
]]);
};
↓
use Symfony\Component\Routing\Annotation\Route;
class SymfonyRoute
{
- #[Route(path: '/path', name: 'action')]
+ /**
+ * @Route("/path", name="action")
+ */
public function action()
{
}
}
DowngradeClassOnObjectToGetClassRector
Change $object::class
to get_class($object)
class SomeClass
{
public function run($object)
{
- return $object::class;
+ return get_class($object);
}
}
DowngradeMatchToSwitchRector
Downgrade match()
to switch()
class SomeClass
{
public function run()
{
- $message = match ($statusCode) {
- 200, 300 => null,
- 400 => 'not found',
- default => 'unknown status code',
- };
+ switch ($statusCode) {
+ case 200:
+ case 300:
+ $message = null;
+ break;
+ case 400:
+ $message = 'not found';
+ break;
+ default:
+ $message = 'unknown status code';
+ break;
+ }
}
}
DowngradeMixedTypeDeclarationRector
Remove the "mixed" param and return type, add a @param
and @return
tag instead
class SomeClass
{
- public function someFunction(mixed $anything): mixed
+ /**
+ * @param mixed $anything
+ * @return mixed
+ */
+ public function someFunction($anything)
{
}
}
DowngradeNamedArgumentRector
Remove named argument
class SomeClass
{
public function run()
{
- $this->execute(b: 100);
+ $this->execute(null, 100);
}
private function execute($a = null, $b = null)
{
}
}
DowngradeNonCapturingCatchesRector
Downgrade catch () without variable to one
class SomeClass
{
public function run()
{
try {
// code
- } catch (\Exception) {
+ } catch (\Exception $exception) {
// error
}
}
}
DowngradeNullsafeToTernaryOperatorRector
Change nullsafe operator to ternary operator rector
-$dateAsString = $booking->getStartDate()?->asDateTimeString();
-$dateAsString = $booking->startDate?->dateTimeString;
+$dateAsString = ($bookingGetStartDate = $booking->getStartDate()) ? $bookingGetStartDate->asDateTimeString() : null;
+$dateAsString = ($bookingGetStartDate = $booking->startDate) ? $bookingGetStartDate->dateTimeString : null;
DowngradePhpTokenRector
"something()"
will be renamed to "somethingElse()"
-$tokens = \PhpToken::tokenize($code);
+$tokens = token_get_all($code);
-foreach ($tokens as $phpToken) {
- $name = $phpToken->getTokenName();
- $text = $phpToken->text;
+foreach ($tokens as $token) {
+ $name = is_array($token) ? token_name($token[0]) : null;
+ $text = is_array($token) ? $token[1] : $token;
}
DowngradePropertyPromotionRector
Change constructor property promotion to property asssign
class SomeClass
{
- public function __construct(public float $value = 0.0)
+ public float $value;
+
+ public function __construct(float $value = 0.0)
{
+ $this->value = $value;
}
}
DowngradeStaticTypeDeclarationRector
Remove "static" return and param type, add a "@param
$this"
and "@return
$this"
tag instead
class SomeClass
{
- public function getStatic(): static
+ /**
+ * @return static
+ */
+ public function getStatic()
{
return new static();
}
}
DowngradeStrContainsRector
Replace str_contains()
with strpos()
!== false
class SomeClass
{
public function run()
{
- return str_contains('abc', 'a');
+ return strpos('abc', 'a') !== false;
}
}
DowngradeStrEndsWithRector
Downgrade str_ends_with()
to strncmp()
version
-str_ends_with($haystack, $needle);
+"" === $needle || ("" !== $haystack && 0 === substr_compare($haystack, $needle, -\strlen($needle)));
DowngradeStrStartsWithRector
Downgrade str_starts_with()
to strncmp()
version
-str_starts_with($haystack, $needle);
+strncmp($haystack, $needle, strlen($needle)) === 0;
DowngradeThrowExprRector
Downgrade throw as expr
class SomeClass
{
public function run()
{
- $id = $somethingNonexistent ?? throw new RuntimeException();
+ if (!isset($somethingNonexistent)) {
+ throw new RuntimeException();
+ }
+ $id = $somethingNonexistent;
}
}
DowngradeTrailingCommasInParamUseRector
Remove trailing commas in param or use list
class SomeClass
{
- public function __construct(string $value1, string $value2,)
+ public function __construct(string $value1, string $value2)
{
- function (string $value1, string $value2,) {
+ function (string $value1, string $value2) {
};
- function () use ($value1, $value2,) {
+ function () use ($value1, $value2) {
};
}
}
-function inFunction(string $value1, string $value2,)
+function inFunction(string $value1, string $value2)
{
}
DowngradeUnionTypeDeclarationRector
Remove the union type params and returns, add @param/@return
tags instead
class SomeClass
{
- public function echoInput(string|int $input): int|bool
+ /**
+ * @param string|int $input
+ * @return int|bool
+ */
+ public function echoInput($input)
{
echo $input;
}
}
DowngradeUnionTypeTypedPropertyRector
Removes union type property type definition, adding @var
annotations instead.
class SomeClass
{
- private string|int $property;
+ /**
+ * @var string|int
+ */
+ private $property;
}
DowngradePhp81
DowngradeFinalizePublicClassConstantRector
Remove final from class constants
class SomeClass
{
- final public const NAME = 'value';
+ public const NAME = 'value';
}
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;
}
}
ReturnAfterToEarlyOnBreakRector
Change return after foreach to early return in foreach on break
class SomeClass
{
public function run(array $pathConstants, string $allowedPath)
{
- $pathOK = false;
-
foreach ($pathConstants as $allowedPath) {
if ($dirPath == $allowedPath) {
- $pathOK = true;
- break;
+ return true;
}
}
- return $pathOK;
+ return false;
}
}
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();
}
}
LeagueEvent
DispatchStringToObjectRector
Change string events to anonymous class which implement \League\Event\HasEventName
final class SomeClass
{
/** @var \League\Event\EventDispatcher */
private $dispatcher;
public function run()
{
- $this->dispatcher->dispatch('my-event');
+ $this->dispatcher->dispatch(new class implements \League\Event\HasEventName
+ {
+ public function eventName(): string
+ {
+ return 'my-event';
+ }
+ });
}
}
MockeryToProphecy
MockeryCloseRemoveRector
Removes mockery close from test classes
public function tearDown() : void
{
- \Mockery::close();
}
MockeryCreateMockToProphizeRector
Changes mockery mock creation to Prophesize
-$mock = \Mockery::mock('MyClass');
+$mock = $this->prophesize('MyClass');
+
$service = new Service();
-$service->injectDependency($mock);
+$service->injectDependency($mock->reveal());
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();
}
}
Order
OrderPrivateMethodsByUseRector
Order private methods in order of their use
class SomeClass
{
public function run()
{
$this->call1();
$this->call2();
}
- private function call2()
+ private function call1()
{
}
- private function call1()
+ private function call2()
{
}
}
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"
-
class:
Rector\PSR4\Rector\FileWithoutNamespace\NormalizeNamespaceByPSR4ComposerAutoloadRector
-
with
composer.json
:
{
"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
ClearReturnNewByReferenceRector
Remove reference from "$assign = &new Value;"
-$assign = &new Value;
+$assign = new Value;
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
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);
}
}
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!
use Rector\Php55\Rector\String_\StringClassNameToClassConstantRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StringClassNameToClassConstantRector::class)
->call('configure', [[
StringClassNameToClassConstantRector::CLASSES_TO_SKIP => ['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);
NonVariableToVariableOnFunctionCallRector
Transform non variable like arguments to variable where a function or method expects an argument passed by reference
-reset(a());
+$a = a(); reset($a);
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 = count((array) $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!
use Rector\Php71\Rector\Name\ReservedObjectRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReservedObjectRector::class)
->call('configure', [[
ReservedObjectRector::RESERVED_KEYWORDS_TO_REPLACEMENTS => [
'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!
use Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddLiteralSeparatorToNumberRector::class)
->call('configure', [[
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, except values with possible string key values
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));
}
}
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);
GetCalledClassToStaticClassRector
Change get_called_class()
to static::class
class SomeClass
{
public function callOnMe()
{
- var_dump(get_called_class());
+ var_dump(static::class);
}
}
MbStrrposEncodingArgumentPositionRector
Change mb_strrpos()
encoding argument position
-mb_strrpos($text, "abc", "UTF-8");
+mb_strrpos($text, "abc", 0, "UTF-8");
NullCoalescingOperatorRector
Use null coalescing operator ??=
$array = [];
-$array['user_id'] = $array['user_id'] ?? 'value';
+$array['user_id'] ??= 'value';
RealToFloatTypeCastRector
Change deprecated (real) to (float)
class SomeClass
{
public function run()
{
- $number = (real) 5;
+ $number = (float) 5;
$number = (float) 5;
$number = (double) 5;
}
}
ReservedFnFunctionRector
Change fn()
function name, since it will be reserved keyword
🔧 configure it!
use Rector\Php74\Rector\Function_\ReservedFnFunctionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReservedFnFunctionRector::class)
->call('configure', [[
ReservedFnFunctionRector::RESERVED_NAMES_TO_NEW_ONES => [
'fn' => 'someFunctionName',
], ]]);
};
↓
class SomeClass
{
public function run()
{
- function fn($value)
+ function f($value)
{
return $value;
}
- fn(5);
+ f(5);
}
}
RestoreDefaultNullToNullableTypePropertyRector
Add null default to properties with PHP 7.4 property nullable type
class SomeClass
{
- public ?string $name;
+ public ?string $name = null;
}
TypedPropertyRector
Changes property @var
annotations from annotation to type.
🔧 configure it!
use Rector\Php74\Rector\Property\TypedPropertyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(TypedPropertyRector::class)
->call('configure', [[
TypedPropertyRector::CLASS_LIKE_TYPE_ONLY => false,
]]);
};
↓
final class SomeClass
{
- /**
- * @var int
- */
- private $count;
+ private int $count;
}
Php80
AnnotationToAttributeRector
Change annotation to attribute
🔧 configure it!
use Rector\Php80\Rector\Class_\AnnotationToAttributeRector;
use Rector\Php80\ValueObject\AnnotationToAttribute;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AnnotationToAttributeRector::class)
->call('configure', [[
AnnotationToAttributeRector::ANNOTATION_TO_ATTRIBUTE => ValueObjectInliner::inline([
new AnnotationToAttribute('Symfony\Component\Routing\Annotation\Route', null),
]),
]]);
};
↓
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;
}
}
ClassPropertyAssignToConstructorPromotionRector
Change simple property init and assign to constructor promotion
class SomeClass
{
- public float $someVariable;
-
- public function __construct(float $someVariable = 0.0)
+ public function __construct(private float $someVariable = 0.0)
{
- $this->someVariable = $someVariable;
}
}
DoctrineAnnotationClassToAttributeRector
Refactor Doctrine @annotation
annotated class to a PHP 8.0 attribute class
🔧 configure it!
use Rector\Php80\Rector\Class_\DoctrineAnnotationClassToAttributeRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DoctrineAnnotationClassToAttributeRector::class)
->call('configure', [[
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);
}
}
NullsafeOperatorRector
Change if null check with nullsafe operator ?-> with full short circuiting
class SomeClass
{
public function run($someObject)
{
- $someObject2 = $someObject->mayFail1();
- if ($someObject2 === null) {
- return null;
- }
-
- return $someObject2->mayFail2();
+ return $someObject->mayFail1()?->mayFail2();
}
}
OptionalParametersAfterRequiredRector
Move required parameters after optional ones
class SomeObject
{
- public function run($optional = 1, $required)
+ public function run($required, $optional = 1)
{
}
}
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
FinalizePublicClassConstantRector
Add final to constants that
class SomeClass
{
- public const NAME = 'value';
+ public final const NAME = 'value';
}
MyCLabsClassToEnumRector
Refactor MyCLabs enum class to native Enum
-use MyCLabs\Enum\Enum;
-
-final class Action extends Enum
+enum Action
{
- 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;
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
{
+ case draft = 'draft';
+ case published = 'published';
+ case archived = 'archived';
}
PhpSpecToPHPUnit
AddMockPropertiesRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
MockVariableToPropertyFetchRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecClassToPHPUnitClassRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecMethodToPHPUnitMethodRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecMocksToPHPUnitMocksRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecPromisesToPHPUnitAssertRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
RenameSpecFileToTestFileRector
Rename "*Spec.php" file to "*Test.php" file
-// tests/SomeSpec.php
+// tests/SomeTest.php
PostRector
ClassRenamingPostRector
Rename references for classes that were renamed during Rector run
-function (OriginalClass $someClass)
+function (RenamedClass $someClass)
{
}
NameImportingPostRector
Imports fully qualified names
+use App\AnotherClass;
+
class SomeClass
{
- public function run(App\AnotherClass $anotherClass)
+ public function run(AnotherClass $anotherClass)
{
}
}
NodeAddingPostRector
Add nodes on weird positions
class SomeClass
{
public function run($value)
{
- return 1;
+ if ($value) {
+ return 1;
+ }
}
}
NodeRemovingPostRector
Remove nodes from weird positions
class SomeClass
{
public function run($value)
{
- if ($value) {
- return 1;
- }
+ return 1;
}
}
NodeToReplacePostRector
Replaces nodes on weird positions
class SomeClass
{
public function run($value)
{
- return 1;
+ return $value;
}
}
PropertyAddingPostRector
Add dependency properties
class SomeClass
{
+ private $value;
public function run()
{
return $this->value;
}
}
UseAddingPostRector
Add unique use imports collected during Rector run
+use App\AnotherClass;
+
class SomeClass
{
public function run(AnotherClass $anotherClass)
{
}
}
Privatization
ChangeGlobalVariablesToPropertiesRector
Change global $variables
to private properties
class SomeClass
{
+ private $variable;
public function go()
{
- global $variable;
- $variable = 5;
+ $this->variable = 5;
}
public function run()
{
- global $variable;
- var_dump($variable);
+ var_dump($this->variable);
}
}
ChangeLocalPropertyToVariableRector
Change local property used in single method to local variable
class SomeClass
{
- private $count;
public function run()
{
- $this->count = 5;
- return $this->count;
+ $count = 5;
+ return $count;
}
}
ChangeReadOnlyPropertyWithDefaultValueToConstantRector
Change property with read only status with default value to constant
class SomeClass
{
/**
* @var string[]
*/
- private $magicMethods = [
+ private const MAGIC_METHODS = [
'__toString',
'__wakeup',
];
public function run()
{
- foreach ($this->magicMethods as $magicMethod) {
+ foreach (self::MAGIC_METHODS as $magicMethod) {
echo $magicMethod;
}
}
}
ChangeReadOnlyVariableWithDefaultValueToConstantRector
Change variable with read only status with default value to constant
class SomeClass
{
+ /**
+ * @var string[]
+ */
+ private const REPLACEMENTS = [
+ 'PHPUnit\Framework\TestCase\Notice' => 'expectNotice',
+ 'PHPUnit\Framework\TestCase\Deprecated' => 'expectDeprecation',
+ ];
+
public function run()
{
- $replacements = [
- 'PHPUnit\Framework\TestCase\Notice' => 'expectNotice',
- 'PHPUnit\Framework\TestCase\Deprecated' => 'expectDeprecation',
- ];
-
- foreach ($replacements as $class => $method) {
+ foreach (self::REPLACEMENTS as $class => $method) {
}
}
}
FinalizeClassesWithoutChildrenRector
Finalize every class that has no children
-class FirstClass
+final class FirstClass
{
}
class SecondClass
{
}
-class ThirdClass extends SecondClass
+final class ThirdClass extends SecondClass
{
}
PrivatizeFinalClassMethodRector
Change protected class method to private if possible
final class SomeClass
{
- protected function someMethod()
+ private function someMethod()
{
}
}
PrivatizeFinalClassPropertyRector
Change property to private if possible
final class SomeClass
{
- protected $value;
+ private $value;
}
PrivatizeLocalGetterToPropertyRector
Privatize getter of local property to property
class SomeClass
{
private $some;
public function run()
{
- return $this->getSome() + 5;
+ return $this->some + 5;
}
private function getSome()
{
return $this->some;
}
}
RepeatedLiteralToClassConstantRector
Replace repeated strings with constant
class SomeClass
{
+ /**
+ * @var string
+ */
+ private const REQUIRES = 'requires';
public function run($key, $items)
{
- if ($key === 'requires') {
- return $items['requires'];
+ if ($key === self::REQUIRES) {
+ return $items[self::REQUIRES];
}
}
}
ReplaceStringWithClassConstantRector
Replace string values in specific method call by constant of provided class
🔧 configure it!
use Rector\Privatization\Rector\MethodCall\ReplaceStringWithClassConstantRector;
use Rector\Privatization\ValueObject\ReplaceStringWithClassConstant;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReplaceStringWithClassConstantRector::class)
->call('configure', [[
ReplaceStringWithClassConstantRector::REPLACE_STRING_WITH_CLASS_CONSTANT => ValueObjectInliner::inline([
new ReplaceStringWithClassConstant('SomeClass', 'call', 0, 'Placeholder'),
]),
]]);
};
↓
class SomeClass
{
public function run()
{
- $this->call('name');
+ $this->call(Placeholder::NAME);
}
}
Removing
ArgumentRemoverRector
Removes defined arguments in defined methods and their calls.
🔧 configure it!
use Rector\Removing\Rector\ClassMethod\ArgumentRemoverRector;
use Rector\Removing\ValueObject\ArgumentRemover;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentRemoverRector::class)
->call('configure', [[
ArgumentRemoverRector::REMOVED_ARGUMENTS => ValueObjectInliner::inline([
new ArgumentRemover('ExampleClass', 'someMethod', 0, 'true'),
]),
]]);
};
↓
$someObject = new SomeClass;
-$someObject->someMethod(true);
+$someObject->someMethod();
RemoveFuncCallArgRector
Remove argument by position by function name
🔧 configure it!
use Rector\Removing\Rector\FuncCall\RemoveFuncCallArgRector;
use Rector\Removing\ValueObject\RemoveFuncCallArg;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveFuncCallArgRector::class)
->call('configure', [[
RemoveFuncCallArgRector::REMOVED_FUNCTION_ARGUMENTS => ValueObjectInliner::inline([
new RemoveFuncCallArg('remove_last_arg', 1),
]),
]]);
};
↓
-remove_last_arg(1, 2);
+remove_last_arg(1);
RemoveFuncCallRector
Remove ini_get by configuration
🔧 configure it!
use Rector\Removing\Rector\FuncCall\RemoveFuncCallRector;
use Rector\Removing\ValueObject\RemoveFuncCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveFuncCallRector::class)
->call('configure', [[
RemoveFuncCallRector::REMOVE_FUNC_CALLS => ValueObjectInliner::inline([
new RemoveFuncCall('ini_get', [['y2k_compliance']]), ]
),
]]);
};
↓
-ini_get('y2k_compliance');
ini_get('keep_me');
RemoveInterfacesRector
Removes interfaces usage from class.
🔧 configure it!
use Rector\Removing\Rector\Class_\RemoveInterfacesRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveInterfacesRector::class)
->call('configure', [[
RemoveInterfacesRector::INTERFACES_TO_REMOVE => ['SomeInterface'],
]]);
};
↓
-class SomeClass implements SomeInterface
+class SomeClass
{
}
RemoveParentRector
Removes extends class by name
🔧 configure it!
use Rector\Removing\Rector\Class_\RemoveParentRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveParentRector::class)
->call('configure', [[
RemoveParentRector::PARENT_TYPES_TO_REMOVE => ['SomeParentClass'],
]]);
};
↓
-final class SomeClass extends SomeParentClass
+final class SomeClass
{
}
RemoveTraitUseRector
Remove specific traits from code
🔧 configure it!
use Rector\Removing\Rector\Class_\RemoveTraitUseRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveTraitUseRector::class)
->call('configure', [[
RemoveTraitUseRector::TRAITS_TO_REMOVE => ['TraitNameToRemove'],
]]);
};
↓
class SomeClass
{
- use SomeTrait;
}
RemovingStatic
DesiredClassTypeToDynamicRector
Change full static service, to dynamic one
class AnotherClass
{
+ /**
+ * @var SomeClass
+ */
+ private $someClass;
+
+ public fuction __construct(SomeClass $someClass)
+ {
+ $this->someClass = $someClass;
+ }
+
public function run()
{
SomeClass::someStatic();
}
}
class SomeClass
{
- public static function run()
+ public function run()
{
- self::someStatic();
+ $this->someStatic();
}
- private static function someStatic()
+ private function someStatic()
{
}
}
DesiredPropertyClassMethodTypeToDynamicRector
Change defined static properties and methods to dynamic
final class SomeClass
{
- public static $name;
+ public $name;
- public static function go()
+ public function go()
{
}
}
DesiredStaticCallTypeToDynamicRector
Change defined static service to dynamic one
final class SomeClass
{
public function run()
{
- SomeStaticMethod::someStatic();
+ $this->someStaticMethod->someStatic();
}
}
DesiredStaticPropertyFetchTypeToDynamicRector
Change defined static service to dynamic one
- class:
Rector\RemovingStatic\Rector\StaticPropertyFetch\DesiredStaticPropertyFetchTypeToDynamicRector
final class SomeClass
{
public function run()
{
- SomeStaticMethod::$someStatic;
+ $this->someStaticMethod->someStatic;
}
}
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()
{
}
}
NewUniqueObjectToEntityFactoryRector
Convert new X to new factories
🔧 configure it!
use Rector\RemovingStatic\Rector\Class_\NewUniqueObjectToEntityFactoryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewUniqueObjectToEntityFactoryRector::class)
->call('configure', [[
NewUniqueObjectToEntityFactoryRector::TYPES_TO_SERVICES => ['ClassName'],
]]);
};
↓
class SomeClass
{
+ public function __construct(AnotherClassFactory $anotherClassFactory)
+ {
+ $this->anotherClassFactory = $anotherClassFactory;
+ }
+
public function run()
{
- return new AnotherClass;
+ return $this->anotherClassFactory->create();
}
}
class AnotherClass
{
public function someFun()
{
return StaticClass::staticMethod();
}
}
PassFactoryToUniqueObjectRector
Convert new X/Static::call()
to factories in entities, pass them via constructor to each other
🔧 configure it!
use Rector\RemovingStatic\Rector\Class_\PassFactoryToUniqueObjectRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PassFactoryToUniqueObjectRector::class)
->call('configure', [[
PassFactoryToUniqueObjectRector::TYPES_TO_SERVICES => ['StaticClass'],
]]);
};
↓
class SomeClass
{
+ public function __construct(AnotherClassFactory $anotherClassFactory)
+ {
+ $this->anotherClassFactory = $anotherClassFactory;
+ }
+
public function run()
{
- return new AnotherClass;
+ return $this->anotherClassFactory->create();
}
}
class AnotherClass
{
+ public function __construct(StaticClass $staticClass)
+ {
+ $this->staticClass = $staticClass;
+ }
+
public function someFun()
{
- return StaticClass::staticMethod();
+ return $this->staticClass->staticMethod();
+ }
+}
+
+final class AnotherClassFactory
+{
+ /**
+ * @var StaticClass
+ */
+ private $staticClass;
+
+ public function __construct(StaticClass $staticClass)
+ {
+ $this->staticClass = $staticClass;
+ }
+
+ public function create(): AnotherClass
+ {
+ return new AnotherClass($this->staticClass);
}
}
StaticTypeToSetterInjectionRector
Changes types to setter injection
🔧 configure it!
use Rector\RemovingStatic\Rector\Class_\StaticTypeToSetterInjectionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StaticTypeToSetterInjectionRector::class)
->call('configure', [[
StaticTypeToSetterInjectionRector::STATIC_TYPES => ['SomeStaticClass'],
]]);
};
↓
final class CheckoutEntityFactory
{
+ /**
+ * @var SomeStaticClass
+ */
+ private $someStaticClass;
+
+ public function setSomeStaticClass(SomeStaticClass $someStaticClass)
+ {
+ $this->someStaticClass = $someStaticClass;
+ }
+
public function run()
{
- return SomeStaticClass::go();
+ return $this->someStaticClass->go();
}
}
Renaming
PseudoNamespaceToNamespaceRector
Replaces defined Pseudo_Namespaces by Namespace\Ones.
🔧 configure it!
use Rector\Renaming\Rector\FileWithoutNamespace\PseudoNamespaceToNamespaceRector;
use Rector\Renaming\ValueObject\PseudoNamespaceToNamespace;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PseudoNamespaceToNamespaceRector::class)
->call('configure', [[
PseudoNamespaceToNamespaceRector::NAMESPACE_PREFIXES_WITH_EXCLUDED_CLASSES => ValueObjectInliner::inline([
new PseudoNamespaceToNamespace('Some_', ['Some_Class_To_Keep']), ]
),
]]);
};
↓
-/** @var Some_Chicken $someService */
-$someService = new Some_Chicken;
+/** @var Some\Chicken $someService */
+$someService = new Some\Chicken;
$someClassToKeep = new Some_Class_To_Keep;
RenameAnnotationRector
Turns defined annotations above properties and methods to their new values.
🔧 configure it!
use Rector\Renaming\Rector\ClassMethod\RenameAnnotationRector;
use Rector\Renaming\ValueObject\RenameAnnotation;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameAnnotationRector::class)
->call('configure', [[
RenameAnnotationRector::RENAMED_ANNOTATIONS_IN_TYPES => ValueObjectInliner::inline([
new RenameAnnotation('PHPUnit\Framework\TestCase', 'test', 'scenario'),
]),
]]);
};
↓
class SomeTest extends PHPUnit\Framework\TestCase
{
/**
- * @test
+ * @scenario
*/
public function someMethod()
{
}
}
RenameClassConstFetchRector
Replaces defined class constants in their calls.
🔧 configure it!
use Rector\Renaming\Rector\ClassConstFetch\RenameClassConstFetchRector;
use Rector\Renaming\ValueObject\RenameClassAndConstFetch;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameClassConstFetchRector::class)
->call('configure', [[
RenameClassConstFetchRector::CLASS_CONSTANT_RENAME => ValueObjectInliner::inline([
new RenameClassAndConstFetch('SomeClass', 'OTHER_OLD_CONSTANT', 'DifferentClass', 'NEW_CONSTANT'),
]),
]]);
};
↓
-$value = SomeClass::OLD_CONSTANT;
-$value = SomeClass::OTHER_OLD_CONSTANT;
+$value = SomeClass::NEW_CONSTANT;
+$value = DifferentClass::NEW_CONSTANT;
RenameClassRector
Replaces defined classes by new ones.
🔧 configure it!
use Rector\Renaming\Rector\Name\RenameClassRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameClassRector::class)
->call('configure', [[
RenameClassRector::OLD_TO_NEW_CLASSES => [
'App\SomeOldClass' => 'App\SomeNewClass',
], ]]);
};
↓
namespace App;
-use SomeOldClass;
+use SomeNewClass;
-function someFunction(SomeOldClass $someOldClass): SomeOldClass
+function someFunction(SomeNewClass $someOldClass): SomeNewClass
{
- if ($someOldClass instanceof SomeOldClass) {
- return new SomeOldClass;
+ if ($someOldClass instanceof SomeNewClass) {
+ return new SomeNewClass;
}
}
RenameConstantRector
Replace constant by new ones
🔧 configure it!
use Rector\Renaming\Rector\ConstFetch\RenameConstantRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameConstantRector::class)
->call('configure', [[
RenameConstantRector::OLD_TO_NEW_CONSTANTS => [
'MYSQL_ASSOC' => 'MYSQLI_ASSOC',
'OLD_CONSTANT' => 'NEW_CONSTANT',
], ]]);
};
↓
final class SomeClass
{
public function run()
{
- return MYSQL_ASSOC;
+ return MYSQLI_ASSOC;
}
}
RenameFunctionRector
Turns defined function call new one.
🔧 configure it!
use Rector\Renaming\Rector\FuncCall\RenameFunctionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameFunctionRector::class)
->call('configure', [[
RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [
'view' => 'Laravel\Templating\render',
], ]]);
};
↓
-view("...", []);
+Laravel\Templating\render("...", []);
RenameMethodRector
Turns method names to new ones.
🔧 configure it!
use Rector\Renaming\Rector\MethodCall\RenameMethodRector;
use Rector\Renaming\ValueObject\MethodCallRename;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameMethodRector::class)
->call('configure', [[
RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([
new MethodCallRename('SomeExampleClass', 'oldMethod', 'newMethod'),
]),
]]);
};
↓
$someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();
RenameNamespaceRector
Replaces old namespace by new one.
🔧 configure it!
use Rector\Renaming\Rector\Namespace_\RenameNamespaceRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameNamespaceRector::class)
->call('configure', [[
RenameNamespaceRector::OLD_TO_NEW_NAMESPACES => [
'SomeOldNamespace' => 'SomeNewNamespace',
], ]]);
};
↓
-$someObject = new SomeOldNamespace\SomeClass;
+$someObject = new SomeNewNamespace\SomeClass;
RenamePropertyRector
Replaces defined old properties by new ones.
🔧 configure it!
use Rector\Renaming\Rector\PropertyFetch\RenamePropertyRector;
use Rector\Renaming\ValueObject\RenameProperty;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenamePropertyRector::class)
->call('configure', [[
RenamePropertyRector::RENAMED_PROPERTIES => ValueObjectInliner::inline([
new RenameProperty('SomeClass', 'someOldProperty', 'someNewProperty'),
]),
]]);
};
↓
-$someObject->someOldProperty;
+$someObject->someNewProperty;
RenameStaticMethodRector
Turns method names to new ones.
🔧 configure it!
use Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector;
use Rector\Renaming\ValueObject\RenameStaticMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameStaticMethodRector::class)
->call('configure', [[
RenameStaticMethodRector::OLD_TO_NEW_METHODS_BY_CLASSES => ValueObjectInliner::inline([
new RenameStaticMethod('SomeClass', 'oldMethod', 'AnotherExampleClass', 'newStaticMethod'),
]),
]]);
};
↓
-SomeClass::oldStaticMethod();
+AnotherExampleClass::newStaticMethod();
use Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector;
use Rector\Renaming\ValueObject\RenameStaticMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameStaticMethodRector::class)
->call('configure', [[
RenameStaticMethodRector::OLD_TO_NEW_METHODS_BY_CLASSES => ValueObjectInliner::inline([
new RenameStaticMethod('SomeClass', 'oldMethod', 'SomeClass', 'newStaticMethod'),
]),
]]);
};
↓
-SomeClass::oldStaticMethod();
+SomeClass::newStaticMethod();
RenameStringRector
Change string value
🔧 configure it!
use Rector\Renaming\Rector\String_\RenameStringRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameStringRector::class)
->call('configure', [[
RenameStringRector::STRING_CHANGES => [
'ROLE_PREVIOUS_ADMIN' => 'IS_IMPERSONATOR',
], ]]);
};
↓
class SomeClass
{
public function run()
{
- return 'ROLE_PREVIOUS_ADMIN';
+ return 'IS_IMPERSONATOR';
}
}
Restoration
CompleteImportForPartialAnnotationRector
In case you have accidentally removed use imports but code still contains partial use statements, this will save you
🔧 configure it!
use Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector;
use Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(CompleteImportForPartialAnnotationRector::class)
->call('configure', [[
CompleteImportForPartialAnnotationRector::USE_IMPORTS_TO_RESTORE => ValueObjectInliner::inline([
new CompleteImportForPartialAnnotation('Doctrine\ORM\Mapping', 'ORM'),
]),
]]);
};
↓
+use Doctrine\ORM\Mapping as ORM;
+
class SomeClass
{
/**
* @ORM\Id
*/
public $id;
}
InferParamFromClassMethodReturnRector
Change @param
doc based on another method return type
🔧 configure it!
use Rector\Restoration\Rector\ClassMethod\InferParamFromClassMethodReturnRector;
use Rector\Restoration\ValueObject\InferParamFromClassMethodReturn;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(InferParamFromClassMethodReturnRector::class)
->call('configure', [[
InferParamFromClassMethodReturnRector::INFER_PARAMS_FROM_CLASS_METHOD_RETURNS => ValueObjectInliner::inline([
new InferParamFromClassMethodReturn('SomeClass', 'process', 'getNodeTypes'),
]),
]]);
};
↓
class SomeClass
{
public function getNodeTypes(): array
{
return [String_::class];
}
+ /**
+ * @param String_ $node
+ */
public function process(Node $node)
{
}
}
MakeTypedPropertyNullableIfCheckedRector
Make typed property nullable if checked
final class SomeClass
{
- private AnotherClass $anotherClass;
+ private ?AnotherClass $anotherClass = null;
public function run()
{
if ($this->anotherClass === null) {
$this->anotherClass = new AnotherClass;
}
}
}
MissingClassConstantReferenceToStringRector
Convert missing class reference to string
class SomeClass
{
public function run()
{
- return NonExistingClass::class;
+ return 'NonExistingClass';
}
}
RemoveFinalFromEntityRector
Remove final from Doctrine entities
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
-final class SomeClass
+class SomeClass
{
}
UpdateFileNameByClassNameFileSystemRector
Rename file to respect class name
-// app/SomeClass.php
+// app/AnotherClass.php
class AnotherClass
{
}
Transform
AddInterfaceByParentRector
Add interface by parent
🔧 configure it!
use Rector\Transform\Rector\Class_\AddInterfaceByParentRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddInterfaceByParentRector::class)
->call('configure', [[
AddInterfaceByParentRector::INTERFACE_BY_PARENT => [
'SomeParent' => 'SomeInterface',
], ]]);
};
↓
-class SomeClass extends SomeParent
+class SomeClass extends SomeParent implements SomeInterface
{
}
AddInterfaceByTraitRector
Add interface by used trait
🔧 configure it!
use Rector\Transform\Rector\Class_\AddInterfaceByTraitRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddInterfaceByTraitRector::class)
->call('configure', [[
AddInterfaceByTraitRector::INTERFACE_BY_TRAIT => [
'SomeTrait' => 'SomeInterface',
], ]]);
};
↓
-class SomeClass
+class SomeClass implements SomeInterface
{
use SomeTrait;
}
ArgumentFuncCallToMethodCallRector
Move help facade-like function calls to constructor injection
🔧 configure it!
use Rector\Transform\Rector\FuncCall\ArgumentFuncCallToMethodCallRector;
use Rector\Transform\ValueObject\ArgumentFuncCallToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentFuncCallToMethodCallRector::class)
->call('configure', [[
ArgumentFuncCallToMethodCallRector::FUNCTIONS_TO_METHOD_CALLS => ValueObjectInliner::inline([
new ArgumentFuncCallToMethodCall('view', 'Illuminate\Contracts\View\Factory', 'make', null),
]),
]]);
};
↓
class SomeController
{
+ /**
+ * @var \Illuminate\Contracts\View\Factory
+ */
+ private $viewFactory;
+
+ public function __construct(\Illuminate\Contracts\View\Factory $viewFactory)
+ {
+ $this->viewFactory = $viewFactory;
+ }
+
public function action()
{
- $template = view('template.blade');
- $viewFactory = view();
+ $template = $this->viewFactory->make('template.blade');
+ $viewFactory = $this->viewFactory;
}
}
CallableInMethodCallToVariableRector
Change a callable in method call to standalone variable assign
🔧 configure it!
use Rector\Transform\Rector\MethodCall\CallableInMethodCallToVariableRector;
use Rector\Transform\ValueObject\CallableInMethodCallToVariable;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(CallableInMethodCallToVariableRector::class)
->call('configure', [[
CallableInMethodCallToVariableRector::CALLABLE_IN_METHOD_CALL_TO_VARIABLE => ValueObjectInliner::inline([
new CallableInMethodCallToVariable('Nette\Caching\Cache', 'save', 1),
]),
]]);
};
↓
final class SomeClass
{
public function run()
{
/** @var \Nette\Caching\Cache $cache */
- $cache->save($key, function () use ($container) {
- return 100;
- });
+ $result = 100;
+ $cache->save($key, $result);
}
}
ChangeSingletonToServiceRector
Change singleton class to normal class that can be registered as a service
class SomeClass
{
- private static $instance;
-
- private function __construct()
+ public function __construct()
{
- }
-
- public static function getInstance()
- {
- if (null === static::$instance) {
- static::$instance = new static();
- }
-
- return static::$instance;
}
}
ClassConstFetchToValueRector
Replaces constant by value
🔧 configure it!
use Rector\Transform\Rector\ClassConstFetch\ClassConstFetchToValueRector;
use Rector\Transform\ValueObject\ClassConstFetchToValue;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ClassConstFetchToValueRector::class)
->call('configure', [[
ClassConstFetchToValueRector::CLASS_CONST_FETCHES_TO_VALUES => ValueObjectInliner::inline([
new ClassConstFetchToValue('Nette\Configurator', 'PRODUCTION', 'production'),
]),
]]);
};
↓
-$value === Nette\Configurator::DEVELOPMENT
+$value === "development"
DimFetchAssignToMethodCallRector
Change magic array access add to $list[],
to explicit $list->addMethod(...)
🔧 configure it!
use Rector\Transform\Rector\Assign\DimFetchAssignToMethodCallRector;
use Rector\Transform\ValueObject\DimFetchAssignToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DimFetchAssignToMethodCallRector::class)
->call('configure', [[
DimFetchAssignToMethodCallRector::DIM_FETCH_ASSIGN_TO_METHOD_CALL => ValueObjectInliner::inline([
new DimFetchAssignToMethodCall(
'Nette\Application\Routers\RouteList',
'Nette\Application\Routers\Route',
'addRoute'
),
]),
]]);
};
↓
-use Nette\Application\Routers\Route;
use Nette\Application\Routers\RouteList;
class RouterFactory
{
public static function createRouter()
{
$routeList = new RouteList();
- $routeList[] = new Route('...');
+ $routeList->addRoute('...');
}
}
FuncCallToConstFetchRector
Changes use of function calls to use constants
🔧 configure it!
use Rector\Transform\Rector\FuncCall\FuncCallToConstFetchRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(FuncCallToConstFetchRector::class)
->call('configure', [[
FuncCallToConstFetchRector::FUNCTIONS_TO_CONSTANTS => [
'php_sapi_name' => 'PHP_SAPI',
], ]]);
};
↓
class SomeClass
{
public function run()
{
- $value = php_sapi_name();
+ $value = PHP_SAPI;
}
}
FuncCallToMethodCallRector
Turns defined function calls to local method calls.
🔧 configure it!
use Rector\Transform\Rector\FuncCall\FuncCallToMethodCallRector;
use Rector\Transform\ValueObject\FuncCallToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(FuncCallToMethodCallRector::class)
->call('configure', [[
FuncCallToMethodCallRector::FUNC_CALL_TO_CLASS_METHOD_CALL => ValueObjectInliner::inline([
new FuncCallToMethodCall('view', 'Namespaced\SomeRenderer', 'render'),
]),
]]);
};
↓
class SomeClass
{
+ /**
+ * @var \Namespaced\SomeRenderer
+ */
+ private $someRenderer;
+
+ public function __construct(\Namespaced\SomeRenderer $someRenderer)
+ {
+ $this->someRenderer = $someRenderer;
+ }
+
public function run()
{
- view('...');
+ $this->someRenderer->view('...');
}
}
FuncCallToNewRector
Change configured function calls to new Instance
🔧 configure it!
use Rector\Transform\Rector\FuncCall\FuncCallToNewRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(FuncCallToNewRector::class)
->call('configure', [[
FuncCallToNewRector::FUNCTIONS_TO_NEWS => [
'collection' => ['Collection'],
], ]]);
};
↓
class SomeClass
{
public function run()
{
- $array = collection([]);
+ $array = new \Collection([]);
}
}
FuncCallToStaticCallRector
Turns defined function call to static method call.
🔧 configure it!
use Rector\Transform\Rector\FuncCall\FuncCallToStaticCallRector;
use Rector\Transform\ValueObject\FuncCallToStaticCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(FuncCallToStaticCallRector::class)
->call('configure', [[
FuncCallToStaticCallRector::FUNC_CALLS_TO_STATIC_CALLS => ValueObjectInliner::inline([
new FuncCallToStaticCall('view', 'SomeStaticClass', 'render'),
]),
]]);
};
↓
-view("...", []);
+SomeClass::render("...", []);
GetAndSetToMethodCallRector
Turns defined __get
/__set
to specific method calls.
🔧 configure it!
use Rector\Transform\Rector\Assign\GetAndSetToMethodCallRector;
use Rector\Transform\ValueObject\GetAndSetToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(GetAndSetToMethodCallRector::class)
->call('configure', [[
GetAndSetToMethodCallRector::TYPE_TO_METHOD_CALLS => ValueObjectInliner::inline([
new GetAndSetToMethodCall('SomeContainer', 'addService', 'getService'),
]),
]]);
};
↓
$container = new SomeContainer;
-$container->someService = $someService;
+$container->setService("someService", $someService);
MergeInterfacesRector
Merges old interface to a new one, that already has its methods
🔧 configure it!
use Rector\Transform\Rector\Class_\MergeInterfacesRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MergeInterfacesRector::class)
->call('configure', [[
MergeInterfacesRector::OLD_TO_NEW_INTERFACES => [
'SomeOldInterface' => 'SomeInterface',
], ]]);
};
↓
-class SomeClass implements SomeInterface, SomeOldInterface
+class SomeClass implements SomeInterface
{
}
MethodCallToAnotherMethodCallWithArgumentsRector
Turns old method call with specific types to new one with arguments
🔧 configure it!
use Rector\Transform\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector;
use Rector\Transform\ValueObject\MethodCallToAnotherMethodCallWithArguments;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MethodCallToAnotherMethodCallWithArgumentsRector::class)
->call('configure', [[
MethodCallToAnotherMethodCallWithArgumentsRector::METHOD_CALL_RENAMES_WITH_ADDED_ARGUMENTS => ValueObjectInliner::inline([
new MethodCallToAnotherMethodCallWithArguments('Nette\DI\ServiceDefinition', 'setInject', 'addTag', [
'inject',
]), ]
),
]]);
};
↓
$serviceDefinition = new Nette\DI\ServiceDefinition;
-$serviceDefinition->setInject();
+$serviceDefinition->addTag('inject');
MethodCallToMethodCallRector
Change method one method from one service to a method call to in another service
🔧 configure it!
use Rector\Transform\Rector\MethodCall\MethodCallToMethodCallRector;
use Rector\Transform\ValueObject\MethodCallToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MethodCallToMethodCallRector::class)
->call('configure', [[
MethodCallToMethodCallRector::METHOD_CALLS_TO_METHOD_CALLS => ValueObjectInliner::inline([
new MethodCallToMethodCall('FirstDependency', 'go', 'SecondDependency', 'away'),
]),
]]);
};
↓
class SomeClass
{
public function __construct(
- private FirstDependency $firstDependency
+ private SecondDependency $secondDependency
) {
}
public function run()
{
- $this->firstDependency->go();
+ $this->secondDependency->away();
}
}
MethodCallToPropertyFetchRector
Turns method call "$this->something()"
to property fetch "$this->something"
🔧 configure it!
use Rector\Transform\Rector\MethodCall\MethodCallToPropertyFetchRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MethodCallToPropertyFetchRector::class)
->call('configure', [[
MethodCallToPropertyFetchRector::METHOD_CALL_TO_PROPERTY_FETCHES => [
'someMethod' => 'someProperty',
], ]]);
};
↓
class SomeClass
{
public function run()
{
- $this->someMethod();
+ $this->someProperty;
}
}
MethodCallToStaticCallRector
Change method call to desired static call
🔧 configure it!
use Rector\Transform\Rector\MethodCall\MethodCallToStaticCallRector;
use Rector\Transform\ValueObject\MethodCallToStaticCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MethodCallToStaticCallRector::class)
->call('configure', [[
MethodCallToStaticCallRector::METHOD_CALLS_TO_STATIC_CALLS => ValueObjectInliner::inline([
new MethodCallToStaticCall('AnotherDependency', 'process', 'StaticCaller', 'anotherMethod'),
]),
]]);
};
↓
final class SomeClass
{
private $anotherDependency;
public function __construct(AnotherDependency $anotherDependency)
{
$this->anotherDependency = $anotherDependency;
}
public function loadConfiguration()
{
- return $this->anotherDependency->process('value');
+ return StaticCaller::anotherMethod('value');
}
}
NewArgToMethodCallRector
Change new with specific argument to method call
🔧 configure it!
use Rector\Transform\Rector\New_\NewArgToMethodCallRector;
use Rector\Transform\ValueObject\NewArgToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewArgToMethodCallRector::class)
->call('configure', [[
NewArgToMethodCallRector::NEW_ARGS_TO_METHOD_CALLS => ValueObjectInliner::inline([
new NewArgToMethodCall('Dotenv', true, 'usePutenv'),
]),
]]);
};
↓
class SomeClass
{
public function run()
{
- $dotenv = new Dotenv(true);
+ $dotenv = new Dotenv();
+ $dotenv->usePutenv();
}
}
NewToConstructorInjectionRector
Change defined new type to constructor injection
🔧 configure it!
use Rector\Transform\Rector\New_\NewToConstructorInjectionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewToConstructorInjectionRector::class)
->call('configure', [[
NewToConstructorInjectionRector::TYPES_TO_CONSTRUCTOR_INJECTION => ['Validator'],
]]);
};
↓
class SomeClass
{
+ /**
+ * @var Validator
+ */
+ private $validator;
+
+ public function __construct(Validator $validator)
+ {
+ $this->validator = $validator;
+ }
+
public function run()
{
- $validator = new Validator();
- $validator->validate(1000);
+ $this->validator->validate(1000);
}
}
NewToMethodCallRector
Replaces creating object instances with "new" keyword with factory method.
🔧 configure it!
use Rector\Transform\Rector\New_\NewToMethodCallRector;
use Rector\Transform\ValueObject\NewToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewToMethodCallRector::class)
->call('configure', [[
NewToMethodCallRector::NEWS_TO_METHOD_CALLS => ValueObjectInliner::inline([
new NewToMethodCall('MyClass', 'MyClassFactory', 'create'),
]),
]]);
};
↓
class SomeClass
{
+ /**
+ * @var \MyClassFactory
+ */
+ private $myClassFactory;
+
public function example() {
- new MyClass($argument);
+ $this->myClassFactory->create($argument);
}
}
NewToStaticCallRector
Change new Object to static call
🔧 configure it!
use Rector\Transform\Rector\New_\NewToStaticCallRector;
use Rector\Transform\ValueObject\NewToStaticCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewToStaticCallRector::class)
->call('configure', [[
NewToStaticCallRector::TYPE_TO_STATIC_CALLS => ValueObjectInliner::inline([
new NewToStaticCall('Cookie', 'Cookie', 'create'),
]),
]]);
};
↓
class SomeClass
{
public function run()
{
- new Cookie($name);
+ Cookie::create($name);
}
}
ParentClassToTraitsRector
Replaces parent class to specific traits
🔧 configure it!
use Rector\Transform\Rector\Class_\ParentClassToTraitsRector;
use Rector\Transform\ValueObject\ParentClassToTraits;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ParentClassToTraitsRector::class)
->call('configure', [[
ParentClassToTraitsRector::PARENT_CLASS_TO_TRAITS => ValueObjectInliner::inline([
new ParentClassToTraits('Nette\Object', ['Nette\SmartObject']), ]
),
]]);
};
↓
-class SomeClass extends Nette\Object
+class SomeClass
{
+ use Nette\SmartObject;
}
PropertyAssignToMethodCallRector
Turns property assign of specific type and property name to method call
🔧 configure it!
use Rector\Transform\Rector\Assign\PropertyAssignToMethodCallRector;
use Rector\Transform\ValueObject\PropertyAssignToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PropertyAssignToMethodCallRector::class)
->call('configure', [[
PropertyAssignToMethodCallRector::PROPERTY_ASSIGNS_TO_METHODS_CALLS => ValueObjectInliner::inline([
new PropertyAssignToMethodCall('SomeClass', 'oldProperty', 'newMethodCall'),
]),
]]);
};
↓
$someObject = new SomeClass;
-$someObject->oldProperty = false;
+$someObject->newMethodCall(false);
PropertyFetchToMethodCallRector
Replaces properties assign calls be defined methods.
🔧 configure it!
use Rector\Transform\Rector\Assign\PropertyFetchToMethodCallRector;
use Rector\Transform\ValueObject\PropertyFetchToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PropertyFetchToMethodCallRector::class)
->call('configure', [[
PropertyFetchToMethodCallRector::PROPERTIES_TO_METHOD_CALLS => ValueObjectInliner::inline([
new PropertyFetchToMethodCall('SomeObject', 'property', 'getProperty', 'setProperty', []), ]
),
]]);
};
↓
-$result = $object->property;
-$object->property = $value;
+$result = $object->getProperty();
+$object->setProperty($value);
use Rector\Transform\Rector\Assign\PropertyFetchToMethodCallRector;
use Rector\Transform\ValueObject\PropertyFetchToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PropertyFetchToMethodCallRector::class)
->call('configure', [[
PropertyFetchToMethodCallRector::PROPERTIES_TO_METHOD_CALLS => ValueObjectInliner::inline([
new PropertyFetchToMethodCall('SomeObject', 'property', 'getConfig', null, ['someArg']), ]
),
]]);
};
↓
-$result = $object->property;
+$result = $object->getProperty('someArg');
ReplaceParentCallByPropertyCallRector
Changes method calls in child of specific types to defined property method call
🔧 configure it!
use Rector\Transform\Rector\MethodCall\ReplaceParentCallByPropertyCallRector;
use Rector\Transform\ValueObject\ReplaceParentCallByPropertyCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReplaceParentCallByPropertyCallRector::class)
->call('configure', [[
ReplaceParentCallByPropertyCallRector::PARENT_CALLS_TO_PROPERTIES => ValueObjectInliner::inline([
new ReplaceParentCallByPropertyCall('SomeTypeToReplace', 'someMethodCall', 'someProperty'),
]),
]]);
};
↓
final class SomeClass
{
public function run(SomeTypeToReplace $someTypeToReplace)
{
- $someTypeToReplace->someMethodCall();
+ $this->someProperty->someMethodCall();
}
}
ServiceGetterToConstructorInjectionRector
Get service call to constructor injection
🔧 configure it!
use Rector\Transform\Rector\MethodCall\ServiceGetterToConstructorInjectionRector;
use Rector\Transform\ValueObject\ServiceGetterToConstructorInjection;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ServiceGetterToConstructorInjectionRector::class)
->call('configure', [[
ServiceGetterToConstructorInjectionRector::METHOD_CALL_TO_SERVICES => ValueObjectInliner::inline([
new ServiceGetterToConstructorInjection('FirstService', 'getAnotherService', 'AnotherService'),
]),
]]);
};
↓
final class SomeClass
{
/**
* @var FirstService
*/
private $firstService;
- public function __construct(FirstService $firstService)
- {
- $this->firstService = $firstService;
- }
-
- public function run()
- {
- $anotherService = $this->firstService->getAnotherService();
- $anotherService->run();
- }
-}
-
-class FirstService
-{
/**
* @var AnotherService
*/
private $anotherService;
- public function __construct(AnotherService $anotherService)
+ public function __construct(FirstService $firstService, AnotherService $anotherService)
{
+ $this->firstService = $firstService;
$this->anotherService = $anotherService;
}
- public function getAnotherService(): AnotherService
+ public function run()
{
- return $this->anotherService;
+ $anotherService = $this->anotherService;
+ $anotherService->run();
}
}
SingleToManyMethodRector
Change method that returns single value to multiple values
🔧 configure it!
use Rector\Transform\Rector\ClassMethod\SingleToManyMethodRector;
use Rector\Transform\ValueObject\SingleToManyMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SingleToManyMethodRector::class)
->call('configure', [[
SingleToManyMethodRector::SINGLES_TO_MANY_METHODS => ValueObjectInliner::inline([
new SingleToManyMethod('SomeClass', 'getNode', 'getNodes'),
]),
]]);
};
↓
class SomeClass
{
- public function getNode(): string
+ /**
+ * @return string[]
+ */
+ public function getNodes(): array
{
- return 'Echo_';
+ return ['Echo_'];
}
}
StaticCallToFuncCallRector
Turns static call to function call.
🔧 configure it!
use Rector\Transform\Rector\StaticCall\StaticCallToFuncCallRector;
use Rector\Transform\ValueObject\StaticCallToFuncCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StaticCallToFuncCallRector::class)
->call('configure', [[
StaticCallToFuncCallRector::STATIC_CALLS_TO_FUNCTIONS => ValueObjectInliner::inline([
new StaticCallToFuncCall('OldClass', 'oldMethod', 'new_function'),
]),
]]);
};
↓
-OldClass::oldMethod("args");
+new_function("args");
StaticCallToMethodCallRector
Change static call to service method via constructor injection
🔧 configure it!
use Rector\Transform\Rector\StaticCall\StaticCallToMethodCallRector;
use Rector\Transform\ValueObject\StaticCallToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StaticCallToMethodCallRector::class)
->call('configure', [[
StaticCallToMethodCallRector::STATIC_CALLS_TO_METHOD_CALLS => ValueObjectInliner::inline([
new StaticCallToMethodCall(
'Nette\Utils\FileSystem',
'write',
'Symplify\SmartFileSystem\SmartFileSystem',
'dumpFile'
),
]),
]]);
};
↓
-use Nette\Utils\FileSystem;
+use Symplify\SmartFileSystem\SmartFileSystem;
class SomeClass
{
+ /**
+ * @var SmartFileSystem
+ */
+ private $smartFileSystem;
+
+ public function __construct(SmartFileSystem $smartFileSystem)
+ {
+ $this->smartFileSystem = $smartFileSystem;
+ }
+
public function run()
{
- return FileSystem::write('file', 'content');
+ return $this->smartFileSystem->dumpFile('file', 'content');
}
}
StaticCallToNewRector
Change static call to new instance
🔧 configure it!
use Rector\Transform\Rector\StaticCall\StaticCallToNewRector;
use Rector\Transform\ValueObject\StaticCallToNew;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StaticCallToNewRector::class)
->call('configure', [[
StaticCallToNewRector::STATIC_CALLS_TO_NEWS => ValueObjectInliner::inline([
new StaticCallToNew('JsonResponse', 'create'),
]),
]]);
};
↓
class SomeClass
{
public function run()
{
- $dotenv = JsonResponse::create(true);
+ $dotenv = new JsonResponse();
}
}
StringToClassConstantRector
Changes strings to specific constants
🔧 configure it!
use Rector\Transform\Rector\String_\StringToClassConstantRector;
use Rector\Transform\ValueObject\StringToClassConstant;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StringToClassConstantRector::class)
->call('configure', [[
StringToClassConstantRector::STRINGS_TO_CLASS_CONSTANTS => ValueObjectInliner::inline([
new StringToClassConstant('compiler.post_dump', 'Yet\AnotherClass', 'CONSTANT'),
]),
]]);
};
↓
final class SomeSubscriber
{
public static function getSubscribedEvents()
{
- return ['compiler.post_dump' => 'compile'];
+ return [\Yet\AnotherClass::CONSTANT => 'compile'];
}
}
ToStringToMethodCallRector
Turns defined code uses of "__toString()"
method to specific method calls.
🔧 configure it!
use Rector\Transform\Rector\String_\ToStringToMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ToStringToMethodCallRector::class)
->call('configure', [[
ToStringToMethodCallRector::METHOD_NAMES_BY_TYPE => [
'SomeObject' => 'getPath',
], ]]);
};
↓
$someValue = new SomeObject;
-$result = (string) $someValue;
-$result = $someValue->__toString();
+$result = $someValue->getPath();
+$result = $someValue->getPath();
UnsetAndIssetToMethodCallRector
Turns defined __isset
/__unset
calls to specific method calls.
🔧 configure it!
use Rector\Transform\Rector\Isset_\UnsetAndIssetToMethodCallRector;
use Rector\Transform\ValueObject\UnsetAndIssetToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(UnsetAndIssetToMethodCallRector::class)
->call('configure', [[
UnsetAndIssetToMethodCallRector::ISSET_UNSET_TO_METHOD_CALL => ValueObjectInliner::inline([
new UnsetAndIssetToMethodCall('SomeContainer', 'hasService', 'removeService'),
]),
]]);
};
↓
$container = new SomeContainer;
-isset($container["someKey"]);
-unset($container["someKey"]);
+$container->hasService("someKey");
+$container->removeService("someKey");
WrapReturnRector
Wrap return value of specific method
🔧 configure it!
use Rector\Transform\Rector\ClassMethod\WrapReturnRector;
use Rector\Transform\ValueObject\WrapReturn;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(WrapReturnRector::class)
->call('configure', [[
WrapReturnRector::TYPE_METHOD_WRAPS => ValueObjectInliner::inline([
new WrapReturn('SomeClass', 'getItem', true),
]),
]]);
};
↓
final class SomeClass
{
public function getItem()
{
- return 1;
+ return [1];
}
}
TypeDeclaration
AddArrayParamDocTypeRector
Adds @param
annotation to array parameters inferred from the rest of the code
class SomeClass
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @param int[] $values
+ */
public function __construct(array $values)
{
$this->values = $values;
}
}
AddArrayReturnDocTypeRector
Adds @return
annotation to array parameters inferred from the rest of the code
class SomeClass
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @return int[]
+ */
public function getValues(): array
{
return $this->values;
}
}
AddClosureReturnTypeRector
Add known return type to functions
class SomeClass
{
public function run($meetups)
{
- return array_filter($meetups, function (Meetup $meetup) {
+ return array_filter($meetups, function (Meetup $meetup): bool {
return is_object($meetup);
});
}
}
AddMethodCallBasedStrictParamTypeRector
Change param type to strict type of passed expression
🔧 configure it!
use Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddMethodCallBasedStrictParamTypeRector::class)
->call('configure', [[
AddMethodCallBasedStrictParamTypeRector::TRUST_DOC_BLOCKS => false,
]]);
};
↓
class SomeClass
{
- public function getById($id)
+ public function getById(int $id)
{
}
}
class CallerClass
{
public function run(SomeClass $someClass)
{
$someClass->getById($this->getId());
}
public function getId(): int
{
return 1000;
}
}
AddParamTypeDeclarationRector
Add param types where needed
🔧 configure it!
use PHPStan\Type\StringType;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector;
use Rector\TypeDeclaration\ValueObject\AddParamTypeDeclaration;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddParamTypeDeclarationRector::class)
->call('configure', [[
AddParamTypeDeclarationRector::PARAMETER_TYPEHINTS => ValueObjectInliner::inline([
new AddParamTypeDeclaration('SomeClass', 'process', 0, new StringType()),
]),
]]);
};
↓
class SomeClass
{
- public function process($name)
+ public function process(string $name)
{
}
}
AddReturnTypeDeclarationRector
Changes defined return typehint of method and class.
🔧 configure it!
use PHPStan\Type\ArrayType;
use PHPStan\Type\MixedType;
use Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector;
use Rector\TypeDeclaration\ValueObject\AddReturnTypeDeclaration;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddReturnTypeDeclarationRector::class)
->call('configure', [[
AddReturnTypeDeclarationRector::METHOD_RETURN_TYPES => ValueObjectInliner::inline([
new AddReturnTypeDeclaration('SomeClass', 'getData', new ArrayType(new MixedType(
false,
null
), new MixedType(
false,
null
))),
]),
]]);
};
↓
class SomeClass
{
- public function getData()
+ public function getData(): array
{
}
}
AddVoidReturnTypeWhereNoReturnRector
Add return type void to function like without any return
final class SomeClass
{
- public function getValues()
+ public function getValues(): void
{
$value = 1000;
return;
}
}
CompleteVarDocTypePropertyRector
Complete property @var
annotations or correct the old ones
final class SomeClass
{
+ /**
+ * @var EventDispatcher
+ */
private $eventDispatcher;
public function __construct(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
}
FormerNullableArgumentToScalarTypedRector
Change null in argument, that is now not nullable anymore
final class SomeClass
{
public function run()
{
- $this->setValue(null);
+ $this->setValue('');
}
public function setValue(string $value)
{
}
}
ParamTypeByMethodCallTypeRector
Change param type based on passed method call type
class SomeTypedService
{
public function run(string $name)
{
}
}
final class UseDependency
{
public function __construct(
private SomeTypedService $someTypedService
) {
}
- public function go($value)
+ public function go(string $value)
{
$this->someTypedService->run($value);
}
}
ParamTypeByParentCallTypeRector
Change param type based on parent param type
class SomeControl
{
public function __construct(string $name)
{
}
}
class VideoControl extends SomeControl
{
- public function __construct($name)
+ public function __construct(string $name)
{
parent::__construct($name);
}
}
ParamTypeDeclarationRector
Change @param
types to type declarations if not a BC-break
abstract class VendorParentClass
{
/**
* @param int $number
*/
public function keep($number)
{
}
}
final class ChildClass extends VendorParentClass
{
/**
* @param int $number
*/
public function keep($number)
{
}
- /**
- * @param int $number
- */
- public function change($number)
+ public function change(int $number)
{
}
}
ParamTypeFromStrictTypedPropertyRector
Add param type from $param
set to typed property
final class SomeClass
{
private int $age;
- public function setAge($age)
+ public function setAge(int $age)
{
$this->age = $age;
}
}
PropertyTypeDeclarationRector
Add @var
to properties that are missing it
class SomeClass
{
+ /**
+ * @var int
+ */
private $value;
public function run()
{
$this->value = 123;
}
}
ReturnNeverTypeRector
Add "never" return-type for methods that never return anything
final class SomeClass
{
+ /**
+ * @return never
+ */
public function run()
{
throw new InvalidException();
}
}
ReturnTypeDeclarationRector
Change @return
types and type from static analysis to type declarations if not a BC-break
class SomeClass
{
- /**
- * @return int
- */
- public function getCount()
+ public function getCount(): int
{
}
}
ReturnTypeFromReturnNewRector
Add return type to function like with return new
final class SomeClass
{
- public function action()
+ public function action(): Response
{
return new Response();
}
}
ReturnTypeFromStrictTypedCallRector
Add return type from strict return type of call
final class SomeClass
{
- public function getData()
+ public function getData(): int
{
return $this->getNumber();
}
private function getNumber(): int
{
return 1000;
}
}
ReturnTypeFromStrictTypedPropertyRector
Add return method return type based on strict typed property
final class SomeClass
{
private int $age = 100;
- public function getAge()
+ public function getAge(): int
{
return $this->age;
}
}
TypedPropertyFromStrictConstructorRector
Add typed properties based only on strict constructor types
class SomeObject
{
- private $name;
+ private string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
Visibility
ChangeConstantVisibilityRector
Change visibility of constant from parent class.
🔧 configure it!
use Rector\Visibility\Rector\ClassConst\ChangeConstantVisibilityRector;
use Rector\Visibility\ValueObject\ChangeConstantVisibility;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangeConstantVisibilityRector::class)
->call('configure', [[
ChangeConstantVisibilityRector::CLASS_CONSTANT_VISIBILITY_CHANGES => ValueObjectInliner::inline([
new ChangeConstantVisibility('ParentObject', 'SOME_CONSTANT', 2),
]),
]]);
};
↓
class FrameworkClass
{
protected const SOME_CONSTANT = 1;
}
class MyClass extends FrameworkClass
{
- public const SOME_CONSTANT = 1;
+ protected const SOME_CONSTANT = 1;
}
ChangeMethodVisibilityRector
Change visibility of method from parent class.
🔧 configure it!
use Rector\Visibility\Rector\ClassMethod\ChangeMethodVisibilityRector;
use Rector\Visibility\ValueObject\ChangeMethodVisibility;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangeMethodVisibilityRector::class)
->call('configure', [[
ChangeMethodVisibilityRector::METHOD_VISIBILITIES => ValueObjectInliner::inline([
new ChangeMethodVisibility('FrameworkClass', 'someMethod', 2),
]),
]]);
};
↓
class FrameworkClass
{
protected function someMethod()
{
}
}
class MyClass extends FrameworkClass
{
- public function someMethod()
+ protected function someMethod()
{
}
}