rector/docs/rector_rules_overview.md

16696 lines
401 KiB
Markdown
Raw Normal View History

# 656 Rules Overview
<br>
2020-02-13 13:42:40 +00:00
## Categories
2020-02-13 13:42:40 +00:00
- [Arguments](#arguments) (3)
- [Autodiscovery](#autodiscovery) (4)
2020-02-13 13:42:40 +00:00
- [CakePHP](#cakephp) (6)
- [Carbon](#carbon) (2)
2020-02-13 13:42:40 +00:00
2021-01-25 18:59:06 +00:00
- [CodeQuality](#codequality) (65)
2020-02-13 13:42:40 +00:00
- [CodeQualityStrict](#codequalitystrict) (4)
2020-02-13 13:42:40 +00:00
- [CodingStyle](#codingstyle) (37)
2020-02-13 13:42:40 +00:00
- [Composer](#composer) (5)
- [DeadCode](#deadcode) (48)
- [DeadDocBlock](#deaddocblock) (5)
- [Defluent](#defluent) (9)
2020-02-13 13:42:40 +00:00
- [DependencyInjection](#dependencyinjection) (5)
- [Doctrine](#doctrine) (6)
2020-02-13 13:42:40 +00:00
- [DoctrineCodeQuality](#doctrinecodequality) (11)
2019-09-15 18:28:10 +00:00
- [DoctrineGedmoToKnplabs](#doctrinegedmotoknplabs) (7)
2019-09-15 18:28:10 +00:00
- [DowngradePhp70](#downgradephp70) (1)
- [DowngradePhp71](#downgradephp71) (7)
2019-09-15 18:28:10 +00:00
- [DowngradePhp72](#downgradephp72) (2)
2019-09-15 18:28:10 +00:00
- [DowngradePhp73](#downgradephp73) (4)
2019-09-15 18:28:10 +00:00
- [DowngradePhp74](#downgradephp74) (11)
2019-09-15 18:28:10 +00:00
- [DowngradePhp80](#downgradephp80) (10)
- [EarlyReturn](#earlyreturn) (11)
2019-09-15 18:28:10 +00:00
2021-01-30 20:30:37 +00:00
- [Generics](#generics) (1)
2019-09-15 18:28:10 +00:00
- [Laravel](#laravel) (11)
2019-09-15 18:28:10 +00:00
- [MockeryToProphecy](#mockerytoprophecy) (2)
2019-09-15 18:28:10 +00:00
- [MysqlToMysqli](#mysqltomysqli) (4)
2020-07-24 11:46:57 +00:00
- [Naming](#naming) (9)
2021-03-12 23:52:38 +00:00
- [Nette](#nette) (21)
2020-07-24 11:46:57 +00:00
2021-02-13 14:57:30 +00:00
- [NetteCodeQuality](#nettecodequality) (8)
- [NetteKdyby](#nettekdyby) (4)
2019-09-15 18:28:10 +00:00
- [NetteTesterToPHPUnit](#nettetestertophpunit) (3)
- [NetteToSymfony](#nettetosymfony) (9)
2021-01-25 18:59:06 +00:00
- [Order](#order) (6)
- [PHPOffice](#phpoffice) (14)
- [PHPUnit](#phpunit) (38)
- [PSR4](#psr4) (2)
- [Php52](#php52) (2)
- [Php53](#php53) (4)
- [Php54](#php54) (2)
- [Php55](#php55) (3)
- [Php56](#php56) (2)
- [Php70](#php70) (19)
- [Php71](#php71) (9)
- [Php72](#php72) (10)
- [Php73](#php73) (9)
- [Php74](#php74) (14)
- [Php80](#php80) (16)
- [PhpSpecToPHPUnit](#phpspectophpunit) (7)
2021-03-03 21:28:27 +00:00
- [PostRector](#postrector) (7)
- [Privatization](#privatization) (15)
2021-01-30 20:30:37 +00:00
- [Removing](#removing) (6)
- [RemovingStatic](#removingstatic) (9)
- [Renaming](#renaming) (11)
- [Restoration](#restoration) (8)
- [Symfony](#symfony) (13)
- [Symfony2](#symfony2) (3)
- [Symfony3](#symfony3) (12)
- [Symfony4](#symfony4) (12)
- [Symfony5](#symfony5) (10)
2021-03-12 23:52:38 +00:00
- [Transform](#transform) (37)
- [TypeDeclaration](#typedeclaration) (18)
2021-01-30 20:30:37 +00:00
- [Visibility](#visibility) (3)
<br>
## Arguments
### ArgumentAdderRector
This Rector adds new default arguments in calls of defined methods and class types.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Arguments\Rector\ClassMethod\ArgumentAdderRector`](../rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php)
```php
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),
]),
]]);
};
```
```diff
$someObject = new SomeExampleClass;
-$someObject->someMethod();
+$someObject->someMethod(true);
```
<br>
```php
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),
]),
]]);
};
```
```diff
class MyCustomClass extends SomeExampleClass
{
- public function someMethod()
+ public function someMethod($value = true)
{
}
}
```
<br>
### ArgumentDefaultValueReplacerRector
Replaces defined map of arguments in defined methods and their calls.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Arguments\Rector\ClassMethod\ArgumentDefaultValueReplacerRector`](../rules/Arguments/Rector/ClassMethod/ArgumentDefaultValueReplacerRector.php)
```php
use Rector\Arguments\Rector\ClassMethod\ArgumentDefaultValueReplacerRector;
use Rector\Arguments\ValueObject\ArgumentDefaultValueReplacer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentDefaultValueReplacerRector::class)
->call('configure', [[
ArgumentDefaultValueReplacerRector::REPLACED_ARGUMENTS => ValueObjectInliner::inline([
new ArgumentDefaultValueReplacer('SomeExampleClass', 'someMethod', 0, 'SomeClass::OLD_CONSTANT', 'false'),
]),
]]);
};
```
```diff
$someObject = new SomeClass;
-$someObject->someMethod(SomeClass::OLD_CONSTANT);
+$someObject->someMethod(false);'
```
<br>
### SwapFuncCallArgumentsRector
Swap arguments in function calls
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Arguments\Rector\FuncCall\SwapFuncCallArgumentsRector`](../rules/Arguments/Rector/FuncCall/SwapFuncCallArgumentsRector.php)
```php
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]), ]
),
]]);
};
```
```diff
final class SomeClass
{
public function run($one, $two)
{
- return some_function($one, $two);
+ return some_function($two, $one);
}
}
```
<br>
## Autodiscovery
### MoveEntitiesToEntityDirectoryRector
Move entities to Entity namespace
2021-03-12 23:52:38 +00:00
- class: [`Rector\Autodiscovery\Rector\FileNode\MoveEntitiesToEntityDirectoryRector`](../rules/Autodiscovery/Rector/FileNode/MoveEntitiesToEntityDirectoryRector.php)
```diff
-// 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
{
}
```
<br>
2019-12-26 10:21:09 +00:00
### MoveInterfacesToContractNamespaceDirectoryRector
2018-09-28 16:33:35 +00:00
Move interface to "Contract" namespace
2021-03-12 23:52:38 +00:00
- class: [`Rector\Autodiscovery\Rector\FileNode\MoveInterfacesToContractNamespaceDirectoryRector`](../rules/Autodiscovery/Rector/FileNode/MoveInterfacesToContractNamespaceDirectoryRector.php)
```diff
-// file: app/Exception/Rule.php
+// file: app/Contract/Rule.php
-namespace App\Exception;
+namespace App\Contract;
interface Rule
{
}
```
<br>
### MoveServicesBySuffixToDirectoryRector
Move classes by their suffix to their own group/directory
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Autodiscovery\Rector\FileNode\MoveServicesBySuffixToDirectoryRector`](../rules/Autodiscovery/Rector/FileNode/MoveServicesBySuffixToDirectoryRector.php)
```php
use Rector\Autodiscovery\Rector\FileNode\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'],
]]);
};
```
```diff
-// file: app/Entity/ProductRepository.php
+// file: app/Repository/ProductRepository.php
-namespace App/Entity;
+namespace App/Repository;
class ProductRepository
{
}
```
<br>
### MoveValueObjectsToValueObjectDirectoryRector
Move value object to ValueObject namespace/directory
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Autodiscovery\Rector\FileNode\MoveValueObjectsToValueObjectDirectoryRector`](../rules/Autodiscovery/Rector/FileNode/MoveValueObjectsToValueObjectDirectoryRector.php)
```php
use Rector\Autodiscovery\Rector\FileNode\MoveValueObjectsToValueObjectDirectoryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MoveValueObjectsToValueObjectDirectoryRector::class)
->call('configure', [[
2021-03-12 23:52:38 +00:00
MoveValueObjectsToValueObjectDirectoryRector::TYPES => [
'ValueObjectInterfaceClassName',
], MoveValueObjectsToValueObjectDirectoryRector::SUFFIXES => [
'Search',
], MoveValueObjectsToValueObjectDirectoryRector::ENABLE_VALUE_OBJECT_GUESSING => true,
]]);
};
```
```diff
-// 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;
}
}
```
<br>
## CakePHP
### AppUsesStaticCallToUseStatementRector
Change `App::uses()` to use imports
2021-03-12 23:52:38 +00:00
- class: [`Rector\CakePHP\Rector\Namespace_\AppUsesStaticCallToUseStatementRector`](../rules/CakePHP/Rector/Namespace_/AppUsesStaticCallToUseStatementRector.php)
```diff
-App::uses('NotificationListener', 'Event');
+use Event\NotificationListener;
CakeEventManager::instance()->attach(new NotificationListener());
```
<br>
### ArrayToFluentCallRector
Moves array options to fluent setter method calls.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\CakePHP\Rector\MethodCall\ArrayToFluentCallRector`](../rules/CakePHP/Rector/MethodCall/ArrayToFluentCallRector.php)
```php
use Rector\CakePHP\Rector\MethodCall\ArrayToFluentCallRector;
use Rector\CakePHP\ValueObject\ArrayToFluentCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArrayToFluentCallRector::class)
->call('configure', [[
ArrayToFluentCallRector::ARRAYS_TO_FLUENT_CALLS => ValueObjectInliner::inline([
new ArrayToFluentCall('ArticlesTable', ['setForeignKey', 'setProperty']), ]
),
]]);
};
```
```diff
use Cake\ORM\Table;
final class ArticlesTable extends Table
{
public function initialize(array $config)
{
- $this->belongsTo('Authors', [
- 'foreignKey' => 'author_id',
- 'propertyName' => 'person'
- ]);
+ $this->belongsTo('Authors')
+ ->setForeignKey('author_id')
+ ->setProperty('person');
}
}
```
<br>
### ChangeSnakedFixtureNameToPascalRector
Changes `$fixtues` style from snake_case to PascalCase.
2021-03-12 23:52:38 +00:00
- class: [`Rector\CakePHP\Rector\Property\ChangeSnakedFixtureNameToPascalRector`](../rules/CakePHP/Rector/Property/ChangeSnakedFixtureNameToPascalRector.php)
2018-09-28 16:33:35 +00:00
```diff
class SomeTest
{
protected $fixtures = [
- 'app.posts',
- 'app.users',
- 'some_plugin.posts/special_posts',
+ 'app.Posts',
+ 'app.Users',
+ 'some_plugin.Posts/SpecialPosts',
];
```
2018-09-28 16:33:35 +00:00
<br>
### ImplicitShortClassNameUseStatementRector
Collect implicit class names and add imports
2021-03-12 23:52:38 +00:00
- class: [`Rector\CakePHP\Rector\FileWithoutNamespace\ImplicitShortClassNameUseStatementRector`](../rules/CakePHP/Rector/FileWithoutNamespace/ImplicitShortClassNameUseStatementRector.php)
```diff
use App\Foo\Plugin;
+use Cake\TestSuite\Fixture\TestFixture;
class LocationsFixture extends TestFixture implements Plugin
{
}
2018-09-28 16:33:35 +00:00
```
2018-08-01 20:09:34 +00:00
<br>
2019-10-02 08:04:14 +00:00
### ModalToGetSetRector
2019-10-02 08:04:14 +00:00
Changes combined set/get `value()` to specific `getValue()` or `setValue(x)`.
2019-10-02 08:04:14 +00:00
:wrench: **configure it!**
2020-07-24 11:46:57 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CakePHP\Rector\MethodCall\ModalToGetSetRector`](../rules/CakePHP/Rector/MethodCall/ModalToGetSetRector.php)
```php
use Rector\CakePHP\Rector\MethodCall\ModalToGetSetRector;
use Rector\CakePHP\ValueObject\ModalToGetSet;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(ModalToGetSetRector::class)
->call('configure', [[
ModalToGetSetRector::UNPREFIXED_METHODS_TO_GET_SET => ValueObjectInliner::inline([
new ModalToGetSet('InstanceConfigTrait', 'config', 'getConfig', 'setConfig', 1, null),
]),
]]);
2020-07-24 11:46:57 +00:00
};
2019-10-02 08:04:14 +00:00
```
```diff
$object = new InstanceConfigTrait;
-$config = $object->config();
-$config = $object->config('key');
+$config = $object->getConfig();
+$config = $object->getConfig('key');
-$object->config('key', 'value');
-$object->config(['key' => 'value']);
+$object->setConfig('key', 'value');
+$object->setConfig(['key' => 'value']);
2019-10-02 08:04:14 +00:00
```
<br>
### RenameMethodCallBasedOnParameterRector
Changes method calls based on matching the first parameter value.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\CakePHP\Rector\MethodCall\RenameMethodCallBasedOnParameterRector`](../rules/CakePHP/Rector/MethodCall/RenameMethodCallBasedOnParameterRector.php)
```php
use Rector\CakePHP\Rector\MethodCall\RenameMethodCallBasedOnParameterRector;
use Rector\CakePHP\ValueObject\RenameMethodCallBasedOnParameter;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameMethodCallBasedOnParameterRector::class)
->call('configure', [[
RenameMethodCallBasedOnParameterRector::CALLS_WITH_PARAM_RENAMES => ValueObjectInliner::inline([
new RenameMethodCallBasedOnParameter('getParam', 'paging', 'getAttribute', 'ServerRequest'),
new RenameMethodCallBasedOnParameter('withParam', 'paging', 'withAttribute', 'ServerRequest'),
]),
]]);
};
```
```diff
$object = new ServerRequest();
-$config = $object->getParam('paging');
-$object = $object->withParam('paging', ['a value']);
+$config = $object->getAttribute('paging');
+$object = $object->withAttribute('paging', ['a value']);
```
<br>
## Carbon
### ChangeCarbonSingularMethodCallToPluralRector
Change setter methods with args to their plural names on Carbon\Carbon
2021-03-12 23:52:38 +00:00
- class: [`Rector\Carbon\Rector\MethodCall\ChangeCarbonSingularMethodCallToPluralRector`](../rules/Carbon/Rector/MethodCall/ChangeCarbonSingularMethodCallToPluralRector.php)
```diff
use Carbon\Carbon;
final class SomeClass
{
public function run(Carbon $carbon, $value): void
{
- $carbon->addMinute($value);
+ $carbon->addMinutes($value);
}
}
```
<br>
2019-03-09 13:24:30 +00:00
### ChangeDiffForHumansArgsRector
2020-01-03 18:20:13 +00:00
Change methods arguments of `diffForHumans()` on Carbon\Carbon
2020-01-03 18:20:13 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Carbon\Rector\MethodCall\ChangeDiffForHumansArgsRector`](../rules/Carbon/Rector/MethodCall/ChangeDiffForHumansArgsRector.php)
2020-01-03 18:20:13 +00:00
```diff
use Carbon\Carbon;
final class SomeClass
2020-01-03 18:20:13 +00:00
{
public function run(Carbon $carbon): void
2020-01-03 18:20:13 +00:00
{
- $carbon->diffForHumans(null, true);
+ $carbon->diffForHumans(null, \Carbon\CarbonInterface::DIFF_ABSOLUTE);
- $carbon->diffForHumans(null, false);
+ $carbon->diffForHumans(null, \Carbon\CarbonInterface::DIFF_RELATIVE_AUTO);
}
}
```
2020-01-03 18:20:13 +00:00
<br>
## 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.
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Include_\AbsolutizeRequireAndIncludePathRector`](../rules/CodeQuality/Rector/Include_/AbsolutizeRequireAndIncludePathRector.php)
```diff
class SomeClass
{
public function run()
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
require $variable;
2020-01-03 18:20:13 +00:00
}
}
```
<br>
2020-01-03 18:20:13 +00:00
### AddPregQuoteDelimiterRector
2019-11-06 23:52:19 +00:00
Add `preg_quote` delimiter when missing
2019-11-06 23:52:19 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\AddPregQuoteDelimiterRector`](../rules/CodeQuality/Rector/FuncCall/AddPregQuoteDelimiterRector.php)
2019-11-06 23:52:19 +00:00
```diff
-'#' . preg_quote('name') . '#';
+'#' . preg_quote('name', '#') . '#';
```
2019-11-06 23:52:19 +00:00
<br>
2019-11-06 23:52:19 +00:00
### AndAssignsToSeparateLinesRector
2019-03-09 13:24:30 +00:00
Split 2 assigns ands to separate line
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\LogicalAnd\AndAssignsToSeparateLinesRector`](../rules/CodeQuality/Rector/LogicalAnd/AndAssignsToSeparateLinesRector.php)
2019-03-09 13:24:30 +00:00
```diff
class SomeClass
2019-03-09 13:24:30 +00:00
{
public function run()
2019-03-09 13:24:30 +00:00
{
$tokens = [];
- $token = 4 and $tokens[] = $token;
+ $token = 4;
+ $tokens[] = $token;
2019-03-09 13:24:30 +00:00
}
}
```
<br>
2019-03-09 13:24:30 +00:00
### ArrayKeyExistsTernaryThenValueToCoalescingRector
2020-01-03 18:20:13 +00:00
Change `array_key_exists()` ternary to coalesing
2020-01-03 18:20:13 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Ternary\ArrayKeyExistsTernaryThenValueToCoalescingRector`](../rules/CodeQuality/Rector/Ternary/ArrayKeyExistsTernaryThenValueToCoalescingRector.php)
2020-01-03 18:20:13 +00:00
```diff
class SomeClass
2020-01-03 18:20:13 +00:00
{
public function run($values, $keyToMatch)
2020-01-03 18:20:13 +00:00
{
- $result = array_key_exists($keyToMatch, $values) ? $values[$keyToMatch] : null;
+ $result = $values[$keyToMatch] ?? null;
2020-01-03 18:20:13 +00:00
}
}
```
<br>
2020-01-03 18:20:13 +00:00
### ArrayKeysAndInArrayToArrayKeyExistsRector
Replace `array_keys()` and `in_array()` to `array_key_exists()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\ArrayKeysAndInArrayToArrayKeyExistsRector`](../rules/CodeQuality/Rector/FuncCall/ArrayKeysAndInArrayToArrayKeyExistsRector.php)
```diff
class SomeClass
{
public function run($packageName, $values)
{
- $keys = array_keys($values);
- return in_array($packageName, $keys, true);
+ return array_key_exists($packageName, $values);
}
}
```
<br>
### ArrayMergeOfNonArraysToSimpleArrayRector
2019-11-06 23:52:19 +00:00
Change `array_merge` of non arrays to array directly
2019-11-06 23:52:19 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\ArrayMergeOfNonArraysToSimpleArrayRector`](../rules/CodeQuality/Rector/FuncCall/ArrayMergeOfNonArraysToSimpleArrayRector.php)
2019-11-06 23:52:19 +00:00
```diff
class SomeClass
{
public function go()
{
$value = 5;
$value2 = 10;
2019-11-06 23:52:19 +00:00
- return array_merge([$value], [$value2]);
+ return [$value, $value2];
}
}
2019-11-06 23:52:19 +00:00
```
<br>
2019-11-06 23:52:19 +00:00
### ArrayThisCallToThisMethodCallRector
Change `[$this, someMethod]` without any args to `$this->someMethod()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Array_\ArrayThisCallToThisMethodCallRector`](../rules/CodeQuality/Rector/Array_/ArrayThisCallToThisMethodCallRector.php)
```diff
class SomeClass
{
public function run()
{
- $values = [$this, 'giveMeMore'];
+ $values = $this->giveMeMore();
}
public function giveMeMore()
{
return 'more';
}
}
```
<br>
### BooleanNotIdenticalToNotIdenticalRector
Negated identical boolean compare to not identical compare (does not apply to non-bool values)
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\BooleanNotIdenticalToNotIdenticalRector`](../rules/CodeQuality/Rector/Identical/BooleanNotIdenticalToNotIdenticalRector.php)
```diff
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
}
}
```
<br>
2018-12-31 11:50:32 +00:00
### CallableThisArrayToAnonymousFunctionRector
2018-12-31 11:50:32 +00:00
Convert [$this, "method"] to proper anonymous function
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector`](../rules/CodeQuality/Rector/Array_/CallableThisArrayToAnonymousFunctionRector.php)
2018-12-31 11:50:32 +00:00
```diff
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;
}
}
2018-12-31 11:50:32 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
### ChangeArrayPushToArrayAssignRector
Change `array_push()` to direct variable assign
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector`](../rules/CodeQuality/Rector/FuncCall/ChangeArrayPushToArrayAssignRector.php)
```diff
class SomeClass
{
public function run()
{
$items = [];
- array_push($items, $item);
+ $items[] = $item;
}
}
```
<br>
### CombineIfRector
2020-01-15 20:40:44 +00:00
Merges nested if statements
2020-01-15 20:40:44 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\CombineIfRector`](../rules/CodeQuality/Rector/If_/CombineIfRector.php)
2020-01-15 20:40:44 +00:00
```diff
class SomeClass
{
public function run()
{
- if ($cond1) {
- if ($cond2) {
- return 'foo';
- }
+ if ($cond1 && $cond2) {
+ return 'foo';
}
}
}
2020-01-15 20:40:44 +00:00
```
<br>
2020-01-15 20:40:44 +00:00
### CombinedAssignRector
2018-10-21 22:26:45 +00:00
Simplify `$value` = `$value` + 5; assignments to shorter ones
2018-10-21 22:26:45 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Assign\CombinedAssignRector`](../rules/CodeQuality/Rector/Assign/CombinedAssignRector.php)
2018-10-21 22:26:45 +00:00
```diff
-$value = $value + 5;
+$value += 5;
```
2018-10-21 22:26:45 +00:00
<br>
### CommonNotEqualRector
2020-07-27 08:16:16 +00:00
Use common != instead of less known <> with same meaning
2020-07-27 08:16:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\NotEqual\CommonNotEqualRector`](../rules/CodeQuality/Rector/NotEqual/CommonNotEqualRector.php)
2020-07-27 08:16:16 +00:00
```diff
final class SomeClass
2020-07-27 08:16:16 +00:00
{
public function run($one, $two)
{
- return $one <> $two;
+ return $one != $two;
}
2020-07-27 08:16:16 +00:00
}
```
<br>
2020-07-27 08:16:16 +00:00
### CompactToVariablesRector
2019-05-01 23:56:58 +00:00
Change `compact()` call to own array
2019-05-01 23:56:58 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\CompactToVariablesRector`](../rules/CodeQuality/Rector/FuncCall/CompactToVariablesRector.php)
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
$checkout = 'one';
$form = 'two';
- return compact('checkout', 'form');
+ return ['checkout' => $checkout, 'form' => $form];
}
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
### CompleteDynamicPropertiesRector
2019-05-29 13:40:20 +00:00
Add missing dynamic properties
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector`](../rules/CodeQuality/Rector/Class_/CompleteDynamicPropertiesRector.php)
```diff
class SomeClass
{
+ /**
+ * @var int
+ */
+ public $value;
public function set()
{
$this->value = 5;
}
}
```
<br>
### ConsecutiveNullCompareReturnsToNullCoalesceQueueRector
Change multiple null compares to ?? queue
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector`](../rules/CodeQuality/Rector/If_/ConsecutiveNullCompareReturnsToNullCoalesceQueueRector.php)
2019-05-01 23:56:58 +00:00
```diff
class SomeClass
{
public function run()
2019-05-01 23:56:58 +00:00
{
- if (null !== $this->orderItem) {
- return $this->orderItem;
- }
-
- if (null !== $this->orderItemUnit) {
- return $this->orderItemUnit;
- }
-
- return null;
+ return $this->orderItem ?? $this->orderItemUnit;
2019-05-01 23:56:58 +00:00
}
}
```
<br>
### DateTimeToDateTimeInterfaceRector
Changes DateTime type-hint to DateTimeInterface
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector`](../rules/CodeQuality/Rector/ClassMethod/DateTimeToDateTimeInterfaceRector.php)
```diff
class SomeClass {
- public function methodWithDateTime(\DateTime $dateTime)
+ /**
+ * @param \DateTime|\DateTimeImmutable $dateTime
+ */
+ public function methodWithDateTime(\DateTimeInterface $dateTime)
{
return true;
}
}
```
<br>
### ExplicitBoolCompareRector
Make if conditions more explicit
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector`](../rules/CodeQuality/Rector/If_/ExplicitBoolCompareRector.php)
2019-05-19 08:27:38 +00:00
```diff
final class SomeController
2019-05-19 08:27:38 +00:00
{
public function run($items)
2019-05-19 08:27:38 +00:00
{
- if (!count($items)) {
+ if (count($items) === 0) {
return 'no items';
}
2019-05-19 08:27:38 +00:00
}
}
```
<br>
2019-05-19 08:27:38 +00:00
### FixClassCaseSensitivityNameRector
2020-07-27 13:40:30 +00:00
Change miss-typed case sensitivity name to correct one
2020-07-27 13:40:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Name\FixClassCaseSensitivityNameRector`](../rules/CodeQuality/Rector/Name/FixClassCaseSensitivityNameRector.php)
2020-07-27 13:40:30 +00:00
```diff
final class SomeClass
2020-07-27 13:40:30 +00:00
{
public function run()
{
- $anotherClass = new anotherclass;
+ $anotherClass = new AnotherClass;
}
2020-07-27 13:40:30 +00:00
}
final class AnotherClass
2020-07-27 13:40:30 +00:00
{
}
```
<br>
2020-07-27 13:40:30 +00:00
### FlipTypeControlToUseExclusiveTypeRector
Flip type control to use exclusive type
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector`](../rules/CodeQuality/Rector/Identical/FlipTypeControlToUseExclusiveTypeRector.php)
```diff
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;
}
}
}
```
<br>
### ForRepeatedCountToOwnVariableRector
2020-01-04 17:49:26 +00:00
Change `count()` in for function to own variable
2020-01-04 17:49:26 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector`](../rules/CodeQuality/Rector/For_/ForRepeatedCountToOwnVariableRector.php)
2020-01-04 17:49:26 +00:00
```diff
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];
}
}
}
```
2020-01-04 17:49:26 +00:00
<br>
2020-01-04 17:49:26 +00:00
### ForToForeachRector
Change `for()` to `foreach()` where useful
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\For_\ForToForeachRector`](../rules/CodeQuality/Rector/For_/ForToForeachRector.php)
```diff
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;
}
}
}
2019-05-29 13:40:20 +00:00
}
```
<br>
2018-10-21 22:26:45 +00:00
### ForeachItemsAssignToEmptyArrayToAssignRector
2020-01-04 17:49:26 +00:00
Change `foreach()` items assign to empty array to direct assign
2020-01-04 17:49:26 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector`](../rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php)
2020-01-04 17:49:26 +00:00
```diff
class SomeClass
{
public function run($items)
{
$collectedItems = [];
- foreach ($items as $item) {
- $collectedItems[] = $item;
- }
+ $collectedItems = $items;
}
2020-01-04 17:49:26 +00:00
}
```
<br>
2020-01-04 17:49:26 +00:00
### ForeachToInArrayRector
2018-10-21 22:26:45 +00:00
Simplify `foreach` loops into `in_array` when possible
2018-10-21 22:26:45 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\ForeachToInArrayRector`](../rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php)
2018-10-21 22:26:45 +00:00
```diff
-foreach ($items as $item) {
- if ($item === 'something') {
- return true;
- }
-}
-
-return false;
2021-02-20 23:02:05 +00:00
+return in_array('something', $items, true);
```
<br>
### GetClassToInstanceOfRector
Changes comparison with `get_class` to instanceof
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\GetClassToInstanceOfRector`](../rules/CodeQuality/Rector/Identical/GetClassToInstanceOfRector.php)
```diff
-if (EventsListener::class === get_class($event->job)) { }
+if ($event->job instanceof EventsListener) { }
2018-10-21 22:26:45 +00:00
```
<br>
### InArrayAndArrayKeysToArrayKeyExistsRector
Simplify `in_array` and `array_keys` functions combination into `array_key_exists` when `array_keys` has one argument only
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\InArrayAndArrayKeysToArrayKeyExistsRector`](../rules/CodeQuality/Rector/FuncCall/InArrayAndArrayKeysToArrayKeyExistsRector.php)
```diff
-in_array("key", array_keys($array), true);
+array_key_exists("key", $array);
```
<br>
### InlineIfToExplicitIfRector
2019-05-19 08:27:38 +00:00
Change inline if to explicit if
2019-05-19 08:27:38 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector`](../rules/CodeQuality/Rector/Expression/InlineIfToExplicitIfRector.php)
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
{
public function run()
{
$userId = null;
- is_null($userId) && $userId = 5;
+ if (is_null($userId)) {
+ $userId = 5;
+ }
}
}
```
<br>
### IntvalToTypeCastRector
Change `intval()` to faster and readable (int) `$value`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\IntvalToTypeCastRector`](../rules/CodeQuality/Rector/FuncCall/IntvalToTypeCastRector.php)
```diff
class SomeClass
{
public function run($value)
{
- return intval($value);
+ return (int) $value;
}
}
```
<br>
### IsAWithStringWithThirdArgumentRector
2019-12-27 17:50:00 +00:00
Complete missing 3rd argument in case `is_a()` function in case of strings
2019-12-27 17:50:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\IsAWithStringWithThirdArgumentRector`](../rules/CodeQuality/Rector/FuncCall/IsAWithStringWithThirdArgumentRector.php)
2019-12-27 17:50:00 +00:00
```diff
class SomeClass
2019-12-27 17:50:00 +00:00
{
public function __construct(string $value)
2019-12-27 17:50:00 +00:00
{
- return is_a($value, 'stdClass');
+ return is_a($value, 'stdClass', true);
2019-12-27 17:50:00 +00:00
}
}
```
<br>
2019-12-27 17:50:00 +00:00
### IssetOnPropertyObjectToPropertyExistsRector
2019-08-05 21:10:47 +00:00
2021-02-20 23:02:05 +00:00
Change isset on property object to `property_exists()` and not null check
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector`](../rules/CodeQuality/Rector/Isset_/IssetOnPropertyObjectToPropertyExistsRector.php)
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
private $x;
public function run(): void
{
- isset($this->x);
+ property_exists($this, 'x') && $this->x !== null;
}
}
2019-08-05 21:10:47 +00:00
```
<br>
2019-08-05 21:10:47 +00:00
### JoinStringConcatRector
Joins concat of 2 strings, unless the length is too long
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Concat\JoinStringConcatRector`](../rules/CodeQuality/Rector/Concat/JoinStringConcatRector.php)
```diff
class SomeClass
{
public function run()
{
- $name = 'Hi' . ' Tom';
+ $name = 'Hi Tom';
}
}
```
<br>
### LogicalToBooleanRector
Change OR, AND to ||, && with more common understanding
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\LogicalAnd\LogicalToBooleanRector`](../rules/CodeQuality/Rector/LogicalAnd/LogicalToBooleanRector.php)
```diff
-if ($f = false or true) {
+if (($f = false) || true) {
return $f;
}
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
### NewStaticToNewSelfRector
Change unsafe new `static()` to new `self()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\New_\NewStaticToNewSelfRector`](../rules/CodeQuality/Rector/New_/NewStaticToNewSelfRector.php)
```diff
class SomeClass
{
public function build()
{
- return new static();
+ return new self();
}
}
```
<br>
### RemoveAlwaysTrueConditionSetInConstructorRector
2019-08-05 21:10:47 +00:00
If conditions is always true, perform the content right away
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FunctionLike\RemoveAlwaysTrueConditionSetInConstructorRector`](../rules/CodeQuality/Rector/FunctionLike/RemoveAlwaysTrueConditionSetInConstructorRector.php)
2019-08-05 21:10:47 +00:00
```diff
final class SomeClass
{
private $value;
2019-08-05 21:10:47 +00:00
2021-02-20 23:02:05 +00:00
public function __construct(stdClass $value)
{
$this->value = $value;
}
public function go()
{
- if ($this->value) {
- return 'yes';
- }
+ return 'yes';
}
}
2019-08-05 21:10:47 +00:00
```
<br>
### RemoveSoleValueSprintfRector
Remove `sprintf()` wrapper if not needed
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\RemoveSoleValueSprintfRector`](../rules/CodeQuality/Rector/FuncCall/RemoveSoleValueSprintfRector.php)
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
public function run()
{
- $value = sprintf('%s', 'hi');
+ $value = 'hi';
$welcome = 'hello';
- $value = sprintf('%s', $welcome);
+ $value = $welcome;
}
}
```
<br>
### SetTypeToCastRector
Changes `settype()` to (type) where possible
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SetTypeToCastRector`](../rules/CodeQuality/Rector/FuncCall/SetTypeToCastRector.php)
```diff
class SomeClass
{
- public function run($foo)
+ public function run(array $items)
{
- settype($foo, 'string');
+ $foo = (string) $foo;
2020-07-27 08:16:16 +00:00
- return settype($foo, 'integer');
+ return (int) $foo;
}
}
```
<br>
### ShortenElseIfRector
Shortens else/if to elseif
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\ShortenElseIfRector`](../rules/CodeQuality/Rector/If_/ShortenElseIfRector.php)
2020-07-27 08:16:16 +00:00
```diff
class SomeClass
2020-07-27 08:16:16 +00:00
{
public function run()
2020-07-27 08:16:16 +00:00
{
if ($cond1) {
return $action1;
- } else {
- if ($cond2) {
- return $action2;
- }
+ } elseif ($cond2) {
+ return $action2;
}
2020-07-27 08:16:16 +00:00
}
}
```
<br>
2020-07-27 08:16:16 +00:00
### SimplifyArraySearchRector
Simplify `array_search` to `in_array`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\SimplifyArraySearchRector`](../rules/CodeQuality/Rector/Identical/SimplifyArraySearchRector.php)
```diff
-array_search("searching", $array) !== false;
+in_array("searching", $array);
```
<br>
```diff
-array_search("searching", $array, true) !== false;
+in_array("searching", $array, true);
```
<br>
### SimplifyBoolIdenticalTrueRector
2018-12-31 11:50:32 +00:00
Symplify bool value compare to true or false
2018-12-31 11:50:32 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector`](../rules/CodeQuality/Rector/Identical/SimplifyBoolIdenticalTrueRector.php)
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
2018-12-31 11:50:32 +00:00
{
public function run(bool $value, string $items)
2019-05-29 13:40:20 +00:00
{
- $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);
2018-12-31 11:50:32 +00:00
}
}
```
<br>
2018-12-31 11:50:32 +00:00
### SimplifyConditionsRector
2018-10-21 22:26:45 +00:00
Simplify conditions
2018-10-21 22:26:45 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\SimplifyConditionsRector`](../rules/CodeQuality/Rector/Identical/SimplifyConditionsRector.php)
2018-10-21 22:26:45 +00:00
```diff
-if (! ($foo !== 'bar')) {...
+if ($foo === 'bar') {...
```
<br>
### SimplifyDeMorganBinaryRector
Simplify negated conditions with de Morgan theorem
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\BooleanNot\SimplifyDeMorganBinaryRector`](../rules/CodeQuality/Rector/BooleanNot/SimplifyDeMorganBinaryRector.php)
```diff
$a = 5;
$b = 10;
-$result = !($a > 20 || $b <= 50);
+$result = $a <= 20 && $b > 50;
```
2018-10-21 22:26:45 +00:00
<br>
2019-03-31 12:25:39 +00:00
### SimplifyDuplicatedTernaryRector
2019-03-31 12:25:39 +00:00
Remove ternary that duplicated return value of true : false
2019-03-31 12:25:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Ternary\SimplifyDuplicatedTernaryRector`](../rules/CodeQuality/Rector/Ternary/SimplifyDuplicatedTernaryRector.php)
```diff
class SomeClass
2019-03-31 12:25:39 +00:00
{
public function run(bool $value, string $name)
2019-03-31 12:25:39 +00:00
{
- $isTrue = $value ? true : false;
+ $isTrue = $value;
$isName = $name ? true : false;
2019-03-31 12:25:39 +00:00
}
}
```
<br>
2019-03-31 12:25:39 +00:00
### SimplifyEmptyArrayCheckRector
Simplify `is_array` and `empty` functions combination into a simple identical check for an empty array
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector`](../rules/CodeQuality/Rector/BooleanAnd/SimplifyEmptyArrayCheckRector.php)
2018-10-21 22:26:45 +00:00
```diff
-is_array($values) && empty($values)
+$values === []
2018-10-21 22:26:45 +00:00
```
<br>
2018-10-21 22:26:45 +00:00
### SimplifyForeachToArrayFilterRector
2019-02-18 15:51:24 +00:00
Simplify foreach with function filtering to array filter
2019-02-18 15:51:24 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToArrayFilterRector`](../rules/CodeQuality/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php)
2019-02-18 15:51:24 +00:00
```diff
-$directories = [];
$possibleDirectories = [];
-foreach ($possibleDirectories as $possibleDirectory) {
- if (file_exists($possibleDirectory)) {
- $directories[] = $possibleDirectory;
- }
-}
+$directories = array_filter($possibleDirectories, 'file_exists');
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
### SimplifyForeachToCoalescingRector
2019-05-29 13:40:20 +00:00
Changes foreach that returns set value to ??
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToCoalescingRector`](../rules/CodeQuality/Rector/Foreach_/SimplifyForeachToCoalescingRector.php)
2019-05-29 13:40:20 +00:00
```diff
-foreach ($this->oldToNewFunctions as $oldFunction => $newFunction) {
- if ($currentFunction === $oldFunction) {
- return $newFunction;
- }
-}
-
-return null;
+return $this->oldToNewFunctions[$currentFunction] ?? null;
2019-02-18 15:51:24 +00:00
```
<br>
### SimplifyFuncGetArgsCountRector
Simplify `count` of `func_get_args()` to `func_num_args()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyFuncGetArgsCountRector`](../rules/CodeQuality/Rector/FuncCall/SimplifyFuncGetArgsCountRector.php)
```diff
-count(func_get_args());
+func_num_args();
```
<br>
### SimplifyIfElseToTernaryRector
Changes if/else for same value as assign to ternary
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector`](../rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php)
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
public function run()
2018-12-31 11:50:32 +00:00
{
- if (empty($value)) {
- $this->arrayBuilt[][$key] = true;
- } else {
- $this->arrayBuilt[][$key] = $value;
- }
+ $this->arrayBuilt[][$key] = empty($value) ? true : $value;
2018-12-31 11:50:32 +00:00
}
}
```
<br>
2018-12-31 11:50:32 +00:00
### SimplifyIfIssetToNullCoalescingRector
2018-10-21 22:26:45 +00:00
Simplify binary if to null coalesce
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfIssetToNullCoalescingRector`](../rules/CodeQuality/Rector/If_/SimplifyIfIssetToNullCoalescingRector.php)
2018-10-21 22:26:45 +00:00
```diff
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);
}
}
2018-10-21 22:26:45 +00:00
```
<br>
2018-10-23 18:58:57 +00:00
### SimplifyIfNotNullReturnRector
2019-02-18 15:51:24 +00:00
Changes redundant null check to instant return
2019-02-18 15:51:24 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfNotNullReturnRector`](../rules/CodeQuality/Rector/If_/SimplifyIfNotNullReturnRector.php)
2019-02-18 15:51:24 +00:00
```diff
$newNode = 'something ;
-if ($newNode !== null) {
- return $newNode;
-}
-
-return null;
+return $newNode;
2019-02-18 15:51:24 +00:00
```
<br>
2019-02-18 15:51:24 +00:00
### SimplifyIfReturnBoolRector
2019-01-22 20:34:38 +00:00
Shortens if return false/true to direct return
2019-01-22 20:34:38 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector`](../rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php)
2019-01-22 20:34:38 +00:00
```diff
-if (strpos($docToken->getContent(), "\n") === false) {
- return true;
-}
-
-return false;
+return strpos($docToken->getContent(), "\n") === false;
2019-01-22 20:34:38 +00:00
```
<br>
2019-01-22 20:34:38 +00:00
### SimplifyInArrayValuesRector
2019-05-19 08:27:38 +00:00
Removes unneeded `array_values()` in `in_array()` call
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyInArrayValuesRector`](../rules/CodeQuality/Rector/FuncCall/SimplifyInArrayValuesRector.php)
2019-05-19 08:27:38 +00:00
```diff
-in_array("key", array_values($array), true);
+in_array("key", $array, true);
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
### SimplifyRegexPatternRector
Simplify regex pattern to known ranges
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyRegexPatternRector`](../rules/CodeQuality/Rector/FuncCall/SimplifyRegexPatternRector.php)
```diff
class SomeClass
{
public function run($value)
{
- preg_match('#[a-zA-Z0-9+]#', $value);
+ preg_match('#[\w\d+]#', $value);
}
}
2019-05-29 13:40:20 +00:00
```
<br>
### SimplifyStrposLowerRector
Simplify `strpos(strtolower()`, "...") calls
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector`](../rules/CodeQuality/Rector/FuncCall/SimplifyStrposLowerRector.php)
```diff
-strpos(strtolower($var), "...")"
+stripos($var, "...")"
```
<br>
2018-10-23 18:58:57 +00:00
### SimplifyTautologyTernaryRector
Simplify tautology ternary to value
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Ternary\SimplifyTautologyTernaryRector`](../rules/CodeQuality/Rector/Ternary/SimplifyTautologyTernaryRector.php)
2018-10-23 18:58:57 +00:00
```diff
-$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;
+$value = $fullyQualifiedTypeHint;
2018-10-23 18:58:57 +00:00
```
<br>
2018-10-21 22:26:45 +00:00
### SimplifyUselessVariableRector
2019-05-01 23:56:58 +00:00
Removes useless variable assigns
2019-05-01 23:56:58 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Return_\SimplifyUselessVariableRector`](../rules/CodeQuality/Rector/Return_/SimplifyUselessVariableRector.php)
2019-05-01 23:56:58 +00:00
```diff
function () {
- $a = true;
- return $a;
+ return true;
};
2019-05-01 23:56:58 +00:00
```
<br>
### SingleInArrayToCompareRector
Changes `in_array()` with single element to ===
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector`](../rules/CodeQuality/Rector/FuncCall/SingleInArrayToCompareRector.php)
```diff
class SomeClass
{
public function run()
{
- if (in_array(strtolower($type), ['$this'], true)) {
+ if (strtolower($type) === '$this') {
return strtolower($type);
}
}
}
```
<br>
2021-01-25 18:59:06 +00:00
### SingularSwitchToIfRector
Change switch with only 1 check to if
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Switch_\SingularSwitchToIfRector`](../rules/CodeQuality/Rector/Switch_/SingularSwitchToIfRector.php)
2021-01-25 18:59:06 +00:00
```diff
class SomeObject
{
public function run($value)
{
$result = 1;
- switch ($value) {
- case 100:
+ if ($value === 100) {
$result = 1000;
}
return $result;
}
}
```
<br>
### SplitListAssignToSeparateLineRector
2019-08-05 21:10:47 +00:00
Splits `[$a, $b] = [5, 10]` scalar assign to standalone lines
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Assign\SplitListAssignToSeparateLineRector`](../rules/CodeQuality/Rector/Assign/SplitListAssignToSeparateLineRector.php)
2019-08-05 21:10:47 +00:00
```diff
final class SomeClass
2019-08-05 21:10:47 +00:00
{
public function run(): void
2019-08-05 21:10:47 +00:00
{
- [$a, $b] = [1, 2];
+ $a = 1;
+ $b = 2;
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
### StrlenZeroToIdenticalEmptyStringRector
2019-08-05 21:10:47 +00:00
Changes `strlen` comparison to 0 to direct empty string compare
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\StrlenZeroToIdenticalEmptyStringRector`](../rules/CodeQuality/Rector/Identical/StrlenZeroToIdenticalEmptyStringRector.php)
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
public function run($value)
{
- $empty = strlen($value) === 0;
+ $empty = $value === '';
}
}
2019-08-05 21:10:47 +00:00
```
<br>
2018-12-25 19:55:16 +00:00
### SwitchNegatedTernaryRector
Switch negated ternary condition rector
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Ternary\SwitchNegatedTernaryRector`](../rules/CodeQuality/Rector/Ternary/SwitchNegatedTernaryRector.php)
```diff
class SomeClass
{
public function run(bool $upper, string $name)
{
- return ! $upper
- ? $name
- : strtoupper($name);
+ return $upper
+ ? strtoupper($name)
+ : $name;
}
}
```
<br>
### ThrowWithPreviousExceptionRector
When throwing into a catch block, checks that the previous exception is passed to the new throw clause
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector`](../rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php)
```diff
class SomeClass
{
public function run()
{
try {
$someCode = 1;
} catch (Throwable $throwable) {
- throw new AnotherException('ups');
+ throw new AnotherException('ups', $throwable->getCode(), $throwable);
}
}
}
```
<br>
### UnnecessaryTernaryExpressionRector
Remove unnecessary ternary expressions.
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Ternary\UnnecessaryTernaryExpressionRector`](../rules/CodeQuality/Rector/Ternary/UnnecessaryTernaryExpressionRector.php)
```diff
-$foo === $bar ? true : false;
+$foo === $bar;
```
<br>
### UnusedForeachValueToArrayKeysRector
Change foreach with unused `$value` but only `$key,` to `array_keys()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector`](../rules/CodeQuality/Rector/Foreach_/UnusedForeachValueToArrayKeysRector.php)
```diff
class SomeClass
{
public function run()
{
$items = [];
- foreach ($values as $key => $value) {
+ foreach (array_keys($values) as $key) {
$items[$key] = null;
}
}
}
```
<br>
### UnwrapSprintfOneArgumentRector
unwrap `sprintf()` with one argument
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\UnwrapSprintfOneArgumentRector`](../rules/CodeQuality/Rector/FuncCall/UnwrapSprintfOneArgumentRector.php)
```diff
-echo sprintf('value');
+echo 'value';
```
<br>
### UseIdenticalOverEqualWithSameTypeRector
Use ===/!== over ==/!=, it values have the same type
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector`](../rules/CodeQuality/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php)
```diff
class SomeClass
{
public function run(int $firstValue, int $secondValue)
{
- $isSame = $firstValue == $secondValue;
- $isDiffernt = $firstValue != $secondValue;
+ $isSame = $firstValue === $secondValue;
+ $isDiffernt = $firstValue !== $secondValue;
}
}
```
2019-05-29 13:40:20 +00:00
<br>
## CodeQualityStrict
### MoveOutMethodCallInsideIfConditionRector
Move out method call inside If condition
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQualityStrict\Rector\If_\MoveOutMethodCallInsideIfConditionRector`](../rules/CodeQualityStrict/Rector/If_/MoveOutMethodCallInsideIfConditionRector.php)
```diff
-if ($obj->run($arg) === 1) {
+$objRun = $obj->run($arg);
+if ($objRun === 1) {
}
```
<br>
### MoveVariableDeclarationNearReferenceRector
Move variable declaration near its reference
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQualityStrict\Rector\Variable\MoveVariableDeclarationNearReferenceRector`](../rules/CodeQualityStrict/Rector/Variable/MoveVariableDeclarationNearReferenceRector.php)
```diff
-$var = 1;
if ($condition === null) {
+ $var = 1;
return $var;
}
```
<br>
### ParamTypeToAssertTypeRector
Turn `@param` type to `assert` type
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQualityStrict\Rector\ClassMethod\ParamTypeToAssertTypeRector`](../rules/CodeQualityStrict/Rector/ClassMethod/ParamTypeToAssertTypeRector.php)
```diff
class SomeClass
{
/**
* @param \A|\B $arg
*/
public function run($arg)
{
-
+ \Webmozart\Assert\Assert::isAnyOf($arg, [\A::class, \B::class]);
}
}
```
<br>
### VarInlineAnnotationToAssertRector
Turn `@var` inline checks above code to `assert()` of the type
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodeQualityStrict\Rector\Stmt\VarInlineAnnotationToAssertRector`](../rules/CodeQualityStrict/Rector/Stmt/VarInlineAnnotationToAssertRector.php)
```diff
class SomeClass
{
public function run()
{
/** @var SpecificClass $value */
+ assert($value instanceof SpecificClass);
$value->call();
}
}
```
<br>
## CodingStyle
2019-05-26 19:26:33 +00:00
### AddArrayDefaultToArrayPropertyRector
Adds array default value to property to prevent foreach over null error
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Class_\AddArrayDefaultToArrayPropertyRector`](../rules/CodingStyle/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php)
```diff
class SomeClass
{
/**
* @var int[]
*/
- private $values;
+ private $values = [];
public function isEmpty()
{
- return $this->values === null;
+ return $this->values === [];
}
}
```
<br>
### AddFalseDefaultToBoolPropertyRector
Add false default to bool properties, to prevent null compare errors
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Property\AddFalseDefaultToBoolPropertyRector`](../rules/CodingStyle/Rector/Property/AddFalseDefaultToBoolPropertyRector.php)
```diff
class SomeClass
{
/**
* @var bool
*/
- private $isDisabled;
+ private $isDisabled = false;
}
```
<br>
### BinarySwitchToIfElseRector
Changes switch with 2 options to if-else
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Switch_\BinarySwitchToIfElseRector`](../rules/CodingStyle/Rector/Switch_/BinarySwitchToIfElseRector.php)
```diff
-switch ($foo) {
- case 'my string':
- $result = 'ok';
- break;
-
- default:
- $result = 'not ok';
+if ($foo == 'my string') {
+ $result = 'ok;
+} else {
+ $result = 'not ok';
}
```
<br>
### CallUserFuncCallToVariadicRector
Replace call_user_func_call with variadic
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\FuncCall\CallUserFuncCallToVariadicRector`](../rules/CodingStyle/Rector/FuncCall/CallUserFuncCallToVariadicRector.php)
```diff
class SomeClass
{
public function run()
{
- call_user_func_array('some_function', $items);
+ some_function(...$items);
}
}
```
<br>
### CamelCaseFunctionNamingToUnderscoreRector
Change CamelCase naming of functions to under_score naming
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector`](../rules/CodingStyle/Rector/Function_/CamelCaseFunctionNamingToUnderscoreRector.php)
```diff
-function someCamelCaseFunction()
+function some_camel_case_function()
{
}
-someCamelCaseFunction();
+some_camel_case_function();
```
<br>
### CatchExceptionNameMatchingTypeRector
Type and name of catch exception should match
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Catch_\CatchExceptionNameMatchingTypeRector`](../rules/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector.php)
```diff
class SomeClass
{
public function run()
{
try {
// ...
- } catch (SomeException $typoException) {
- $typoException->getMessage();
+ } catch (SomeException $someException) {
+ $someException->getMessage();
}
}
}
```
<br>
### ConsistentImplodeRector
Changes various `implode` forms to consistent one
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\FuncCall\ConsistentImplodeRector`](../rules/CodingStyle/Rector/FuncCall/ConsistentImplodeRector.php)
```diff
class SomeClass
{
public function run(array $items)
{
- $itemsAsStrings = implode($items);
- $itemsAsStrings = implode($items, '|');
+ $itemsAsStrings = implode('', $items);
+ $itemsAsStrings = implode('|', $items);
$itemsAsStrings = implode('|', $items);
}
}
```
<br>
### ConsistentPregDelimiterRector
2019-08-05 21:10:47 +00:00
Replace PREG delimiter with configured one
2019-08-05 21:10:47 +00:00
:wrench: **configure it!**
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector`](../rules/CodingStyle/Rector/FuncCall/ConsistentPregDelimiterRector.php)
2019-08-05 21:10:47 +00:00
```php
use Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-08-05 21:10:47 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-01 23:56:58 +00:00
$services->set(ConsistentPregDelimiterRector::class)
->call('configure', [[
ConsistentPregDelimiterRector::DELIMITER => '#',
]]);
};
```
2019-05-01 23:56:58 +00:00
2019-05-01 23:56:58 +00:00
```diff
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);
}
}
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
2021-01-30 20:30:37 +00:00
### CountArrayToEmptyArrayComparisonRector
Change `count` array comparison to empty array comparison to improve performance
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\FuncCall\CountArrayToEmptyArrayComparisonRector`](../rules/CodingStyle/Rector/FuncCall/CountArrayToEmptyArrayComparisonRector.php)
2021-01-30 20:30:37 +00:00
```diff
-count($array) === 0;
-count($array) > 0;
-! count($array);
+$array === [];
+$array !== [];
+$array === [];
```
<br>
### EncapsedStringsToSprintfRector
2019-10-15 14:46:31 +00:00
Convert enscaped {$string} to more readable `sprintf`
2019-10-15 14:46:31 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector`](../rules/CodingStyle/Rector/Encapsed/EncapsedStringsToSprintfRector.php)
2019-10-15 14:46:31 +00:00
```diff
final class SomeClass
{
public function run(string $format)
{
- return "Unsupported format {$format}";
+ return sprintf('Unsupported format %s', $format);
}
}
```
<br>
### FollowRequireByDirRector
include/require should be followed by absolute path
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Include_\FollowRequireByDirRector`](../rules/CodingStyle/Rector/Include_/FollowRequireByDirRector.php)
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
{
public function run()
2019-10-15 14:46:31 +00:00
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
2019-10-15 14:46:31 +00:00
}
}
```
<br>
### MakeInheritedMethodVisibilitySameAsParentRector
Make method visibility same as parent one
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector`](../rules/CodingStyle/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php)
```diff
class ChildClass extends ParentClass
{
- public function run()
+ protected function run()
{
}
}
class ParentClass
{
protected function run()
{
}
}
```
<br>
### ManualJsonStringToJsonEncodeArrayRector
2019-08-05 21:10:47 +00:00
Add extra space before new assign set
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Assign\ManualJsonStringToJsonEncodeArrayRector`](../rules/CodingStyle/Rector/Assign/ManualJsonStringToJsonEncodeArrayRector.php)
2019-08-05 21:10:47 +00:00
```diff
+use Nette\Utils\Json;
+
final class SomeClass
2019-08-05 21:10:47 +00:00
{
public function run()
{
- $someJsonAsString = '{"role_name":"admin","numberz":{"id":"10"}}';
+ $data = [
+ 'role_name' => 'admin',
+ 'numberz' => ['id' => 10]
+ ];
+ $someJsonAsString = Json::encode($data);
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
### NewlineBeforeNewAssignSetRector
2019-08-05 21:10:47 +00:00
Add extra space before new assign set
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassMethod\NewlineBeforeNewAssignSetRector`](../rules/CodingStyle/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php)
2019-08-05 21:10:47 +00:00
```diff
final class SomeClass
2019-08-05 21:10:47 +00:00
{
public function run()
{
$value = new Value;
$value->setValue(5);
+
$value2 = new Value;
$value2->setValue(1);
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
### NullableCompareToNullRector
Changes negate of empty comparison of nullable value to explicit === or !== compare
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\If_\NullableCompareToNullRector`](../rules/CodingStyle/Rector/If_/NullableCompareToNullRector.php)
```diff
/** @var stdClass|null $value */
-if ($value) {
+if ($value !== null) {
}
-if (!$value) {
+if ($value === null) {
}
```
<br>
2020-07-24 11:46:57 +00:00
### PHPStormVarAnnotationRector
Change various `@var` annotation formats to one PHPStorm understands
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Assign\PHPStormVarAnnotationRector`](../rules/CodingStyle/Rector/Assign/PHPStormVarAnnotationRector.php)
```diff
-$config = 5;
-/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+$config = 5;
```
<br>
### PostIncDecToPreIncDecRector
Use ++$value or --$value instead of `$value++` or `$value--`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\PostInc\PostIncDecToPreIncDecRector`](../rules/CodingStyle/Rector/PostInc/PostIncDecToPreIncDecRector.php)
```diff
class SomeClass
{
public function run($value = 1)
{
- $value++; echo $value;
- $value--; echo $value;
+ ++$value; echo $value;
+ --$value; echo $value;
}
}
```
<br>
### PreferThisOrSelfMethodCallRector
Changes `$this->...` and static:: to self:: or vise versa for given types
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector`](../rules/CodingStyle/Rector/MethodCall/PreferThisOrSelfMethodCallRector.php)
```php
use PHPUnit\Framework\TestCase;
use Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PreferThisOrSelfMethodCallRector::class)
->call('configure', [[
PreferThisOrSelfMethodCallRector::TYPE_TO_PREFERENCE => [
2021-03-12 23:52:38 +00:00
TestCase::class => 'prefer_self',
], ]]);
};
```
```diff
class SomeClass extends \PHPUnit\Framework\TestCase
{
public function run()
{
- $this->assertEquals('a', 'a');
+ self::assertEquals('a', 'a');
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### PreslashSimpleFunctionRector
Add pre-slash to short named functions to improve performance
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\FuncCall\PreslashSimpleFunctionRector`](../rules/CodingStyle/Rector/FuncCall/PreslashSimpleFunctionRector.php)
2021-01-30 20:30:37 +00:00
```diff
class SomeClass
{
public function shorten($value)
{
- return trim($value);
+ return \trim($value);
}
}
```
<br>
### RemoveDoubleUnderscoreInMethodNameRector
Non-magic PHP object methods cannot start with "__"
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassMethod\RemoveDoubleUnderscoreInMethodNameRector`](../rules/CodingStyle/Rector/ClassMethod/RemoveDoubleUnderscoreInMethodNameRector.php)
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
2019-09-25 08:49:53 +00:00
{
- public function __getName($anotherObject)
+ public function getName($anotherObject)
2019-09-25 08:49:53 +00:00
{
- $anotherObject->__getSurname();
+ $anotherObject->getSurname();
2019-09-25 08:49:53 +00:00
}
}
```
<br>
2019-09-25 08:49:53 +00:00
### RemoveUnusedAliasRector
Removes unused use aliases. Keep annotation aliases like "Doctrine\ORM\Mapping as ORM" to keep convention format
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Use_\RemoveUnusedAliasRector`](../rules/CodingStyle/Rector/Use_/RemoveUnusedAliasRector.php)
```diff
-use Symfony\Kernel as BaseKernel;
+use Symfony\Kernel;
-class SomeClass extends BaseKernel
+class SomeClass extends Kernel
{
}
```
<br>
### ReturnArrayClassMethodToYieldRector
Turns array return to yield return in specific type and method
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector`](../rules/CodingStyle/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php)
```php
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('EventSubscriberInterface', 'getSubscribedEvents'),
]),
]]);
};
```
```diff
class SomeEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- return ['event' => 'callback'];
+ yield 'event' => 'callback';
}
}
```
<br>
2020-07-24 11:46:57 +00:00
### SplitDoubleAssignRector
Split multiple inline assigns to each own lines default value, to prevent undefined array issues
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Assign\SplitDoubleAssignRector`](../rules/CodingStyle/Rector/Assign/SplitDoubleAssignRector.php)
```diff
class SomeClass
{
public function run()
{
- $one = $two = 1;
+ $one = 1;
+ $two = 1;
}
}
```
<br>
### SplitGroupedConstantsAndPropertiesRector
2019-05-29 13:40:20 +00:00
Separate constant and properties to own lines
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassConst\SplitGroupedConstantsAndPropertiesRector`](../rules/CodingStyle/Rector/ClassConst/SplitGroupedConstantsAndPropertiesRector.php)
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
- const HI = true, AHOJ = 'true';
+ const HI = true;
+ const AHOJ = 'true';
/**
* @var string
*/
- public $isIt, $isIsThough;
+ public $isIt;
+
+ /**
+ * @var string
+ */
+ public $isIsThough;
2019-05-29 13:40:20 +00:00
}
```
<br>
2019-05-29 13:40:20 +00:00
### SplitGroupedUseImportsRector
2019-05-01 23:56:58 +00:00
Split grouped use imports and trait statements to standalone lines
2019-05-01 23:56:58 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Use_\SplitGroupedUseImportsRector`](../rules/CodingStyle/Rector/Use_/SplitGroupedUseImportsRector.php)
2019-05-01 23:56:58 +00:00
```diff
-use A, B;
+use A;
+use B;
2019-05-01 23:56:58 +00:00
class SomeClass
{
- use SomeTrait, AnotherTrait;
+ use SomeTrait;
+ use AnotherTrait;
2019-05-01 23:56:58 +00:00
}
```
<br>
2019-05-01 23:56:58 +00:00
### SplitStringClassConstantToClassConstFetchRector
Separate class constant in a string to class constant fetch and string
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\String_\SplitStringClassConstantToClassConstFetchRector`](../rules/CodingStyle/Rector/String_/SplitStringClassConstantToClassConstFetchRector.php)
```diff
class SomeClass
{
const HI = true;
}
class AnotherClass
{
public function get()
{
- return 'SomeClass::HI';
+ return SomeClass::class . '::HI';
}
}
```
<br>
### StrictArraySearchRector
Makes `array_search` search for identical elements
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\FuncCall\StrictArraySearchRector`](../rules/CodingStyle/Rector/FuncCall/StrictArraySearchRector.php)
```diff
-array_search($value, $items);
+array_search($value, $items, true);
```
<br>
### SymplifyQuoteEscapeRector
Prefer quote that are not inside the string
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\String_\SymplifyQuoteEscapeRector`](../rules/CodingStyle/Rector/String_/SymplifyQuoteEscapeRector.php)
```diff
class SomeClass
{
public function run()
{
- $name = "\" Tom";
- $name = '\' Sara';
+ $name = '" Tom';
+ $name = "' Sara";
}
}
```
<br>
### TernaryConditionVariableAssignmentRector
Assign outcome of ternary condition to variable, where applicable
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Ternary\TernaryConditionVariableAssignmentRector`](../rules/CodingStyle/Rector/Ternary/TernaryConditionVariableAssignmentRector.php)
```diff
function ternary($value)
{
- $value ? $a = 1 : $a = 0;
+ $a = $value ? 1 : 0;
}
```
<br>
### UnSpreadOperatorRector
Remove spread operator
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassMethod\UnSpreadOperatorRector`](../rules/CodingStyle/Rector/ClassMethod/UnSpreadOperatorRector.php)
```diff
class SomeClass
{
- public function run(...$array)
+ public function run(array $array)
{
}
public function execute(array $data)
{
- $this->run(...$data);
+ $this->run($data);
}
}
```
<br>
### UseClassKeywordForClassNameResolutionRector
Use `class` keyword for class name resolution in string instead of hardcoded string reference
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\String_\UseClassKeywordForClassNameResolutionRector`](../rules/CodingStyle/Rector/String_/UseClassKeywordForClassNameResolutionRector.php)
```diff
-$value = 'App\SomeClass::someMethod()';
+$value = \App\SomeClass . '::someMethod()';
```
<br>
### UseIncrementAssignRector
Use ++ increment instead of `$var += 1`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Plus\UseIncrementAssignRector`](../rules/CodingStyle/Rector/Plus/UseIncrementAssignRector.php)
```diff
class SomeClass
{
public function run()
{
- $style += 1;
+ ++$style;
}
}
```
<br>
### UseMessageVariableForSprintfInSymfonyStyleRector
Decouple `$message` property from `sprintf()` calls in `$this->symfonyStyle->method()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\MethodCall\UseMessageVariableForSprintfInSymfonyStyleRector`](../rules/CodingStyle/Rector/MethodCall/UseMessageVariableForSprintfInSymfonyStyleRector.php)
```diff
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);
}
}
2018-10-21 22:26:45 +00:00
```
<br>
2018-10-21 22:26:45 +00:00
### VarConstantCommentRector
2019-10-15 14:46:31 +00:00
`Constant` should have a `@var` comment with type
2019-10-15 14:46:31 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassConst\VarConstantCommentRector`](../rules/CodingStyle/Rector/ClassConst/VarConstantCommentRector.php)
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
2019-10-15 14:46:31 +00:00
{
+ /**
+ * @var string
+ */
const HI = 'hi';
2019-10-15 14:46:31 +00:00
}
```
<br>
2019-10-15 14:46:31 +00:00
### VersionCompareFuncCallToConstantRector
Changes use of call to version compare function to use of PHP version constant
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\FuncCall\VersionCompareFuncCallToConstantRector`](../rules/CodingStyle/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php)
```diff
class SomeClass
{
public function run()
{
- version_compare(PHP_VERSION, '5.3.0', '<');
+ PHP_VERSION_ID < 50300;
}
}
```
<br>
### WrapEncapsedVariableInCurlyBracesRector
Wrap encapsed variables in curly braces
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\Encapsed\WrapEncapsedVariableInCurlyBracesRector`](../rules/CodingStyle/Rector/Encapsed/WrapEncapsedVariableInCurlyBracesRector.php)
```diff
function run($world)
{
- echo "Hello $world!"
+ echo "Hello {$world}!"
}
```
<br>
### YieldClassMethodToArrayClassMethodRector
Turns yield return to array return in specific type and method
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector`](../rules/CodingStyle/Rector/ClassMethod/YieldClassMethodToArrayClassMethodRector.php)
```php
use Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-29 13:40:20 +00:00
$services->set(YieldClassMethodToArrayClassMethodRector::class)
->call('configure', [[
YieldClassMethodToArrayClassMethodRector::METHODS_BY_TYPE => [
'EventSubscriberInterface' => ['getSubscribedEvents'],
2021-03-12 23:52:38 +00:00
], ]]);
};
```
2019-05-29 13:40:20 +00:00
```diff
class SomeEventSubscriber implements EventSubscriberInterface
2019-05-29 13:40:20 +00:00
{
public static function getSubscribedEvents()
2019-05-29 13:40:20 +00:00
{
- yield 'event' => 'callback';
+ return ['event' => 'callback'];
2019-05-29 13:40:20 +00:00
}
}
```
<br>
## Composer
### AddPackageToRequireComposerRector
Add package to "require" in `composer.json`
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Composer\Rector\AddPackageToRequireComposerRector`](../rules/Composer/Rector/AddPackageToRequireComposerRector.php)
```php
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'),
]),
]]);
};
```
```diff
{
+ "require": {
+ "symfony/console": "^3.4"
+ }
}
```
<br>
### AddPackageToRequireDevComposerRector
Add package to "require-dev" in `composer.json`
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Composer\Rector\AddPackageToRequireDevComposerRector`](../rules/Composer/Rector/AddPackageToRequireDevComposerRector.php)
```php
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'),
]),
]]);
};
```
```diff
{
+ "require-dev": {
+ "symfony/console": "^3.4"
+ }
}
```
<br>
### ChangePackageVersionComposerRector
Change package version `composer.json`
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Composer\Rector\ChangePackageVersionComposerRector`](../rules/Composer/Rector/ChangePackageVersionComposerRector.php)
```php
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'),
]),
]]);
};
```
```diff
{
- "require-dev": {
- "symfony/console": "^3.4"
+ "require": {
+ "symfony/console": "^4.4"
}
}
```
<br>
### RemovePackageComposerRector
Remove package from "require" and "require-dev" in `composer.json`
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Composer\Rector\RemovePackageComposerRector`](../rules/Composer/Rector/RemovePackageComposerRector.php)
```php
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'],
]]);
};
```
```diff
{
- "require": {
- "symfony/console": "^3.4"
- }
}
```
<br>
### ReplacePackageAndVersionComposerRector
Change package name and version `composer.json`
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Composer\Rector\ReplacePackageAndVersionComposerRector`](../rules/Composer/Rector/ReplacePackageAndVersionComposerRector.php)
```php
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'),
]),
]]);
};
```
```diff
{
"require-dev": {
- "symfony/console": "^3.4"
+ "symfony/http-kernel": "^4.4"
}
}
```
<br>
## DeadCode
### RecastingRemovalRector
Removes recasting of the same type
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Cast\RecastingRemovalRector`](../rules/DeadCode/Rector/Cast/RecastingRemovalRector.php)
```diff
$string = '';
-$string = (string) $string;
+$string = $string;
$array = [];
-$array = (array) $array;
+$array = $array;
```
<br>
### RemoveAlwaysTrueIfConditionRector
Remove if condition that is always true
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector`](../rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php)
```diff
final class SomeClass
{
public function go()
{
- if (1 === 1) {
- return 'yes';
- }
+ return 'yes';
return 'no';
}
}
```
<br>
### RemoveAndTrueRector
Remove and true that has no added value
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\BooleanAnd\RemoveAndTrueRector`](../rules/DeadCode/Rector/BooleanAnd/RemoveAndTrueRector.php)
```diff
class SomeClass
{
public function run()
{
- return true && 5 === 1;
+ return 5 === 1;
}
}
```
<br>
### RemoveAssignOfVoidReturnFunctionRector
2019-06-06 13:01:53 +00:00
Remove assign of void function/method to variable
2019-06-06 13:01:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Assign\RemoveAssignOfVoidReturnFunctionRector`](../rules/DeadCode/Rector/Assign/RemoveAssignOfVoidReturnFunctionRector.php)
2019-06-06 13:01:53 +00:00
```diff
class SomeClass
2019-06-06 13:01:53 +00:00
{
public function run()
2019-06-06 13:01:53 +00:00
{
- $value = $this->getOne();
+ $this->getOne();
}
private function getOne(): void
{
2019-06-06 13:01:53 +00:00
}
}
```
<br>
2019-06-06 13:01:53 +00:00
### RemoveCodeAfterReturnRector
Remove dead code after return statement
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\FunctionLike\RemoveCodeAfterReturnRector`](../rules/DeadCode/Rector/FunctionLike/RemoveCodeAfterReturnRector.php)
```diff
class SomeClass
{
public function run(int $a)
{
return $a;
- $a++;
}
}
```
<br>
2018-12-25 19:55:16 +00:00
### RemoveConcatAutocastRector
Remove (string) casting when it comes to concat, that does this by default
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Concat\RemoveConcatAutocastRector`](../rules/DeadCode/Rector/Concat/RemoveConcatAutocastRector.php)
```diff
class SomeConcatingClass
{
public function run($value)
{
- return 'hi ' . (string) $value;
+ return 'hi ' . $value;
}
}
```
<br>
### RemoveDeadConditionAboveReturnRector
Remove dead condition above return
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Return_\RemoveDeadConditionAboveReturnRector`](../rules/DeadCode/Rector/Return_/RemoveDeadConditionAboveReturnRector.php)
```diff
final class SomeClass
{
public function go()
{
- if (1 === 1) {
- return 'yes';
- }
-
return 'yes';
}
}
```
<br>
### RemoveDeadConstructorRector
2018-12-25 19:55:16 +00:00
Remove empty constructor
2018-12-25 19:55:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveDeadConstructorRector`](../rules/DeadCode/Rector/ClassMethod/RemoveDeadConstructorRector.php)
2018-12-25 19:55:16 +00:00
```diff
class SomeClass
2018-12-25 19:55:16 +00:00
{
- public function __construct()
- {
- }
2018-12-25 19:55:16 +00:00
}
```
<br>
2018-12-25 19:55:16 +00:00
### RemoveDeadIfForeachForRector
2018-12-31 11:50:32 +00:00
Remove if, foreach and for that does not do anything
2018-12-31 11:50:32 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\For_\RemoveDeadIfForeachForRector`](../rules/DeadCode/Rector/For_/RemoveDeadIfForeachForRector.php)
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
public function run($someObject)
{
$value = 5;
- if ($value) {
- }
-
if ($someObject->run()) {
- }
-
- foreach ($values as $value) {
}
return $value;
}
}
```
<br>
2021-02-13 14:57:30 +00:00
### RemoveDeadInstanceOfRector
Remove dead instanceof check on type hinted variable
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\If_\RemoveDeadInstanceOfRector`](../rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php)
2021-02-13 14:57:30 +00:00
```diff
final class SomeClass
{
public function go(stdClass $stdClass)
{
- if (! $stdClass instanceof stdClass) {
- return false;
- }
-
return true;
}
}
```
<br>
2021-02-20 23:02:05 +00:00
### RemoveDeadLoopRector
Remove loop with no body
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\For_\RemoveDeadLoopRector`](../rules/DeadCode/Rector/For_/RemoveDeadLoopRector.php)
2021-02-20 23:02:05 +00:00
```diff
class SomeClass
{
public function run($values)
{
- for ($i=1; $i<count($values); ++$i) {
- }
}
}
```
<br>
### RemoveDeadRecursiveClassMethodRector
Remove unused public method that only calls itself recursively
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveDeadRecursiveClassMethodRector`](../rules/DeadCode/Rector/ClassMethod/RemoveDeadRecursiveClassMethodRector.php)
```diff
class SomeClass
{
- public function run()
- {
- return $this->run();
- }
}
```
<br>
### RemoveDeadReturnRector
2019-03-09 13:24:30 +00:00
Remove last return in the functions, since does not do anything
2019-03-09 13:24:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\FunctionLike\RemoveDeadReturnRector`](../rules/DeadCode/Rector/FunctionLike/RemoveDeadReturnRector.php)
2019-03-09 13:24:30 +00:00
```diff
class SomeClass
{
public function run()
2019-02-21 14:36:16 +00:00
{
$shallWeDoThis = true;
if ($shallWeDoThis) {
return;
}
-
- return;
2019-02-21 14:36:16 +00:00
}
}
```
<br>
2019-02-21 14:36:16 +00:00
### RemoveDeadStmtRector
Removes dead code statements
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Expression\RemoveDeadStmtRector`](../rules/DeadCode/Rector/Expression/RemoveDeadStmtRector.php)
```diff
-$value = 5;
-$value;
+$value = 5;
```
<br>
### RemoveDeadTryCatchRector
2019-02-18 15:51:24 +00:00
Remove dead try/catch
2019-02-18 15:51:24 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\TryCatch\RemoveDeadTryCatchRector`](../rules/DeadCode/Rector/TryCatch/RemoveDeadTryCatchRector.php)
2019-02-18 15:51:24 +00:00
```diff
class SomeClass
{
public function run()
{
- try {
- // some code
- }
- catch (Throwable $throwable) {
- throw $throwable;
- }
+ // some code
}
}
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
### RemoveDeadZeroAndOneOperationRector
2019-08-05 21:10:47 +00:00
Remove operation with 1 and 0, that have no effect on the value
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Plus\RemoveDeadZeroAndOneOperationRector`](../rules/DeadCode/Rector/Plus/RemoveDeadZeroAndOneOperationRector.php)
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
public function run()
{
- $value = 5 * 1;
- $value = 5 + 0;
+ $value = 5;
+ $value = 5;
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
### RemoveDefaultArgumentValueRector
Remove argument value, if it is the same as default value
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\MethodCall\RemoveDefaultArgumentValueRector`](../rules/DeadCode/Rector/MethodCall/RemoveDefaultArgumentValueRector.php)
```diff
class SomeClass
{
public function run()
{
- $this->runWithDefault([]);
- $card = self::runWithStaticDefault([]);
+ $this->runWithDefault();
+ $card = self::runWithStaticDefault();
}
public function runWithDefault($items = [])
{
return $items;
}
public function runStaticWithDefault($cards = [])
{
return $cards;
}
}
```
<br>
### RemoveDelegatingParentCallRector
Removed dead parent call, that does not change anything
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveDelegatingParentCallRector`](../rules/DeadCode/Rector/ClassMethod/RemoveDelegatingParentCallRector.php)
```diff
class SomeClass
{
- public function prettyPrint(array $stmts): string
- {
- return parent::prettyPrint($stmts);
- }
}
```
<br>
### RemoveDoubleAssignRector
2019-03-31 12:25:39 +00:00
Simplify useless double assigns
2019-03-31 12:25:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Assign\RemoveDoubleAssignRector`](../rules/DeadCode/Rector/Assign/RemoveDoubleAssignRector.php)
2019-03-31 12:25:39 +00:00
```diff
-$value = 1;
$value = 1;
```
<br>
### RemoveDuplicatedArrayKeyRector
Remove duplicated `key` in defined arrays.
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector`](../rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php)
```diff
$item = [
- 1 => 'A',
1 => 'B'
];
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
### RemoveDuplicatedCaseInSwitchRector
2 following switch keys with identical will be reduced to one result
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Switch_\RemoveDuplicatedCaseInSwitchRector`](../rules/DeadCode/Rector/Switch_/RemoveDuplicatedCaseInSwitchRector.php)
```diff
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;
}
}
}
```
<br>
### RemoveDuplicatedIfReturnRector
2019-08-24 11:08:59 +00:00
Remove duplicated if stmt with return in function/method body
2019-08-24 11:08:59 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\FunctionLike\RemoveDuplicatedIfReturnRector`](../rules/DeadCode/Rector/FunctionLike/RemoveDuplicatedIfReturnRector.php)
2019-08-24 11:08:59 +00:00
```diff
class SomeClass
2019-08-24 11:08:59 +00:00
{
public function run($value)
{
if ($value) {
return true;
}
$value2 = 100;
-
- if ($value) {
- return true;
- }
}
2019-08-24 11:08:59 +00:00
}
```
<br>
2019-08-24 11:08:59 +00:00
### RemoveDuplicatedInstanceOfRector
2018-12-25 19:55:16 +00:00
Remove duplicated instanceof in one call
2018-12-25 19:55:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\BinaryOp\RemoveDuplicatedInstanceOfRector`](../rules/DeadCode/Rector/BinaryOp/RemoveDuplicatedInstanceOfRector.php)
2018-12-25 19:55:16 +00:00
```diff
class SomeClass
2018-12-25 19:55:16 +00:00
{
- public function run($value)
+ public function run($value): void
2019-05-29 13:40:20 +00:00
{
- $isIt = $value instanceof A || $value instanceof A;
- $isIt = $value instanceof A && $value instanceof A;
+ $isIt = $value instanceof A;
+ $isIt = $value instanceof A;
}
}
```
2018-12-25 19:55:16 +00:00
<br>
2018-12-25 19:55:16 +00:00
### RemoveEmptyClassMethodRector
2018-12-25 19:55:16 +00:00
Remove empty method calls not required by parents
2018-12-25 19:55:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector`](../rules/DeadCode/Rector/ClassMethod/RemoveEmptyClassMethodRector.php)
2018-12-25 19:55:16 +00:00
```diff
class OrphanClass
2019-05-29 13:40:20 +00:00
{
- public function __construct()
- {
- }
2019-05-29 13:40:20 +00:00
}
2018-12-25 19:55:16 +00:00
```
<br>
2018-12-25 19:55:16 +00:00
### RemoveEmptyMethodCallRector
2019-08-17 13:06:02 +00:00
Remove empty method call
2019-08-17 13:06:02 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\MethodCall\RemoveEmptyMethodCallRector`](../rules/DeadCode/Rector/MethodCall/RemoveEmptyMethodCallRector.php)
```diff
class SomeClass
{
public function callThis()
{
}
}
-$some = new SomeClass();
-$some->callThis();
+$some = new SomeClass();
```
<br>
### RemoveNullPropertyInitializationRector
Remove initialization with null value from property declarations
2019-08-17 13:06:02 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\PropertyProperty\RemoveNullPropertyInitializationRector`](../rules/DeadCode/Rector/PropertyProperty/RemoveNullPropertyInitializationRector.php)
2019-08-17 13:06:02 +00:00
```diff
class SunshineCommand extends ParentClassWithNewConstructor
2019-08-17 13:06:02 +00:00
{
- private $myVar = null;
+ private $myVar;
2019-08-17 13:06:02 +00:00
}
```
<br>
2019-08-17 13:06:02 +00:00
### RemoveOverriddenValuesRector
Remove initial assigns of overridden values
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\FunctionLike\RemoveOverriddenValuesRector`](../rules/DeadCode/Rector/FunctionLike/RemoveOverriddenValuesRector.php)
```diff
final class SomeController
{
public function run()
{
- $directories = [];
$possibleDirectories = [];
$directories = array_filter($possibleDirectories, 'file_exists');
}
}
```
<br>
### RemoveParentCallWithoutParentRector
Remove unused parent call with no parent class
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector`](../rules/DeadCode/Rector/StaticCall/RemoveParentCallWithoutParentRector.php)
```diff
class OrphanClass
{
public function __construct()
{
- parent::__construct();
}
}
```
<br>
### RemoveSetterOnlyPropertyAndMethodCallRector
Removes method that set values that are never used
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Property\RemoveSetterOnlyPropertyAndMethodCallRector`](../rules/DeadCode/Rector/Property/RemoveSetterOnlyPropertyAndMethodCallRector.php)
```diff
class SomeClass
{
- private $name;
-
- public function setName($name)
- {
- $this->name = $name;
- }
}
class ActiveOnlySetter
{
public function run()
{
$someClass = new SomeClass();
- $someClass->setName('Tom');
}
}
```
<br>
### RemoveUnreachableStatementRector
2020-01-04 23:18:57 +00:00
Remove unreachable statements
2020-01-04 23:18:57 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector`](../rules/DeadCode/Rector/Stmt/RemoveUnreachableStatementRector.php)
2020-01-04 23:18:57 +00:00
```diff
class SomeClass
2020-01-04 23:18:57 +00:00
{
public function run()
2020-01-04 23:18:57 +00:00
{
return 5;
2020-01-04 23:18:57 +00:00
-
- $removeMe = 10;
}
2020-01-04 23:18:57 +00:00
}
```
<br>
2020-01-04 23:18:57 +00:00
### RemoveUnusedAssignVariableRector
2019-08-05 21:10:47 +00:00
Remove assigned unused variable
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Assign\RemoveUnusedAssignVariableRector`](../rules/DeadCode/Rector/Assign/RemoveUnusedAssignVariableRector.php)
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
2019-08-05 21:10:47 +00:00
{
public function run()
{
- $value = $this->process();
+ $this->process();
}
public function process()
{
// something going on
return 5;
}
2019-08-05 21:10:47 +00:00
}
```
<br>
2019-08-05 21:10:47 +00:00
### RemoveUnusedClassConstantRector
2019-05-19 08:27:38 +00:00
Remove unused class constants
2019-05-19 08:27:38 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassConst\RemoveUnusedClassConstantRector`](../rules/DeadCode/Rector/ClassConst/RemoveUnusedClassConstantRector.php)
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
{
- private const SOME_CONST = 'dead';
-
public function run()
{
}
2019-05-19 08:27:38 +00:00
}
```
<br>
2019-05-19 08:27:38 +00:00
2021-02-13 14:57:30 +00:00
### RemoveUnusedConstructorParamRector
Remove unused parameter in constructor
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveUnusedConstructorParamRector`](../rules/DeadCode/Rector/ClassMethod/RemoveUnusedConstructorParamRector.php)
2021-02-13 14:57:30 +00:00
```diff
final class SomeClass
{
private $hey;
- public function __construct($hey, $man)
+ public function __construct($hey)
{
$this->hey = $hey;
}
}
```
<br>
### RemoveUnusedDoctrineEntityMethodAndPropertyRector
Removes unused methods and properties from Doctrine entity classes
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Class_\RemoveUnusedDoctrineEntityMethodAndPropertyRector`](../rules/DeadCode/Rector/Class_/RemoveUnusedDoctrineEntityMethodAndPropertyRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class UserEntity
{
- /**
- * @ORM\Column
- */
- private $name;
-
- public function getName()
- {
- return $this->name;
- }
-
- public function setName($name)
- {
- $this->name = $name;
- }
}
```
<br>
### RemoveUnusedForeachKeyRector
Remove unused `key` in foreach
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Foreach_\RemoveUnusedForeachKeyRector`](../rules/DeadCode/Rector/Foreach_/RemoveUnusedForeachKeyRector.php)
```diff
$items = [];
-foreach ($items as $key => $value) {
+foreach ($items as $value) {
$result = $value;
}
```
<br>
### RemoveUnusedFunctionRector
2019-02-21 14:36:16 +00:00
Remove unused function
2019-02-21 14:36:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Function_\RemoveUnusedFunctionRector`](../rules/DeadCode/Rector/Function_/RemoveUnusedFunctionRector.php)
2019-02-21 14:36:16 +00:00
```diff
-function removeMe()
-{
-}
-
function useMe()
2019-02-21 14:36:16 +00:00
{
}
useMe();
2019-02-21 14:36:16 +00:00
```
<br>
2019-02-21 14:36:16 +00:00
### RemoveUnusedNonEmptyArrayBeforeForeachRector
2019-02-21 14:36:16 +00:00
Remove unused if check to non-empty array before foreach of the array
2019-02-21 14:36:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector`](../rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php)
2019-02-21 14:36:16 +00:00
```diff
class SomeClass
2019-02-21 14:36:16 +00:00
{
public function run()
2019-02-21 14:36:16 +00:00
{
$values = [];
- if ($values !== []) {
- foreach ($values as $value) {
- echo $value;
- }
+ foreach ($values as $value) {
+ echo $value;
}
2019-02-21 14:36:16 +00:00
}
}
```
<br>
2019-02-21 14:36:16 +00:00
### RemoveUnusedParameterRector
2019-03-31 12:25:39 +00:00
Remove unused parameter, if not required by interface or parent class
2019-03-31 12:25:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveUnusedParameterRector`](../rules/DeadCode/Rector/ClassMethod/RemoveUnusedParameterRector.php)
2019-03-31 12:25:39 +00:00
```diff
class SomeClass
2019-03-31 12:25:39 +00:00
{
- public function __construct($value, $value2)
+ public function __construct($value)
{
$this->value = $value;
}
2019-03-31 12:25:39 +00:00
}
```
<br>
2019-03-31 12:25:39 +00:00
### RemoveUnusedPrivateConstantRector
2018-12-25 19:55:16 +00:00
Remove unused private constant
2018-12-25 19:55:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassConst\RemoveUnusedPrivateConstantRector`](../rules/DeadCode/Rector/ClassConst/RemoveUnusedPrivateConstantRector.php)
2018-12-25 19:55:16 +00:00
```diff
final class SomeController
2019-05-29 13:40:20 +00:00
{
- private const SOME_CONSTANT = 5;
public function run()
{
return 5;
}
}
2018-12-25 19:55:16 +00:00
```
<br>
2018-12-25 19:55:16 +00:00
### RemoveUnusedPrivateMethodRector
Remove unused private method
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector`](../rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php)
```diff
final class SomeController
{
public function run()
{
return 5;
}
-
- private function skip()
- {
- return 10;
- }
}
```
<br>
### RemoveUnusedPrivatePropertyRector
2019-10-15 14:46:31 +00:00
Remove unused private properties
2019-10-15 14:46:31 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector`](../rules/DeadCode/Rector/Property/RemoveUnusedPrivatePropertyRector.php)
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
{
- private $property;
2019-10-15 14:46:31 +00:00
}
```
<br>
2019-10-15 14:46:31 +00:00
### RemoveUnusedPublicMethodRector
Remove unused public method
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPublicMethodRector`](../rules/DeadCode/Rector/ClassMethod/RemoveUnusedPublicMethodRector.php)
```diff
class SomeClass
{
- public function unusedpublicMethod()
- {
- // ...
- }
-
public function execute()
{
// ...
}
public function run()
{
$obj = new self;
$obj->execute();
}
}
```
<br>
### RemoveUnusedVariableAssignRector
Remove unused assigns to variables
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector`](../rules/DeadCode/Rector/Assign/RemoveUnusedVariableAssignRector.php)
```diff
class SomeClass
{
public function run()
{
- $value = 5;
}
}
```
<br>
2019-12-27 17:50:00 +00:00
### SimplifyIfElseWithSameContentRector
2019-12-27 17:50:00 +00:00
Remove if/else if they have same content
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\If_\SimplifyIfElseWithSameContentRector`](../rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php)
2019-12-27 17:50:00 +00:00
```diff
class SomeClass
{
public function run()
{
- if (true) {
- return 1;
- } else {
- return 1;
- }
+ return 1;
}
2019-12-27 17:50:00 +00:00
}
```
<br>
### SimplifyMirrorAssignRector
Removes unneeded $a = $a assigns
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Expression\SimplifyMirrorAssignRector`](../rules/DeadCode/Rector/Expression/SimplifyMirrorAssignRector.php)
```diff
-$a = $a;
```
<br>
### TernaryToBooleanOrFalseToBooleanAndRector
Change ternary of bool : false to && bool
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\Ternary\TernaryToBooleanOrFalseToBooleanAndRector`](../rules/DeadCode/Rector/Ternary/TernaryToBooleanOrFalseToBooleanAndRector.php)
```diff
class SomeClass
{
public function go()
{
- return $value ? $this->getBool() : false;
+ return $value && $this->getBool();
}
private function getBool(): bool
{
return (bool) 5;
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### UnwrapFutureCompatibleIfFunctionExistsRector
Remove functions exists if with else for always existing
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\If_\UnwrapFutureCompatibleIfFunctionExistsRector`](../rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfFunctionExistsRector.php)
2021-01-30 20:30:37 +00:00
```diff
class SomeClass
{
public function run()
{
// session locking trough other addons
- if (function_exists('session_abort')) {
- session_abort();
- } else {
- session_write_close();
- }
+ session_abort();
}
}
```
<br>
### UnwrapFutureCompatibleIfPhpVersionRector
Remove php version checks if they are passed
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadCode\Rector\If_\UnwrapFutureCompatibleIfPhpVersionRector`](../rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfPhpVersionRector.php)
2021-01-30 20:30:37 +00:00
```diff
// 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+';
```
<br>
## DeadDocBlock
2021-01-30 20:30:37 +00:00
### RemoveAnnotationRector
Remove annotation by names
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadDocBlock\Rector\ClassLike\RemoveAnnotationRector`](../rules/DeadDocBlock/Rector/ClassLike/RemoveAnnotationRector.php)
2021-01-30 20:30:37 +00:00
```php
use Rector\DeadDocBlock\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'],
]]);
};
```
```diff
-/**
- * @method getName()
- */
final class SomeClass
{
}
```
<br>
### RemoveNonExistingVarAnnotationRector
Removes non-existing `@var` annotations above the code
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadDocBlock\Rector\Node\RemoveNonExistingVarAnnotationRector`](../rules/DeadDocBlock/Rector/Node/RemoveNonExistingVarAnnotationRector.php)
```diff
class SomeClass
{
public function get()
{
- /** @var Training[] $trainings */
return $this->getData();
}
}
```
<br>
### RemoveUselessParamTagRector
Remove `@param` docblock with same type as parameter type
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadDocBlock\Rector\ClassMethod\RemoveUselessParamTagRector`](../rules/DeadDocBlock/Rector/ClassMethod/RemoveUselessParamTagRector.php)
```diff
class SomeClass
{
/**
- * @param string $a
* @param string $b description
*/
public function foo(string $a, string $b)
{
}
}
```
<br>
### RemoveUselessReturnTagRector
Remove `@return` docblock with same type as defined in PHP
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadDocBlock\Rector\ClassMethod\RemoveUselessReturnTagRector`](../rules/DeadDocBlock/Rector/ClassMethod/RemoveUselessReturnTagRector.php)
```diff
use stdClass;
class SomeClass
{
- /**
- * @return stdClass
- */
public function foo(): stdClass
{
}
}
```
<br>
### RemoveUselessVarTagRector
Remove unused `@var` annotation for properties
2021-03-12 23:52:38 +00:00
- class: [`Rector\DeadDocBlock\Rector\Property\RemoveUselessVarTagRector`](../rules/DeadDocBlock/Rector/Property/RemoveUselessVarTagRector.php)
```diff
final class SomeClass
{
- /**
- * @var string
- */
public string $name = 'name';
}
```
<br>
## Defluent
### DefluentReturnMethodCallRector
Turns return of fluent, to standalone call line and return of value
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\Return_\DefluentReturnMethodCallRector`](../rules/Defluent/Rector/Return_/DefluentReturnMethodCallRector.php)
```diff
$someClass = new SomeClass();
-return $someClass->someFunction();
+$someClass->someFunction();
+return $someClass;
```
<br>
### FluentChainMethodCallToNormalMethodCallRector
Turns fluent interface calls to classic ones.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\MethodCall\FluentChainMethodCallToNormalMethodCallRector`](../rules/Defluent/Rector/MethodCall/FluentChainMethodCallToNormalMethodCallRector.php)
```diff
$someClass = new SomeClass();
-$someClass->someFunction()
- ->otherFunction();
+$someClass->someFunction();
+$someClass->otherFunction();
```
<br>
### InArgFluentChainMethodCallToStandaloneMethodCallRector
Turns fluent interface calls to classic ones.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\MethodCall\InArgFluentChainMethodCallToStandaloneMethodCallRector`](../rules/Defluent/Rector/MethodCall/InArgFluentChainMethodCallToStandaloneMethodCallRector.php)
```diff
class UsedAsParameter
{
public function someFunction(FluentClass $someClass)
{
- $this->processFluentClass($someClass->someFunction()->otherFunction());
+ $someClass->someFunction();
+ $someClass->otherFunction();
+ $this->processFluentClass($someClass);
}
public function processFluentClass(FluentClass $someClass)
{
}
}
```
<br>
### MethodCallOnSetterMethodCallToStandaloneAssignRector
Change method call on setter to standalone assign before the setter
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\MethodCall\MethodCallOnSetterMethodCallToStandaloneAssignRector`](../rules/Defluent/Rector/MethodCall/MethodCallOnSetterMethodCallToStandaloneAssignRector.php)
```diff
class SomeClass
{
public function some()
{
- $this->anotherMethod(new AnotherClass())
- ->someFunction();
+ $anotherClass = new AnotherClass();
+ $anotherClass->someFunction();
+ $this->anotherMethod($anotherClass);
}
public function anotherMethod(AnotherClass $anotherClass)
{
}
}
```
<br>
### NewFluentChainMethodCallToNonFluentRector
Turns fluent interface calls to classic ones.
2019-12-22 18:38:09 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\MethodCall\NewFluentChainMethodCallToNonFluentRector`](../rules/Defluent/Rector/MethodCall/NewFluentChainMethodCallToNonFluentRector.php)
2019-12-22 18:38:09 +00:00
```diff
-(new SomeClass())->someFunction()
- ->otherFunction();
+$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
2019-12-22 18:38:09 +00:00
```
<br>
### NormalToFluentRector
Turns fluent interface calls to classic ones.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\ClassMethod\NormalToFluentRector`](../rules/Defluent/Rector/ClassMethod/NormalToFluentRector.php)
```php
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']), ]
),
]]);
};
```
```diff
$someObject = new SomeClass();
-$someObject->someFunction();
-$someObject->otherFunction();
+$someObject->someFunction()
+ ->otherFunction();
```
<br>
### ReturnFluentChainMethodCallToNormalMethodCallRector
Turns fluent interface calls to classic ones.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\Return_\ReturnFluentChainMethodCallToNormalMethodCallRector`](../rules/Defluent/Rector/Return_/ReturnFluentChainMethodCallToNormalMethodCallRector.php)
2019-09-21 22:14:49 +00:00
```diff
$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
-return $someClass->someFunction()
- ->otherFunction();
+return $someClass;
```
<br>
2019-09-21 22:14:49 +00:00
### ReturnNewFluentChainMethodCallToNonFluentRector
Turns fluent interface calls to classic ones.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\Return_\ReturnNewFluentChainMethodCallToNonFluentRector`](../rules/Defluent/Rector/Return_/ReturnNewFluentChainMethodCallToNonFluentRector.php)
```diff
-return (new SomeClass())->someFunction()
- ->otherFunction();
+$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
+return $someClass;
```
<br>
### ReturnThisRemoveRector
Removes "return `$this;"` from *fluent interfaces* for specified classes.
2018-08-01 20:09:34 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Defluent\Rector\ClassMethod\ReturnThisRemoveRector`](../rules/Defluent/Rector/ClassMethod/ReturnThisRemoveRector.php)
```diff
class SomeExampleClass
{
public function someFunction()
{
- return $this;
}
2019-09-19 09:27:29 +00:00
public function otherFunction()
{
- return $this;
}
}
```
<br>
2019-09-19 09:27:29 +00:00
## DependencyInjection
2019-09-21 22:14:49 +00:00
2021-02-13 14:57:30 +00:00
### ActionInjectionToConstructorInjectionRector
Turns action injection in Controllers to constructor injection
2021-03-12 23:52:38 +00:00
- class: [`Rector\DependencyInjection\Rector\Class_\ActionInjectionToConstructorInjectionRector`](../rules/DependencyInjection/Rector/Class_/ActionInjectionToConstructorInjectionRector.php)
2021-02-13 14:57:30 +00:00
```diff
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();
}
}
```
<br>
### AddMethodParentCallRector
Add method parent call, in case new parent method is added
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\DependencyInjection\Rector\ClassMethod\AddMethodParentCallRector`](../rules/DependencyInjection/Rector/ClassMethod/AddMethodParentCallRector.php)
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
class SunshineCommand extends ParentClassWithNewConstructor
{
public function __construct()
{
$value = 5;
+
+ parent::__construct();
}
}
```
<br>
2021-02-20 23:02:05 +00:00
### AnnotatedPropertyInjectToConstructorInjectionRector
Turns properties with `@inject` to private properties and constructor injection
2021-03-12 23:52:38 +00:00
- class: [`Rector\DependencyInjection\Rector\Property\AnnotatedPropertyInjectToConstructorInjectionRector`](../rules/DependencyInjection/Rector/Property/AnnotatedPropertyInjectToConstructorInjectionRector.php)
2021-02-20 23:02:05 +00:00
```diff
/**
* @var SomeService
- * @inject
*/
-public $someService;
+private $someService;
+
+public function __construct(SomeService $someService)
+{
+ $this->someService = $someService;
+}
```
<br>
### MultiParentingToAbstractDependencyRector
Move dependency passed to all children to parent as `@inject/@required` dependency
2019-09-21 22:14:49 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\DependencyInjection\Rector\Class_\MultiParentingToAbstractDependencyRector`](../rules/DependencyInjection/Rector/Class_/MultiParentingToAbstractDependencyRector.php)
```php
use Rector\DependencyInjection\Rector\Class_\MultiParentingToAbstractDependencyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-09-21 22:14:49 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-09-21 22:14:49 +00:00
$services->set(MultiParentingToAbstractDependencyRector::class)
->call('configure', [[
MultiParentingToAbstractDependencyRector::FRAMEWORK => 'nette',
]]);
};
```
2019-09-21 22:14:49 +00:00
2019-09-21 22:14:49 +00:00
```diff
abstract class AbstractParentClass
2019-09-21 22:14:49 +00:00
{
- private $someDependency;
-
- public function __construct(SomeDependency $someDependency)
- {
- $this->someDependency = $someDependency;
- }
+ /**
+ * @inject
+ * @var SomeDependency
+ */
+ public $someDependency;
}
class FirstChild extends AbstractParentClass
{
- public function __construct(SomeDependency $someDependency)
- {
- parent::__construct($someDependency);
- }
}
class SecondChild extends AbstractParentClass
{
- public function __construct(SomeDependency $someDependency)
- {
- parent::__construct($someDependency);
- }
2019-09-21 22:14:49 +00:00
}
```
<br>
2019-09-21 22:14:49 +00:00
2021-02-13 14:57:30 +00:00
### ReplaceVariableByPropertyFetchRector
Turns variable in controller action to property fetch, as follow up to action injection variable to property change.
2021-03-12 23:52:38 +00:00
- class: [`Rector\DependencyInjection\Rector\Variable\ReplaceVariableByPropertyFetchRector`](../rules/DependencyInjection/Rector/Variable/ReplaceVariableByPropertyFetchRector.php)
2021-02-13 14:57:30 +00:00
```diff
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();
}
}
```
<br>
## Doctrine
2019-09-21 22:14:49 +00:00
### AddEntityIdByConditionRector
Add entity id with annotations when meets condition
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Doctrine\Rector\Class_\AddEntityIdByConditionRector`](../rules/Doctrine/Rector/Class_/AddEntityIdByConditionRector.php)
```php
use Rector\Doctrine\Rector\Class_\AddEntityIdByConditionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddEntityIdByConditionRector::class)
->call('configure', [[
AddEntityIdByConditionRector::DETECTED_TRAITS => [
'Knp\DoctrineBehaviors\Model\Translatable\Translation',
'Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait',
],
]]);
};
```
```diff
class SomeClass
{
use SomeTrait;
+
+ /**
+ * @ORM\Id
+ * @ORM\Column(type="integer")
+ * @ORM\GeneratedValue(strategy="AUTO")
+ */
+ private $id;
+
+ public function getId(): int
+ {
+ return $this->id;
+ }
}
```
<br>
### EntityAliasToClassConstantReferenceRector
Replaces doctrine alias with class.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Doctrine\Rector\MethodCall\EntityAliasToClassConstantReferenceRector`](../rules/Doctrine/Rector/MethodCall/EntityAliasToClassConstantReferenceRector.php)
```php
use Rector\Doctrine\Rector\MethodCall\EntityAliasToClassConstantReferenceRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(EntityAliasToClassConstantReferenceRector::class)
->call('configure', [[
EntityAliasToClassConstantReferenceRector::ALIASES_TO_NAMESPACES => [
App::class => 'App\Entity',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
$entityManager = new Doctrine\ORM\EntityManager();
-$entityManager->getRepository("AppBundle:Post");
+$entityManager->getRepository(\App\Entity\Post::class);
```
<br>
### ManagerRegistryGetManagerToEntityManagerRector
Changes ManagerRegistry intermediate calls directly to EntityManager calls
2021-03-12 23:52:38 +00:00
- class: [`Rector\Doctrine\Rector\Class_\ManagerRegistryGetManagerToEntityManagerRector`](../rules/Doctrine/Rector/Class_/ManagerRegistryGetManagerToEntityManagerRector.php)
```diff
-use Doctrine\Common\Persistence\ManagerRegistry;
+use Doctrine\ORM\EntityManagerInterface;
class CustomRepository
{
/**
- * @var ManagerRegistry
+ * @var EntityManagerInterface
*/
- private $managerRegistry;
+ private $entityManager;
- public function __construct(ManagerRegistry $managerRegistry)
+ public function __construct(EntityManagerInterface $entityManager)
{
- $this->managerRegistry = $managerRegistry;
+ $this->entityManager = $entityManager;
}
public function run()
{
- $entityManager = $this->managerRegistry->getManager();
- $someRepository = $entityManager->getRepository('Some');
+ $someRepository = $this->entityManager->getRepository('Some');
}
}
```
<br>
### RemoveRepositoryFromEntityAnnotationRector
Removes repository class from `@Entity` annotation
2021-03-12 23:52:38 +00:00
- class: [`Rector\Doctrine\Rector\Class_\RemoveRepositoryFromEntityAnnotationRector`](../rules/Doctrine/Rector/Class_/RemoveRepositoryFromEntityAnnotationRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
- * @ORM\Entity(repositoryClass="ProductRepository")
+ * @ORM\Entity
*/
class Product
{
}
```
<br>
2021-01-30 20:30:37 +00:00
### ReplaceParentRepositoryCallsByRepositoryPropertyRector
Handles method calls in child of Doctrine EntityRepository and moves them to `$this->repository` property.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Doctrine\Rector\MethodCall\ReplaceParentRepositoryCallsByRepositoryPropertyRector`](../rules/Doctrine/Rector/MethodCall/ReplaceParentRepositoryCallsByRepositoryPropertyRector.php)
2021-01-30 20:30:37 +00:00
```diff
use Doctrine\ORM\EntityRepository;
class SomeRepository extends EntityRepository
{
public function someMethod()
{
- return $this->findAll();
+ return $this->repository->findAll();
}
}
```
<br>
### ServiceEntityRepositoryParentCallToDIRector
Change ServiceEntityRepository to dependency injection, with repository property
2021-03-12 23:52:38 +00:00
- class: [`Rector\Doctrine\Rector\ClassMethod\ServiceEntityRepositoryParentCallToDIRector`](../rules/Doctrine/Rector/ClassMethod/ServiceEntityRepositoryParentCallToDIRector.php)
```diff
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
final class ProjectRepository extends ServiceEntityRepository
{
- public function __construct(ManagerRegistry $registry)
+ /**
+ * @var \Doctrine\ORM\EntityManagerInterface
+ */
+ private $entityManager;
+
+ /**
+ * @var \Doctrine\ORM\EntityRepository<Project>
+ */
+ private $repository;
+
+ public function __construct(\Doctrine\ORM\EntityManagerInterface $entityManager)
{
- parent::__construct($registry, Project::class);
+ $this->repository = $entityManager->getRepository(Project::class);
+ $this->entityManager = $entityManager;
}
}
```
<br>
## DoctrineCodeQuality
### ChangeBigIntEntityPropertyToIntTypeRector
Change database type "bigint" for @var/type declaration to string
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Property\ChangeBigIntEntityPropertyToIntTypeRector`](../rules/DoctrineCodeQuality/Rector/Property/ChangeBigIntEntityPropertyToIntTypeRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class SomeEntity
{
/**
- * @var int|null
+ * @var string|null
* @ORM\Column(type="bigint", nullable=true)
*/
private $bigNumber;
}
```
<br>
### ChangeSetParametersArrayToArrayCollectionRector
Change array to ArrayCollection in setParameters method of query builder
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\MethodCall\ChangeSetParametersArrayToArrayCollectionRector`](../rules/DoctrineCodeQuality/Rector/MethodCall/ChangeSetParametersArrayToArrayCollectionRector.php)
```diff
+use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;
+use Doctrine\ORM\Query\Parameter;
class SomeRepository extends EntityRepository
{
public function getSomething()
{
return $this
->createQueryBuilder('sm')
->select('sm')
->where('sm.foo = :bar')
- ->setParameters([
- 'bar' => 'baz'
- ])
+ ->setParameters(new ArrayCollection([
+ new Parameter('bar', 'baz'),
+ ]))
->getQuery()
->getResult()
;
}
}
```
<br>
### CorrectDefaultTypesOnEntityPropertyRector
Change default value types to match Doctrine annotation type
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Property\CorrectDefaultTypesOnEntityPropertyRector`](../rules/DoctrineCodeQuality/Rector/Property/CorrectDefaultTypesOnEntityPropertyRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class User
{
/**
* @ORM\Column(name="is_old", type="boolean")
*/
- private $isOld = '0';
+ private $isOld = false;
}
```
<br>
### ImproveDoctrineCollectionDocTypeInEntityRector
Improve @var, `@param` and `@return` types for Doctrine collections to make them useful both for PHPStan and PHPStorm
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Property\ImproveDoctrineCollectionDocTypeInEntityRector`](../rules/DoctrineCodeQuality/Rector/Property/ImproveDoctrineCollectionDocTypeInEntityRector.php)
```diff
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeClass
{
/**
* @ORM\OneToMany(targetEntity=Training::class, mappedBy="trainer")
- * @var Collection|Trainer[]
+ * @var Collection<int, Training>|Trainer[]
*/
private $trainings = [];
}
```
<br>
### InitializeDefaultEntityCollectionRector
Initialize collection property in Entity constructor
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Class_\InitializeDefaultEntityCollectionRector`](../rules/DoctrineCodeQuality/Rector/Class_/InitializeDefaultEntityCollectionRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeClass
{
/**
* @ORM\OneToMany(targetEntity="MarketingEvent")
*/
private $marketingEvents = [];
+
+ public function __construct()
+ {
+ $this->marketingEvents = new ArrayCollection();
+ }
}
```
<br>
### MakeEntityDateTimePropertyDateTimeInterfaceRector
Make maker bundle generate DateTime property accept DateTimeInterface too
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\ClassMethod\MakeEntityDateTimePropertyDateTimeInterfaceRector`](../rules/DoctrineCodeQuality/Rector/ClassMethod/MakeEntityDateTimePropertyDateTimeInterfaceRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class User
{
/**
- * @var DateTime|null
+ * @var DateTimeInterface|null
*/
private $bornAt;
public function setBornAt(DateTimeInterface $bornAt)
{
$this->bornAt = $bornAt;
}
}
```
<br>
### MakeEntitySetterNullabilityInSyncWithPropertyRector
Make nullability in setter class method with respect to property
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\ClassMethod\MakeEntitySetterNullabilityInSyncWithPropertyRector`](../rules/DoctrineCodeQuality/Rector/ClassMethod/MakeEntitySetterNullabilityInSyncWithPropertyRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class Product
{
/**
* @ORM\ManyToOne(targetEntity="AnotherEntity")
*/
private $anotherEntity;
- public function setAnotherEntity(?AnotherEntity $anotherEntity)
+ public function setAnotherEntity(AnotherEntity $anotherEntity)
{
$this->anotherEntity = $anotherEntity;
}
}
```
<br>
2019-12-26 10:21:09 +00:00
### MoveCurrentDateTimeDefaultInEntityToConstructorRector
2020-01-08 00:05:45 +00:00
Move default value for entity property to constructor, the safest place
2020-01-08 00:05:45 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Class_\MoveCurrentDateTimeDefaultInEntityToConstructorRector`](../rules/DoctrineCodeQuality/Rector/Class_/MoveCurrentDateTimeDefaultInEntityToConstructorRector.php)
2020-01-08 00:05:45 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class User
{
/**
* @var DateTimeInterface
*
- * @ORM\Column(type="datetime", nullable=false, options={"default"="now()"})
+ * @ORM\Column(type="datetime", nullable=false)
*/
- private $when = 'now()';
+ private $when;
+
+ public function __construct()
+ {
+ $this->when = new \DateTime();
+ }
}
2020-01-08 00:05:45 +00:00
```
<br>
2020-01-08 00:05:45 +00:00
### MoveRepositoryFromParentToConstructorRector
2020-01-08 00:05:45 +00:00
Turns parent EntityRepository class to constructor dependency
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Class_\MoveRepositoryFromParentToConstructorRector`](../rules/DoctrineCodeQuality/Rector/Class_/MoveRepositoryFromParentToConstructorRector.php)
```diff
namespace App\Repository;
+use App\Entity\Post;
use Doctrine\ORM\EntityRepository;
+use Doctrine\ORM\EntityManagerInterface;
-final class PostRepository extends EntityRepository
+final class PostRepository
{
+ /**
+ * @var \Doctrine\ORM\EntityRepository<Post>
+ */
+ private EntityRepository $repository;
+
+ public function __construct(EntityManagerInterface $entityManager)
+ {
+ $this->repository = $entityManager->getRepository(Post::class);
+ }
}
```
<br>
### RemoveRedundantDefaultClassAnnotationValuesRector
Removes redundant default values from Doctrine ORM annotations on class level
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Class_\RemoveRedundantDefaultClassAnnotationValuesRector`](../rules/DoctrineCodeQuality/Rector/Class_/RemoveRedundantDefaultClassAnnotationValuesRector.php)
2020-01-08 00:05:45 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
2020-01-08 00:05:45 +00:00
/**
- * @ORM\Entity(readOnly=false)
+ * @ORM\Entity()
*/
class SomeClass
2020-01-08 00:05:45 +00:00
{
}
```
<br>
2020-01-08 00:05:45 +00:00
### RemoveRedundantDefaultPropertyAnnotationValuesRector
2019-12-26 10:21:09 +00:00
Removes redundant default values from Doctrine ORM annotations on class property level
2019-12-26 10:21:09 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineCodeQuality\Rector\Property\RemoveRedundantDefaultPropertyAnnotationValuesRector`](../rules/DoctrineCodeQuality/Rector/Property/RemoveRedundantDefaultPropertyAnnotationValuesRector.php)
2020-01-08 00:05:45 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
2020-01-08 00:05:45 +00:00
/**
* @ORM\Entity
*/
class SomeClass
2020-01-08 00:05:45 +00:00
{
/**
* @ORM\ManyToOne(targetEntity=Training::class)
- * @ORM\JoinColumn(name="training", unique=false)
+ * @ORM\JoinColumn(name="training")
*/
private $training;
2020-01-08 00:05:45 +00:00
}
```
<br>
2020-01-08 00:05:45 +00:00
## DoctrineGedmoToKnplabs
2019-12-26 10:21:09 +00:00
### BlameableBehaviorRector
2019-12-26 10:21:09 +00:00
Change Blameable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\BlameableBehaviorRector`](../rules/DoctrineGedmoToKnplabs/Rector/Class_/BlameableBehaviorRector.php)
2019-12-26 10:21:09 +00:00
```diff
-use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
+use Knp\DoctrineBehaviors\Contract\Entity\BlameableInterface;
+use Knp\DoctrineBehaviors\Model\Blameable\BlameableTrait;
/**
* @ORM\Entity
*/
-class SomeClass
+class SomeClass implements BlameableInterface
2019-12-26 10:21:09 +00:00
{
- /**
- * @Gedmo\Blameable(on="create")
- */
- private $createdBy;
-
- /**
- * @Gedmo\Blameable(on="update")
- */
- private $updatedBy;
-
- /**
- * @Gedmo\Blameable(on="change", field={"title", "body"})
- */
- private $contentChangedBy;
-
- public function getCreatedBy()
- {
- return $this->createdBy;
- }
-
- public function getUpdatedBy()
- {
- return $this->updatedBy;
- }
-
- public function getContentChangedBy()
- {
- return $this->contentChangedBy;
- }
+ use BlameableTrait;
2019-12-26 10:21:09 +00:00
}
```
<br>
2019-12-27 17:50:00 +00:00
### LoggableBehaviorRector
2019-12-26 10:21:09 +00:00
Change Loggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2019-12-26 10:21:09 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\LoggableBehaviorRector`](../rules/DoctrineGedmoToKnplabs/Rector/Class_/LoggableBehaviorRector.php)
2019-12-26 10:21:09 +00:00
```diff
-use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
+use Knp\DoctrineBehaviors\Model\Loggable\LoggableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\LoggableInterface;
2019-12-26 10:21:09 +00:00
/**
* @ORM\Entity
- * @Gedmo\Loggable
*/
-class SomeClass
+class SomeClass implements LoggableInterface
2019-12-26 10:21:09 +00:00
{
+ use LoggableTrait;
+
/**
- * @Gedmo\Versioned
* @ORM\Column(name="title", type="string", length=8)
*/
private $title;
2019-12-26 10:21:09 +00:00
}
```
<br>
2019-12-26 10:21:09 +00:00
### SluggableBehaviorRector
Change Sluggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\SluggableBehaviorRector`](../rules/DoctrineGedmoToKnplabs/Rector/Class_/SluggableBehaviorRector.php)
```diff
use Gedmo\Mapping\Annotation as Gedmo;
+use Knp\DoctrineBehaviors\Model\Sluggable\SluggableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\SluggableInterface;
-class SomeClass
+class SomeClass implements SluggableInterface
{
+ use SluggableTrait;
+
/**
- * @Gedmo\Slug(fields={"name"})
+ * @return string[]
*/
- private $slug;
-
- public function getSlug(): ?string
+ public function getSluggableFields(): array
{
- return $this->slug;
- }
-
- public function setSlug(?string $slug): void
- {
- $this->slug = $slug;
+ return ['name'];
}
}
```
<br>
### SoftDeletableBehaviorRector
Change SoftDeletable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\SoftDeletableBehaviorRector`](../rules/DoctrineGedmoToKnplabs/Rector/Class_/SoftDeletableBehaviorRector.php)
```diff
-use Gedmo\Mapping\Annotation as Gedmo;
+use Knp\DoctrineBehaviors\Contract\Entity\SoftDeletableInterface;
+use Knp\DoctrineBehaviors\Model\SoftDeletable\SoftDeletableTrait;
-/**
- * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=true)
- */
-class SomeClass
+class SomeClass implements SoftDeletableInterface
{
- /**
- * @ORM\Column(name="deletedAt", type="datetime", nullable=true)
- */
- private $deletedAt;
-
- public function getDeletedAt()
- {
- return $this->deletedAt;
- }
-
- public function setDeletedAt($deletedAt)
- {
- $this->deletedAt = $deletedAt;
- }
+ use SoftDeletableTrait;
}
```
<br>
### TimestampableBehaviorRector
Change Timestampable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\TimestampableBehaviorRector`](../rules/DoctrineGedmoToKnplabs/Rector/Class_/TimestampableBehaviorRector.php)
```diff
-use Gedmo\Timestampable\Traits\TimestampableEntity;
+use Knp\DoctrineBehaviors\Model\Timestampable\TimestampableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\TimestampableInterface;
-class SomeClass
+class SomeClass implements TimestampableInterface
{
- use TimestampableEntity;
+ use TimestampableTrait;
}
```
<br>
### TranslationBehaviorRector
Change Translation from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\TranslationBehaviorRector`](../rules/DoctrineGedmoToKnplabs/Rector/Class_/TranslationBehaviorRector.php)
```diff
-use Gedmo\Mapping\Annotation as Gedmo;
-use Doctrine\ORM\Mapping as ORM;
-use Gedmo\Translatable\Translatable;
+use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
-/**
- * @ORM\Table
- */
-class Article implements Translatable
+class SomeClass implements TranslatableInterface
{
+ use TranslatableTrait;
+}
+
+
+use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
+use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;
+
+class SomeClassTranslation implements TranslationInterface
+{
+ use TranslationTrait;
+
/**
- * @Gedmo\Translatable
* @ORM\Column(length=128)
*/
private $title;
/**
- * @Gedmo\Translatable
* @ORM\Column(type="text")
*/
private $content;
-
- /**
- * @Gedmo\Locale
- * Used locale to override Translation listener`s locale
- * this is not a mapped field of entity metadata, just a simple property
- * and it is not necessary because globally locale can be set in listener
- */
- private $locale;
-
- public function setTitle($title)
- {
- $this->title = $title;
- }
-
- public function getTitle()
- {
- return $this->title;
- }
-
- public function setContent($content)
- {
- $this->content = $content;
- }
-
- public function getContent()
- {
- return $this->content;
- }
-
- public function setTranslatableLocale($locale)
- {
- $this->locale = $locale;
- }
}
```
<br>
### TreeBehaviorRector
Change Tree from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2021-03-12 23:52:38 +00:00
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\TreeBehaviorRector`](../rules/DoctrineGedmoToKnplabs/Rector/Class_/TreeBehaviorRector.php)
```diff
-use Doctrine\Common\Collections\Collection;
-use Gedmo\Mapping\Annotation as Gedmo;
+use Knp\DoctrineBehaviors\Contract\Entity\TreeNodeInterface;
+use Knp\DoctrineBehaviors\Model\Tree\TreeNodeTrait;
-/**
- * @Gedmo\Tree(type="nested")
- */
-class SomeClass
+class SomeClass implements TreeNodeInterface
{
- /**
- * @Gedmo\TreeLeft
- * @ORM\Column(name="lft", type="integer")
- * @var int
- */
- private $lft;
-
- /**
- * @Gedmo\TreeRight
- * @ORM\Column(name="rgt", type="integer")
- * @var int
- */
- private $rgt;
-
- /**
- * @Gedmo\TreeLevel
- * @ORM\Column(name="lvl", type="integer")
- * @var int
- */
- private $lvl;
-
- /**
- * @Gedmo\TreeRoot
- * @ORM\ManyToOne(targetEntity="Category")
- * @ORM\JoinColumn(name="tree_root", referencedColumnName="id", onDelete="CASCADE")
- * @var Category
- */
- private $root;
-
- /**
- * @Gedmo\TreeParent
- * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
- * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
- * @var Category
- */
- private $parent;
-
- /**
- * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
- * @var Category[]|Collection
- */
- private $children;
-
- public function getRoot(): self
- {
- return $this->root;
- }
-
- public function setParent(self $category): void
- {
- $this->parent = $category;
- }
-
- public function getParent(): self
- {
- return $this->parent;
- }
+ use TreeNodeTrait;
}
```
<br>
## DowngradePhp70
### DowngradeTypeDeclarationRector
Remove the type params and return type, add `@param` and `@return` tags instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp70\Rector\FunctionLike\DowngradeTypeDeclarationRector`](../rules/DowngradePhp70/Rector/FunctionLike/DowngradeTypeDeclarationRector.php)
```diff
class SomeClass
{
- public function run(string $input): string
+ /**
+ * @param string $input
+ * @return string
+ */
+ public function run($input)
{
}
}
```
<br>
## DowngradePhp71
### DowngradeClassConstantVisibilityRector
Downgrade class constant visibility
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp71\Rector\ClassConst\DowngradeClassConstantVisibilityRector`](../rules/DowngradePhp71/Rector/ClassConst/DowngradeClassConstantVisibilityRector.php)
```diff
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;
}
```
<br>
### DowngradeIterablePseudoTypeDeclarationRector
Remove the iterable pseudo type params and returns, add `@param` and `@return` tags instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp71\Rector\FunctionLike\DowngradeIterablePseudoTypeDeclarationRector`](../rules/DowngradePhp71/Rector/FunctionLike/DowngradeIterablePseudoTypeDeclarationRector.php)
```diff
class SomeClass
{
- public function run(iterable $iterator): iterable
+ /**
+ * @param mixed[]|\Traversable $iterator
+ * @return mixed[]|\Traversable
+ */
+ public function run($iterator)
{
// do something
}
}
```
<br>
### DowngradeNegativeStringOffsetToStrlenRector
Downgrade negative string offset to `strlen`
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp71\Rector\String_\DowngradeNegativeStringOffsetToStrlenRector`](../rules/DowngradePhp71/Rector/String_/DowngradeNegativeStringOffsetToStrlenRector.php)
```diff
-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);
```
<br>
### DowngradeNullableTypeDeclarationRector
Remove the nullable type params, add `@param` tags instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp71\Rector\FunctionLike\DowngradeNullableTypeDeclarationRector`](../rules/DowngradePhp71/Rector/FunctionLike/DowngradeNullableTypeDeclarationRector.php)
```diff
class SomeClass
{
- public function run(?string $input): ?string
+ /**
+ * @param string|null $input
+ * @return string|null $input
+ */
+ public function run($input)
{
}
}
```
<br>
### DowngradePipeToMultiCatchExceptionRector
Downgrade single one | separated to multi catch exception
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp71\Rector\TryCatch\DowngradePipeToMultiCatchExceptionRector`](../rules/DowngradePhp71/Rector/TryCatch/DowngradePipeToMultiCatchExceptionRector.php)
```diff
try {
// Some code...
- } catch (ExceptionType1 | ExceptionType2 $exception) {
+} catch (ExceptionType1 $exception) {
$sameCode;
- }
+} catch (ExceptionType2 $exception) {
+ $sameCode;
+}
```
<br>
### DowngradeVoidTypeDeclarationRector
2020-10-09 20:01:37 +00:00
Remove "void" return type, add a `"@return` void" tag instead
2020-10-09 20:01:37 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp71\Rector\FunctionLike\DowngradeVoidTypeDeclarationRector`](../rules/DowngradePhp71/Rector/FunctionLike/DowngradeVoidTypeDeclarationRector.php)
2020-10-07 13:41:19 +00:00
```diff
class SomeClass
{
- public function run(): void
+ /**
+ * @return void
+ */
+ public function run()
2020-10-07 13:41:19 +00:00
{
}
}
```
<br>
### SymmetricArrayDestructuringToListRector
Downgrade Symmetric array destructuring to `list()` function
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp71\Rector\Array_\SymmetricArrayDestructuringToListRector`](../rules/DowngradePhp71/Rector/Array_/SymmetricArrayDestructuringToListRector.php)
```diff
-[$id1, $name1] = $data;
+list($id1, $name1) = $data;
```
<br>
## DowngradePhp72
### DowngradeObjectTypeDeclarationRector
Remove the "object" param and return type, add a `@param` and `@return` tags instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp72\Rector\FunctionLike\DowngradeObjectTypeDeclarationRector`](../rules/DowngradePhp72/Rector/FunctionLike/DowngradeObjectTypeDeclarationRector.php)
```diff
class SomeClass
{
- public function someFunction(object $someObject): object
+ /**
+ * @param object $someObject
+ * @return object
+ */
+ public function someFunction($someObject)
{
}
}
```
<br>
### DowngradeParameterTypeWideningRector
Remove argument type declarations in the parent and in all child classes, whenever some child class removes it
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp72\Rector\ClassMethod\DowngradeParameterTypeWideningRector`](../rules/DowngradePhp72/Rector/ClassMethod/DowngradeParameterTypeWideningRector.php)
```diff
interface A
{
- public function test(array $input);
+ /**
+ * @param array $input
+ */
+ public function test($input);
}
class B implements A
{
public function test($input){} // type omitted for $input
}
class C implements A
{
- public function test(array $input){}
+ /**
+ * @param array $input
+ */
+ public function test($input);
}
```
<br>
## DowngradePhp73
### DowngradeFlexibleHeredocSyntaxRector
Changes heredoc/nowdoc that contains closing word to safe wrapper name
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp73\Rector\String_\DowngradeFlexibleHeredocSyntaxRector`](../rules/DowngradePhp73/Rector/String_/DowngradeFlexibleHeredocSyntaxRector.php)
```diff
$query = <<<SQL
- SELECT *
- FROM `table`
- WHERE `column` = true;
- SQL;
+SELECT *
+FROM `table`
+WHERE `column` = true;
+SQL;
```
<br>
### DowngradeListReferenceAssignmentRector
Convert the list reference assignment to its equivalent PHP 7.2 code
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp73\Rector\List_\DowngradeListReferenceAssignmentRector`](../rules/DowngradePhp73/Rector/List_/DowngradeListReferenceAssignmentRector.php)
```diff
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];
}
}
```
<br>
### DowngradeTrailingCommasInFunctionCallsRector
Remove trailing commas in function calls
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp73\Rector\FuncCall\DowngradeTrailingCommasInFunctionCallsRector`](../rules/DowngradePhp73/Rector/FuncCall/DowngradeTrailingCommasInFunctionCallsRector.php)
```diff
class SomeClass
{
public function __construct(string $value)
{
$compacted = compact(
'posts',
- 'units',
+ 'units'
);
}
}
```
<br>
### SetCookieOptionsArrayToArgumentsRector
Convert `setcookie` option array to arguments
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp73\Rector\FuncCall\SetCookieOptionsArrayToArgumentsRector`](../rules/DowngradePhp73/Rector/FuncCall/SetCookieOptionsArrayToArgumentsRector.php)
```diff
-setcookie('name', $value, ['expires' => 360]);
+setcookie('name', $value, 360);
```
<br>
## DowngradePhp74
### ArrowFunctionToAnonymousFunctionRector
Replace arrow functions with anonymous functions
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\ArrowFunction\ArrowFunctionToAnonymousFunctionRector`](../rules/DowngradePhp74/Rector/ArrowFunction/ArrowFunctionToAnonymousFunctionRector.php)
```diff
class SomeClass
{
public function run()
{
$delimiter = ",";
- $callable = fn($matches) => $delimiter . strtolower($matches[1]);
+ $callable = function ($matches) use ($delimiter) {
+ return $delimiter . strtolower($matches[1]);
+ };
}
}
```
<br>
### DowngradeArrayMergeCallWithoutArgumentsRector
Add missing param to `array_merge` and `array_merge_recursive`
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\FuncCall\DowngradeArrayMergeCallWithoutArgumentsRector`](../rules/DowngradePhp74/Rector/FuncCall/DowngradeArrayMergeCallWithoutArgumentsRector.php)
```diff
class SomeClass
{
public function run()
{
- array_merge();
- array_merge_recursive();
+ array_merge([]);
+ array_merge_recursive([]);
}
}
```
<br>
### DowngradeArraySpreadRector
Replace array spread with `array_merge` function
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\Array_\DowngradeArraySpreadRector`](../rules/DowngradePhp74/Rector/Array_/DowngradeArraySpreadRector.php)
```diff
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']);
}
}
```
<br>
### DowngradeContravariantArgumentTypeRector
Remove contravariant argument type declarations
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\ClassMethod\DowngradeContravariantArgumentTypeRector`](../rules/DowngradePhp74/Rector/ClassMethod/DowngradeContravariantArgumentTypeRector.php)
```diff
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)
{
}
}
```
<br>
### DowngradeCovariantReturnTypeRector
Make method return same type as parent
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\ClassMethod\DowngradeCovariantReturnTypeRector`](../rules/DowngradePhp74/Rector/ClassMethod/DowngradeCovariantReturnTypeRector.php)
```diff
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
{
}
}
```
<br>
### DowngradeFreadFwriteFalsyToNegationRector
Changes `fread()` or `fwrite()` compare to false to negation check
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\Identical\DowngradeFreadFwriteFalsyToNegationRector`](../rules/DowngradePhp74/Rector/Identical/DowngradeFreadFwriteFalsyToNegationRector.php)
```diff
-fread($handle, $length) === false;
-fwrite($fp, '1') === false;
+!fread($handle, $length);
+!fwrite($fp, '1');
```
<br>
### DowngradeNullCoalescingOperatorRector
Remove null coalescing operator ??=
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\Coalesce\DowngradeNullCoalescingOperatorRector`](../rules/DowngradePhp74/Rector/Coalesce/DowngradeNullCoalescingOperatorRector.php)
```diff
$array = [];
-$array['user_id'] ??= 'value';
+$array['user_id'] = $array['user_id'] ?? 'value';
```
<br>
### DowngradeNumericLiteralSeparatorRector
Remove "_" as thousands separator in numbers
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\LNumber\DowngradeNumericLiteralSeparatorRector`](../rules/DowngradePhp74/Rector/LNumber/DowngradeNumericLiteralSeparatorRector.php)
```diff
class SomeClass
{
public function run()
{
- $int = 1_000;
- $float = 1_000_500.001;
+ $int = 1000;
+ $float = 1000500.001;
}
}
```
<br>
### DowngradeSelfTypeDeclarationRector
Remove "self" return type, add a `"@return` self" tag instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\ClassMethod\DowngradeSelfTypeDeclarationRector`](../rules/DowngradePhp74/Rector/ClassMethod/DowngradeSelfTypeDeclarationRector.php)
```diff
class SomeClass
{
- public function foo(): self
+ public function foo()
{
return $this;
}
}
```
<br>
### DowngradeStripTagsCallWithArrayRector
Convert 2nd param to `strip_tags` from array to string
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\FuncCall\DowngradeStripTagsCallWithArrayRector`](../rules/DowngradePhp74/Rector/FuncCall/DowngradeStripTagsCallWithArrayRector.php)
```diff
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);
}
}
```
<br>
### DowngradeTypedPropertyRector
Changes property type definition from type definitions to `@var` annotations.
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp74\Rector\Property\DowngradeTypedPropertyRector`](../rules/DowngradePhp74/Rector/Property/DowngradeTypedPropertyRector.php)
```diff
class SomeClass
{
- private string $property;
+ /**
+ * @var string
+ */
+ private $property;
}
```
<br>
## DowngradePhp80
### DowngradeClassOnObjectToGetClassRector
Change `$object::class` to get_class($object)
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\ClassConstFetch\DowngradeClassOnObjectToGetClassRector`](../rules/DowngradePhp80/Rector/ClassConstFetch/DowngradeClassOnObjectToGetClassRector.php)
```diff
class SomeClass
{
public function run($object)
{
- return $object::class;
+ return get_class($object);
}
}
```
<br>
### DowngradeMatchToSwitchRector
Downgrade `match()` to `switch()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\Expression\DowngradeMatchToSwitchRector`](../rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php)
```diff
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;
+ }
}
}
```
<br>
### DowngradeMixedTypeDeclarationRector
Remove the "mixed" param and return type, add a `@param` and `@return` tag instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\FunctionLike\DowngradeMixedTypeDeclarationRector`](../rules/DowngradePhp80/Rector/FunctionLike/DowngradeMixedTypeDeclarationRector.php)
```diff
class SomeClass
{
- public function someFunction(mixed $anything): mixed
+ /**
+ * @param mixed $anything
+ * @return mixed
+ */
+ public function someFunction($anything)
{
}
}
```
<br>
### DowngradeNonCapturingCatchesRector
Downgrade catch () without variable to one
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\Catch_\DowngradeNonCapturingCatchesRector`](../rules/DowngradePhp80/Rector/Catch_/DowngradeNonCapturingCatchesRector.php)
```diff
class SomeClass
{
public function run()
{
try {
// code
- } catch (\Exception) {
+ } catch (\Exception $exception) {
// error
}
}
}
```
<br>
### DowngradeNullsafeToTernaryOperatorRector
Change nullsafe operator to ternary operator rector
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\NullsafeMethodCall\DowngradeNullsafeToTernaryOperatorRector`](../rules/DowngradePhp80/Rector/NullsafeMethodCall/DowngradeNullsafeToTernaryOperatorRector.php)
```diff
-$dateAsString = $booking->getStartDate()?->asDateTimeString();
-$dateAsString = $booking->startDate?->dateTimeString;
+$dateAsString = $booking->getStartDate() ? $booking->getStartDate()->asDateTimeString() : null;
+$dateAsString = $booking->startDate ? $booking->startDate->dateTimeString : null;
```
<br>
### DowngradePropertyPromotionRector
Change constructor property promotion to property asssign
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\Class_\DowngradePropertyPromotionRector`](../rules/DowngradePhp80/Rector/Class_/DowngradePropertyPromotionRector.php)
```diff
class SomeClass
{
- public function __construct(public float $value = 0.0)
+ public float $value;
+
+ public function __construct(float $value = 0.0)
{
+ $this->value = $value;
}
}
```
<br>
### DowngradeStaticTypeDeclarationRector
Remove "static" return and param type, add a `"@param` `$this"` and `"@return` `$this"` tag instead
- class: [`Rector\DowngradePhp80\Rector\ClassMethod\DowngradeStaticTypeDeclarationRector`](../rules/DowngradePhp80/Rector/ClassMethod/DowngradeStaticTypeDeclarationRector.php)
2020-07-24 11:46:57 +00:00
```diff
class SomeClass
2020-07-24 11:46:57 +00:00
{
- public function getStatic(): static
+ /**
+ * @return static
+ */
+ public function getStatic()
{
return new static();
}
2020-07-24 11:46:57 +00:00
}
```
<br>
### DowngradeTrailingCommasInParamUseRector
Remove trailing commas in param or use list
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\ClassMethod\DowngradeTrailingCommasInParamUseRector`](../rules/DowngradePhp80/Rector/ClassMethod/DowngradeTrailingCommasInParamUseRector.php)
```diff
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)
{
}
```
<br>
### DowngradeUnionTypeDeclarationRector
Remove the union type params and returns, add `@param/@return` tags instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\FunctionLike\DowngradeUnionTypeDeclarationRector`](../rules/DowngradePhp80/Rector/FunctionLike/DowngradeUnionTypeDeclarationRector.php)
```diff
class SomeClass
{
- public function echoInput(string|int $input): int|bool
+ /**
+ * @param string|int $input
+ * @return int|bool
+ */
+ public function echoInput($input)
{
echo $input;
}
}
```
<br>
### DowngradeUnionTypeTypedPropertyRector
2019-03-09 13:24:30 +00:00
Removes union type property type definition, adding `@var` annotations instead.
2019-03-09 13:24:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\DowngradePhp80\Rector\Property\DowngradeUnionTypeTypedPropertyRector`](../rules/DowngradePhp80/Rector/Property/DowngradeUnionTypeTypedPropertyRector.php)
2019-03-09 13:24:30 +00:00
```diff
class SomeClass
{
- private string|int $property;
+ /**
+ * @var string|int
+ */
+ private $property;
}
```
<br>
## EarlyReturn
2019-09-19 09:27:29 +00:00
### ChangeAndIfToEarlyReturnRector
2019-09-19 09:27:29 +00:00
Changes if && to early return
2019-09-19 09:27:29 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\If_\ChangeAndIfToEarlyReturnRector`](../rules/EarlyReturn/Rector/If_/ChangeAndIfToEarlyReturnRector.php)
2019-09-19 09:27:29 +00:00
```diff
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;
}
}
```
<br>
### ChangeIfElseValueAssignToEarlyReturnRector
Change if/else value to early return
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector`](../rules/EarlyReturn/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector.php)
```diff
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;
}
}
```
<br>
### ChangeNestedForeachIfsToEarlyContinueRector
Change nested ifs to foreach with continue
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\Foreach_\ChangeNestedForeachIfsToEarlyContinueRector`](../rules/EarlyReturn/Rector/Foreach_/ChangeNestedForeachIfsToEarlyContinueRector.php)
2019-03-09 13:24:30 +00:00
```diff
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';
}
}
}
```
<br>
2019-03-09 13:24:30 +00:00
### ChangeNestedIfsToEarlyReturnRector
Change nested ifs to early return
2019-03-09 13:24:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\If_\ChangeNestedIfsToEarlyReturnRector`](../rules/EarlyReturn/Rector/If_/ChangeNestedIfsToEarlyReturnRector.php)
2019-03-09 13:24:30 +00:00
```diff
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';
}
}
2020-05-29 10:41:25 +00:00
```
<br>
### ChangeOrIfContinueToMultiContinueRector
2020-05-29 10:41:25 +00:00
Changes if && to early return
2020-05-29 10:41:25 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\If_\ChangeOrIfContinueToMultiContinueRector`](../rules/EarlyReturn/Rector/If_/ChangeOrIfContinueToMultiContinueRector.php)
```diff
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);
}
}
}
```
<br>
### ChangeOrIfReturnToEarlyReturnRector
Changes if || with return to early return
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\If_\ChangeOrIfReturnToEarlyReturnRector`](../rules/EarlyReturn/Rector/If_/ChangeOrIfReturnToEarlyReturnRector.php)
2020-05-29 10:41:25 +00:00
```diff
class SomeClass
{
public function run($a, $b)
{
- if ($a || $b) {
+ if ($a) {
+ return null;
+ }
+ if ($b) {
return null;
}
return 'another';
}
}
```
<br>
### PreparedValueToEarlyReturnRector
Return early prepared value in ifs
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\Return_\PreparedValueToEarlyReturnRector`](../rules/EarlyReturn/Rector/Return_/PreparedValueToEarlyReturnRector.php)
```diff
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;
}
}
```
<br>
### RemoveAlwaysElseRector
Split if statement, when if condition always break execution flow
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\If_\RemoveAlwaysElseRector`](../rules/EarlyReturn/Rector/If_/RemoveAlwaysElseRector.php)
```diff
class SomeClass
{
public function run($value)
{
if ($value) {
throw new \InvalidStateException;
- } else {
- return 10;
}
+
+ return 10;
}
}
```
<br>
### ReturnAfterToEarlyOnBreakRector
2019-03-16 20:31:46 +00:00
Change return after foreach to early return in foreach on break
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\Foreach_\ReturnAfterToEarlyOnBreakRector`](../rules/EarlyReturn/Rector/Foreach_/ReturnAfterToEarlyOnBreakRector.php)
```diff
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;
}
}
```
<br>
### ReturnBinaryAndToEarlyReturnRector
Changes Single return of && to early returns
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\Return_\ReturnBinaryAndToEarlyReturnRector`](../rules/EarlyReturn/Rector/Return_/ReturnBinaryAndToEarlyReturnRector.php)
```diff
class SomeClass
{
public function accept()
{
- return $this->something() && $this->somethingelse();
+ if (!$this->something()) {
+ return false;
+ }
+ return (bool) $this->somethingelse();
}
}
```
<br>
### ReturnBinaryOrToEarlyReturnRector
Changes Single return of || to early returns
2021-03-12 23:52:38 +00:00
- class: [`Rector\EarlyReturn\Rector\Return_\ReturnBinaryOrToEarlyReturnRector`](../rules/EarlyReturn/Rector/Return_/ReturnBinaryOrToEarlyReturnRector.php)
```diff
class SomeClass
{
public function accept()
{
- return $this->something() || $this->somethingElse();
+ if ($this->something()) {
+ return true;
+ }
+ return (bool) $this->somethingElse();
}
}
```
<br>
2021-01-30 20:30:37 +00:00
## Generics
### GenericsPHPStormMethodAnnotationRector
Complete PHPStorm `@method` annotations, to make it understand the PHPStan/Psalm generics
2021-03-12 23:52:38 +00:00
- class: [`Rector\Generics\Rector\Class_\GenericsPHPStormMethodAnnotationRector`](../rules/Generics/Rector/Class_/GenericsPHPStormMethodAnnotationRector.php)
2021-01-30 20:30:37 +00:00
```diff
/**
* @template TEntity as object
*/
abstract class AbstractRepository
{
/**
* @return TEntity
*/
public function find($id)
{
}
}
/**
* @template TEntity as SomeObject
* @extends AbstractRepository<TEntity>
+ * @method SomeObject find($id)
*/
final class AndroidDeviceRepository extends AbstractRepository
{
}
```
<br>
## Laravel
### AddGuardToLoginEventRector
Add new `$guard` argument to Illuminate\Auth\Events\Login
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\New_\AddGuardToLoginEventRector`](../rules/Laravel/Rector/New_/AddGuardToLoginEventRector.php)
```diff
use Illuminate\Auth\Events\Login;
final class SomeClass
{
public function run(): void
{
- $loginEvent = new Login('user', false);
+ $guard = config('auth.defaults.guard');
+ $loginEvent = new Login($guard, 'user', false);
}
}
```
<br>
2019-12-22 18:38:09 +00:00
### AddMockConsoleOutputFalseToConsoleTestsRector
Add "$this->mockConsoleOutput = false"; to console tests that work with output content
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\Class_\AddMockConsoleOutputFalseToConsoleTestsRector`](../rules/Laravel/Rector/Class_/AddMockConsoleOutputFalseToConsoleTestsRector.php)
```diff
use Illuminate\Support\Facades\Artisan;
use Illuminate\Foundation\Testing\TestCase;
final class SomeTest extends TestCase
{
+ public function setUp(): void
+ {
+ parent::setUp();
+
+ $this->mockConsoleOutput = false;
+ }
+
public function test(): void
{
$this->assertEquals('content', \trim((new Artisan())::output()));
}
}
```
<br>
### AddParentBootToModelClassMethodRector
Add `parent::boot();` call to `boot()` class method in child of Illuminate\Database\Eloquent\Model
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\ClassMethod\AddParentBootToModelClassMethodRector`](../rules/Laravel/Rector/ClassMethod/AddParentBootToModelClassMethodRector.php)
```diff
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function boot()
{
+ parent::boot();
}
}
```
<br>
### CallOnAppArrayAccessToStandaloneAssignRector
Replace magical call on `$this->app["something"]` to standalone type assign variable
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\Assign\CallOnAppArrayAccessToStandaloneAssignRector`](../rules/Laravel/Rector/Assign/CallOnAppArrayAccessToStandaloneAssignRector.php)
```diff
class SomeClass
{
/**
* @var \Illuminate\Contracts\Foundation\Application
*/
private $app;
public function run()
{
- $validator = $this->app['validator']->make('...');
+ /** @var \Illuminate\Validation\Factory $validationFactory */
+ $validationFactory = $this->app['validator'];
+ $validator = $validationFactory->make('...');
}
}
```
<br>
### ChangeQueryWhereDateValueWithCarbonRector
Add `parent::boot();` call to `boot()` class method in child of Illuminate\Database\Eloquent\Model
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\MethodCall\ChangeQueryWhereDateValueWithCarbonRector`](../rules/Laravel/Rector/MethodCall/ChangeQueryWhereDateValueWithCarbonRector.php)
```diff
use Illuminate\Database\Query\Builder;
final class SomeClass
{
public function run(Builder $query)
{
- $query->whereDate('created_at', '<', Carbon::now());
+ $dateTime = Carbon::now();
+ $query->whereDate('created_at', '<=', $dateTime);
+ $query->whereTime('created_at', '<=', $dateTime);
}
}
```
<br>
### HelperFuncCallToFacadeClassRector
2019-02-18 15:51:24 +00:00
Change `app()` func calls to facade calls
2019-02-18 15:51:24 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\FuncCall\HelperFuncCallToFacadeClassRector`](../rules/Laravel/Rector/FuncCall/HelperFuncCallToFacadeClassRector.php)
2019-02-18 15:51:24 +00:00
```diff
class SomeClass
2019-02-18 15:51:24 +00:00
{
public function run()
{
- return app('translator')->trans('value');
+ return \Illuminate\Support\Facades\App::get('translator')->trans('value');
}
2019-02-18 15:51:24 +00:00
}
```
<br>
2019-02-18 15:51:24 +00:00
### MakeTaggedPassedToParameterIterableTypeRector
Change param type to iterable, if passed one
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\New_\MakeTaggedPassedToParameterIterableTypeRector`](../rules/Laravel/Rector/New_/MakeTaggedPassedToParameterIterableTypeRector.php)
```diff
class AnotherClass
{
/**
* @var \Illuminate\Contracts\Foundation\Application
*/
private $app;
public function create()
{
$tagged = $this->app->tagged('some_tagged');
return new SomeClass($tagged);
}
}
class SomeClass
{
- public function __construct(array $items)
+ public function __construct(iterable $items)
{
}
}
```
<br>
### MinutesToSecondsInCacheRector
2019-02-18 15:51:24 +00:00
Change minutes argument to seconds in Illuminate\Contracts\Cache\Store and Illuminate\Support\Facades\Cache
2019-02-18 15:51:24 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\StaticCall\MinutesToSecondsInCacheRector`](../rules/Laravel/Rector/StaticCall/MinutesToSecondsInCacheRector.php)
2019-02-18 15:51:24 +00:00
```diff
class SomeClass
2019-02-18 15:51:24 +00:00
{
public function run()
2019-02-18 15:51:24 +00:00
{
- Illuminate\Support\Facades\Cache::put('key', 'value', 60);
+ Illuminate\Support\Facades\Cache::put('key', 'value', 60 * 60);
2019-02-18 15:51:24 +00:00
}
}
```
<br>
2019-02-18 15:51:24 +00:00
### PropertyDeferToDeferrableProviderToRector
2019-03-31 12:25:39 +00:00
Change deprecated `$defer` = true; to Illuminate\Contracts\Support\DeferrableProvider interface
2019-03-31 12:25:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\Class_\PropertyDeferToDeferrableProviderToRector`](../rules/Laravel/Rector/Class_/PropertyDeferToDeferrableProviderToRector.php)
2019-03-31 12:25:39 +00:00
```diff
use Illuminate\Support\ServiceProvider;
+use Illuminate\Contracts\Support\DeferrableProvider;
2019-03-31 12:25:39 +00:00
-final class SomeServiceProvider extends ServiceProvider
+final class SomeServiceProvider extends ServiceProvider implements DeferrableProvider
2019-03-31 12:25:39 +00:00
{
- /**
- * @var bool
- */
- protected $defer = true;
2019-03-31 12:25:39 +00:00
}
```
<br>
### Redirect301ToPermanentRedirectRector
Change "redirect" call with 301 to "permanentRedirect"
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\StaticCall\Redirect301ToPermanentRedirectRector`](../rules/Laravel/Rector/StaticCall/Redirect301ToPermanentRedirectRector.php)
```diff
class SomeClass
{
public function run()
{
- Illuminate\Routing\Route::redirect('/foo', '/bar', 301);
+ Illuminate\Routing\Route::permanentRedirect('/foo', '/bar');
}
}
```
<br>
### RequestStaticValidateToInjectRector
Change static `validate()` method to `$request->validate()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Laravel\Rector\StaticCall\RequestStaticValidateToInjectRector`](../rules/Laravel/Rector/StaticCall/RequestStaticValidateToInjectRector.php)
```diff
use Illuminate\Http\Request;
class SomeClass
{
- public function store()
+ public function store(\Illuminate\Http\Request $request)
{
- $validatedData = Request::validate(['some_attribute' => 'required']);
+ $validatedData = $request->validate(['some_attribute' => 'required']);
}
}
```
<br>
## MockeryToProphecy
### MockeryCloseRemoveRector
Removes mockery close from test classes
2021-03-12 23:52:38 +00:00
- class: [`Rector\MockeryToProphecy\Rector\StaticCall\MockeryCloseRemoveRector`](../rules/MockeryToProphecy/Rector/StaticCall/MockeryCloseRemoveRector.php)
```diff
public function tearDown() : void
{
- \Mockery::close();
}
```
<br>
### MockeryCreateMockToProphizeRector
Changes mockery mock creation to Prophesize
2021-03-12 23:52:38 +00:00
- class: [`Rector\MockeryToProphecy\Rector\ClassMethod\MockeryCreateMockToProphizeRector`](../rules/MockeryToProphecy/Rector/ClassMethod/MockeryCreateMockToProphizeRector.php)
```diff
-$mock = \Mockery::mock('MyClass');
+$mock = $this->prophesize('MyClass');
+
$service = new Service();
-$service->injectDependency($mock);
+$service->injectDependency($mock->reveal());
```
<br>
## MysqlToMysqli
### MysqlAssignToMysqliRector
Converts more complex mysql functions to mysqli
2021-03-12 23:52:38 +00:00
- class: [`Rector\MysqlToMysqli\Rector\Assign\MysqlAssignToMysqliRector`](../rules/MysqlToMysqli/Rector/Assign/MysqlAssignToMysqliRector.php)
```diff
-$data = mysql_db_name($result, $row);
+mysqli_data_seek($result, $row);
+$fetch = mysql_fetch_row($result);
+$data = $fetch[0];
```
<br>
### MysqlFuncCallToMysqliRector
Converts more complex mysql functions to mysqli
2021-03-12 23:52:38 +00:00
- class: [`Rector\MysqlToMysqli\Rector\FuncCall\MysqlFuncCallToMysqliRector`](../rules/MysqlToMysqli/Rector/FuncCall/MysqlFuncCallToMysqliRector.php)
```diff
-mysql_drop_db($database);
+mysqli_query('DROP DATABASE ' . $database);
```
<br>
### MysqlPConnectToMysqliConnectRector
Replace `mysql_pconnect()` with `mysqli_connect()` with host p: prefix
2021-03-12 23:52:38 +00:00
- class: [`Rector\MysqlToMysqli\Rector\FuncCall\MysqlPConnectToMysqliConnectRector`](../rules/MysqlToMysqli/Rector/FuncCall/MysqlPConnectToMysqliConnectRector.php)
```diff
final class SomeClass
{
public function run($host, $username, $password)
{
- return mysql_pconnect($host, $username, $password);
+ return mysqli_connect('p:' . $host, $username, $password);
}
}
```
<br>
### MysqlQueryMysqlErrorWithLinkRector
Add mysql_query and mysql_error with connection
2021-03-12 23:52:38 +00:00
- class: [`Rector\MysqlToMysqli\Rector\FuncCall\MysqlQueryMysqlErrorWithLinkRector`](../rules/MysqlToMysqli/Rector/FuncCall/MysqlQueryMysqlErrorWithLinkRector.php)
```diff
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);
}
}
```
<br>
## Naming
### MakeBoolPropertyRespectIsHasWasMethodNamingRector
Renames property to respect is/has/was method naming
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\Property\MakeBoolPropertyRespectIsHasWasMethodNamingRector`](../rules/Naming/Rector/Property/MakeBoolPropertyRespectIsHasWasMethodNamingRector.php)
```diff
class SomeClass
{
-private $full = false;
+private $isFull = false;
public function isFull()
{
- return $this->full;
+ return $this->isFull;
}
+
}
```
<br>
### MakeGetterClassMethodNameStartWithGetRector
Change getter method names to start with get/provide
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\ClassMethod\MakeGetterClassMethodNameStartWithGetRector`](../rules/Naming/Rector/ClassMethod/MakeGetterClassMethodNameStartWithGetRector.php)
```diff
class SomeClass
{
/**
* @var string
*/
private $name;
- public function name(): string
+ public function getName(): string
{
return $this->name;
}
}
```
<br>
### MakeIsserClassMethodNameStartWithIsRector
Change is method names to start with is/has/was
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\ClassMethod\MakeIsserClassMethodNameStartWithIsRector`](../rules/Naming/Rector/ClassMethod/MakeIsserClassMethodNameStartWithIsRector.php)
```diff
class SomeClass
{
/**
* @var bool
*/
private $isActive = false;
- public function getIsActive()
+ public function isActive()
{
return $this->isActive;
}
}
```
<br>
### RenameForeachValueVariableToMatchExprVariableRector
Renames value variable name in foreach loop to match expression variable
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\Foreach_\RenameForeachValueVariableToMatchExprVariableRector`](../rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchExprVariableRector.php)
```diff
class SomeClass
{
public function run()
{
$array = [];
- foreach ($variables as $foo) {
- $array[] = $property;
+ foreach ($variables as $variable) {
+ $array[] = $variable;
}
}
}
```
<br>
### RenameForeachValueVariableToMatchMethodCallReturnTypeRector
Renames value variable name in foreach loop to match method type
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\Foreach_\RenameForeachValueVariableToMatchMethodCallReturnTypeRector`](../rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchMethodCallReturnTypeRector.php)
```diff
class SomeClass
{
public function run()
{
$array = [];
- foreach ($object->getMethods() as $property) {
- $array[] = $property;
+ foreach ($object->getMethods() as $method) {
+ $array[] = $method;
}
}
}
```
<br>
### RenameParamToMatchTypeRector
Rename variable to match new ClassType
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\ClassMethod\RenameParamToMatchTypeRector`](../rules/Naming/Rector/ClassMethod/RenameParamToMatchTypeRector.php)
```diff
final class SomeClass
{
- public function run(Apple $pie)
+ public function run(Apple $apple)
{
- $food = $pie;
+ $food = $apple;
}
}
```
<br>
### RenamePropertyToMatchTypeRector
Rename property and method param to match its type
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector`](../rules/Naming/Rector/Class_/RenamePropertyToMatchTypeRector.php)
```diff
class SomeClass
{
/**
* @var EntityManager
*/
- private $eventManager;
+ private $entityManager;
- public function __construct(EntityManager $eventManager)
+ public function __construct(EntityManager $entityManager)
{
- $this->eventManager = $eventManager;
+ $this->entityManager = $entityManager;
}
}
```
<br>
### RenameVariableToMatchMethodCallReturnTypeRector
Rename variable to match method return type
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\Assign\RenameVariableToMatchMethodCallReturnTypeRector`](../rules/Naming/Rector/Assign/RenameVariableToMatchMethodCallReturnTypeRector.php)
```diff
class SomeClass
{
2021-02-20 23:02:05 +00:00
public function run()
{
- $a = $this->getRunner();
+ $runner = $this->getRunner();
}
2021-02-20 23:02:05 +00:00
public function getRunner(): Runner
{
return new Runner();
}
}
```
<br>
### RenameVariableToMatchNewTypeRector
Rename variable to match new ClassType
2021-03-12 23:52:38 +00:00
- class: [`Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector`](../rules/Naming/Rector/ClassMethod/RenameVariableToMatchNewTypeRector.php)
```diff
final class SomeClass
{
public function run()
{
- $search = new DreamSearch();
- $search->advance();
+ $dreamSearch = new DreamSearch();
+ $dreamSearch->advance();
}
}
```
<br>
## Nette
### AddNextrasDatePickerToDateControlRector
Nextras/Form upgrade of addDatePicker method call to DateControl assign
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\AddNextrasDatePickerToDateControlRector`](../rules/Nette/Rector/MethodCall/AddNextrasDatePickerToDateControlRector.php)
```diff
use Nette\Application\UI\Form;
class SomeClass
{
public function run()
{
$form = new Form();
- $form->addDatePicker('key', 'Label');
+ $form['key'] = new \Nextras\FormComponents\Controls\DateControl('Label');
}
}
```
<br>
### BuilderExpandToHelperExpandRector
Change `containerBuilder->expand()` to static call with parameters
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\BuilderExpandToHelperExpandRector`](../rules/Nette/Rector/MethodCall/BuilderExpandToHelperExpandRector.php)
```diff
use Nette\DI\CompilerExtension;
final class SomeClass extends CompilerExtension
{
public function loadConfiguration()
{
- $value = $this->getContainerBuilder()->expand('%value');
+ $value = \Nette\DI\Helpers::expand('%value', $this->getContainerBuilder()->parameters);
}
}
```
<br>
### ContextGetByTypeToConstructorInjectionRector
Move dependency get via `$context->getByType()` to constructor injection
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\ContextGetByTypeToConstructorInjectionRector`](../rules/Nette/Rector/MethodCall/ContextGetByTypeToConstructorInjectionRector.php)
```diff
class SomeClass
{
/**
* @var \Nette\DI\Container
*/
private $context;
2021-02-13 14:57:30 +00:00
+ public function __construct(private SomeTypeToInject $someTypeToInject)
+ {
+ }
+
public function run()
{
- $someTypeToInject = $this->context->getByType(SomeTypeToInject::class);
+ $someTypeToInject = $this->someTypeToInject;
}
}
```
<br>
### ConvertAddUploadWithThirdArgumentTrueToAddMultiUploadRector
convert `addUpload()` with 3rd argument true to `addMultiUpload()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\ConvertAddUploadWithThirdArgumentTrueToAddMultiUploadRector`](../rules/Nette/Rector/MethodCall/ConvertAddUploadWithThirdArgumentTrueToAddMultiUploadRector.php)
```diff
$form = new Nette\Forms\Form();
-$form->addUpload('...', '...', true);
+$form->addMultiUpload('...', '...');
```
<br>
### EndsWithFunctionToNetteUtilsStringsRector
Use `Nette\Utils\Strings::endsWith()` over bare string-functions
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\Identical\EndsWithFunctionToNetteUtilsStringsRector`](../rules/Nette/Rector/Identical/EndsWithFunctionToNetteUtilsStringsRector.php)
2019-08-05 21:10:47 +00:00
```diff
2021-03-03 21:28:27 +00:00
+use Nette\Utils\Strings;
+
class SomeClass
{
public function end($needle)
{
$content = 'Hi, my name is Tom';
2021-03-03 21:28:27 +00:00
-
- $yes = substr($content, -strlen($needle)) === $needle;
2021-03-03 21:28:27 +00:00
+ $yes = Strings::endsWith($content, $needle);
}
}
```
2019-08-05 21:10:47 +00:00
<br>
### FilePutContentsToFileSystemWriteRector
Change `file_put_contents()` to `FileSystem::write()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\FuncCall\FilePutContentsToFileSystemWriteRector`](../rules/Nette/Rector/FuncCall/FilePutContentsToFileSystemWriteRector.php)
```diff
class SomeClass
2019-08-05 21:10:47 +00:00
{
public function run()
{
- file_put_contents('file.txt', 'content');
+ \Nette\Utils\FileSystem::write('file.txt', 'content');
file_put_contents('file.txt', 'content_to_append', FILE_APPEND);
}
2019-08-05 21:10:47 +00:00
}
```
<br>
2019-10-15 14:46:31 +00:00
### JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector
Changes `json_encode()/json_decode()` to safer and more verbose `Nette\Utils\Json::encode()/decode()` calls
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\FuncCall\JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector`](../rules/Nette/Rector/FuncCall/JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector.php)
2020-04-01 00:05:51 +00:00
```diff
class SomeClass
2020-04-01 00:05:51 +00:00
{
public function decodeJson(string $jsonString)
2020-04-01 00:05:51 +00:00
{
- $stdClass = json_decode($jsonString);
+ $stdClass = \Nette\Utils\Json::decode($jsonString);
- $array = json_decode($jsonString, true);
- $array = json_decode($jsonString, false);
+ $array = \Nette\Utils\Json::decode($jsonString, \Nette\Utils\Json::FORCE_ARRAY);
+ $array = \Nette\Utils\Json::decode($jsonString);
}
public function encodeJson(array $data)
{
- $jsonString = json_encode($data);
+ $jsonString = \Nette\Utils\Json::encode($data);
- $prettyJsonString = json_encode($data, JSON_PRETTY_PRINT);
+ $prettyJsonString = \Nette\Utils\Json::encode($data, \Nette\Utils\Json::PRETTY);
2020-04-01 00:05:51 +00:00
}
}
```
<br>
2020-04-01 00:05:51 +00:00
### MagicHtmlCallToAppendAttributeRector
Change magic `addClass()` etc. calls on Html to explicit methods
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\MagicHtmlCallToAppendAttributeRector`](../rules/Nette/Rector/MethodCall/MagicHtmlCallToAppendAttributeRector.php)
```diff
use Nette\Utils\Html;
final class SomeClass
{
public function run()
{
$html = Html::el();
- $html->setClass('first');
+ $html->appendAttribute('class', 'first');
}
}
```
<br>
### MergeDefaultsInGetConfigCompilerExtensionRector
Change `$this->getConfig($defaults)` to `array_merge`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\MergeDefaultsInGetConfigCompilerExtensionRector`](../rules/Nette/Rector/MethodCall/MergeDefaultsInGetConfigCompilerExtensionRector.php)
```diff
use Nette\DI\CompilerExtension;
final class SomeExtension extends CompilerExtension
{
private $defaults = [
'key' => 'value'
];
public function loadConfiguration()
{
- $config = $this->getConfig($this->defaults);
+ $config = array_merge($this->defaults, $this->getConfig());
}
}
```
<br>
### MoveFinalGetUserToCheckRequirementsClassMethodRector
2020-08-03 22:21:59 +00:00
Presenter method `getUser()` is now final, move logic to `checkRequirements()`
2020-08-03 22:21:59 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\Class_\MoveFinalGetUserToCheckRequirementsClassMethodRector`](../rules/Nette/Rector/Class_/MoveFinalGetUserToCheckRequirementsClassMethodRector.php)
2020-08-03 22:21:59 +00:00
```diff
use Nette\Application\UI\Presenter;
class SomeControl extends Presenter
{
- public function getUser()
+ public function checkRequirements()
{
- $user = parent::getUser();
+ $user = $this->getUser();
$user->getStorage()->setNamespace('admin_session');
- return $user;
+
+ parent::checkRequirements();
}
}
2020-08-03 22:21:59 +00:00
```
<br>
2020-08-03 22:21:59 +00:00
### PregFunctionToNetteUtilsStringsRector
Use `Nette\Utils\Strings` over bare `preg_split()` and `preg_replace()` functions
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\FuncCall\PregFunctionToNetteUtilsStringsRector`](../rules/Nette/Rector/FuncCall/PregFunctionToNetteUtilsStringsRector.php)
```diff
+use Nette\Utils\Strings;
+
class SomeClass
{
public function run()
{
$content = 'Hi my name is Tom';
- $splitted = preg_split('#Hi#', $content);
+ $splitted = \Nette\Utils\Strings::split($content, '#Hi#');
}
}
```
<br>
### PregMatchFunctionToNetteUtilsStringsRector
2018-10-21 22:26:45 +00:00
Use `Nette\Utils\Strings` over bare `preg_match()` and `preg_match_all()` functions
2018-10-21 22:26:45 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\FuncCall\PregMatchFunctionToNetteUtilsStringsRector`](../rules/Nette/Rector/FuncCall/PregMatchFunctionToNetteUtilsStringsRector.php)
```diff
+use Nette\Utils\Strings;
+
class SomeClass
{
public function run()
{
$content = 'Hi my name is Tom';
- preg_match('#Hi#', $content, $matches);
+ $matches = Strings::match($content, '#Hi#');
}
}
2018-12-14 19:35:35 +00:00
```
<br>
2018-12-14 19:35:35 +00:00
### RemoveParentAndNameFromComponentConstructorRector
Remove `$parent` and `$name` in control constructor
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\ClassMethod\RemoveParentAndNameFromComponentConstructorRector`](../rules/Nette/Rector/ClassMethod/RemoveParentAndNameFromComponentConstructorRector.php)
```diff
use Nette\Application\UI\Control;
class SomeControl extends Control
{
- public function __construct(IContainer $parent = null, $name = null, int $value)
+ public function __construct(int $value)
{
- parent::__construct($parent, $name);
$this->value = $value;
}
}
```
<br>
2021-03-12 23:52:38 +00:00
### ReplaceTimeNumberWithDateTimeConstantRector
Replace `time` numbers with `Nette\Utils\DateTime` constants
- class: [`Rector\Nette\Rector\LNumber\ReplaceTimeNumberWithDateTimeConstantRector`](../rules/Nette/Rector/LNumber/ReplaceTimeNumberWithDateTimeConstantRector.php)
```diff
final class SomeClass
{
public function run()
{
- return 86400;
+ return \Nette\Utils\DateTime::DAY;
}
}
```
<br>
### RequestGetCookieDefaultArgumentToCoalesceRector
2020-10-09 20:01:37 +00:00
Add removed `Nette\Http\Request::getCookies()` default value as coalesce
2020-10-09 20:01:37 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\RequestGetCookieDefaultArgumentToCoalesceRector`](../rules/Nette/Rector/MethodCall/RequestGetCookieDefaultArgumentToCoalesceRector.php)
2020-10-09 20:01:37 +00:00
```diff
use Nette\Http\Request;
class SomeClass
{
public function run(Request $request)
{
- return $request->getCookie('name', 'default');
+ return $request->getCookie('name') ?? 'default';
}
}
2020-10-09 20:01:37 +00:00
```
<br>
2020-10-09 20:01:37 +00:00
### SetClassWithArgumentToSetFactoryRector
2018-12-14 19:35:35 +00:00
Change setClass with class and arguments to separated methods
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\MethodCall\SetClassWithArgumentToSetFactoryRector`](../rules/Nette/Rector/MethodCall/SetClassWithArgumentToSetFactoryRector.php)
2019-05-29 13:40:20 +00:00
```diff
use Nette\DI\ContainerBuilder;
class SomeClass
{
public function run(ContainerBuilder $containerBuilder)
{
$containerBuilder->addDefinition('...')
- ->setClass('SomeClass', [1, 2]);
+ ->setFactory('SomeClass', [1, 2]);
}
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
### StartsWithFunctionToNetteUtilsStringsRector
2019-05-29 13:40:20 +00:00
Use `Nette\Utils\Strings::startsWith()` over bare string-functions
2018-12-14 19:35:35 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\Identical\StartsWithFunctionToNetteUtilsStringsRector`](../rules/Nette/Rector/Identical/StartsWithFunctionToNetteUtilsStringsRector.php)
2018-12-14 19:35:35 +00:00
```diff
2021-03-03 21:28:27 +00:00
+use Nette\Utils\Strings;
+
class SomeClass
2018-12-14 19:35:35 +00:00
{
2021-03-03 21:28:27 +00:00
public function start($needle)
{
$content = 'Hi, my name is Tom';
- $yes = substr($content, 0, strlen($needle)) === $needle;
+ $yes = Strings::startsWith($content, $needle);
}
2019-03-16 20:31:46 +00:00
}
```
<br>
2019-03-16 20:31:46 +00:00
### StrposToStringsContainsRector
2019-05-29 13:40:20 +00:00
Use `Nette\Utils\Strings` over bare string-functions
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\NotIdentical\StrposToStringsContainsRector`](../rules/Nette/Rector/NotIdentical/StrposToStringsContainsRector.php)
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
$name = 'Hi, my name is Tom';
- return strpos($name, 'Hi') !== false;
+ return \Nette\Utils\Strings::contains($name, 'Hi');
}
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
### SubstrStrlenFunctionToNetteUtilsStringsRector
2019-03-16 20:31:46 +00:00
Use `Nette\Utils\Strings` over bare string-functions
2019-03-16 20:31:46 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\FuncCall\SubstrStrlenFunctionToNetteUtilsStringsRector`](../rules/Nette/Rector/FuncCall/SubstrStrlenFunctionToNetteUtilsStringsRector.php)
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
public function run()
{
- return substr($value, 0, 3);
+ return \Nette\Utils\Strings::substring($value, 0, 3);
}
}
2018-07-31 12:50:39 +00:00
```
<br>
### TemplateMagicAssignToExplicitVariableArrayRector
2018-07-31 12:50:39 +00:00
Change `$this->templates->{magic}` to `$this->template->render(..., $values)` in components
2018-07-31 12:50:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\ClassMethod\TemplateMagicAssignToExplicitVariableArrayRector`](../rules/Nette/Rector/ClassMethod/TemplateMagicAssignToExplicitVariableArrayRector.php)
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
use Nette\Application\UI\Control;
2018-10-12 23:15:00 +00:00
class SomeControl extends Control
{
public function render()
{
- $this->template->param = 'some value';
- $this->template->render(__DIR__ . '/poll.latte');
+ $this->template->render(__DIR__ . '/poll.latte', ['param' => 'some value']);
}
}
2018-10-12 23:15:00 +00:00
```
<br>
2018-07-31 12:50:39 +00:00
### TranslateClassMethodToVariadicsRector
2020-07-29 08:33:10 +00:00
Change `translate()` method call 2nd arg to variadic
2020-07-29 08:33:10 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Nette\Rector\ClassMethod\TranslateClassMethodToVariadicsRector`](../rules/Nette/Rector/ClassMethod/TranslateClassMethodToVariadicsRector.php)
2020-07-29 08:33:10 +00:00
```diff
use Nette\Localization\ITranslator;
2020-07-29 08:33:10 +00:00
final class SomeClass implements ITranslator
2020-07-29 08:33:10 +00:00
{
- public function translate($message, $count = null)
+ public function translate($message, ... $parameters)
{
+ $count = $parameters[0] ?? null;
return [$message, $count];
}
2020-07-29 08:33:10 +00:00
}
```
<br>
2020-07-29 08:33:10 +00:00
## NetteCodeQuality
### AnnotateMagicalControlArrayAccessRector
Change magic `$this["some_component"]` to variable assign with `@var` annotation
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\ArrayDimFetch\AnnotateMagicalControlArrayAccessRector`](../rules/NetteCodeQuality/Rector/ArrayDimFetch/AnnotateMagicalControlArrayAccessRector.php)
```diff
use Nette\Application\UI\Presenter;
use Nette\Application\UI\Form;
final class SomePresenter extends Presenter
{
public function run()
{
- if ($this['some_form']->isSubmitted()) {
+ /** @var \Nette\Application\UI\Form $someForm */
+ $someForm = $this['some_form'];
+ if ($someForm->isSubmitted()) {
}
}
protected function createComponentSomeForm()
{
return new Form();
}
}
```
<br>
### ArrayAccessGetControlToGetComponentMethodCallRector
Change magic arrays access get, to explicit `$this->getComponent(...)` method
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\Assign\ArrayAccessGetControlToGetComponentMethodCallRector`](../rules/NetteCodeQuality/Rector/Assign/ArrayAccessGetControlToGetComponentMethodCallRector.php)
```diff
use Nette\Application\UI\Presenter;
class SomeClass extends Presenter
{
public function some()
{
- $someControl = $this['whatever'];
+ $someControl = $this->getComponent('whatever');
}
}
```
<br>
### ArrayAccessSetControlToAddComponentMethodCallRector
Change magic arrays access set, to explicit `$this->setComponent(...)` method
2018-10-12 23:15:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\Assign\ArrayAccessSetControlToAddComponentMethodCallRector`](../rules/NetteCodeQuality/Rector/Assign/ArrayAccessSetControlToAddComponentMethodCallRector.php)
2018-10-12 23:15:00 +00:00
```diff
use Nette\Application\UI\Control;
use Nette\Application\UI\Presenter;
class SomeClass extends Presenter
{
public function some()
{
$someControl = new Control();
- $this['whatever'] = $someControl;
+ $this->addComponent($someControl, 'whatever');
}
}
```
2018-10-12 23:15:00 +00:00
<br>
2018-10-21 22:26:45 +00:00
### ChangeFormArrayAccessToAnnotatedControlVariableRector
Change array access magic on `$form` to explicit standalone typed variable
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\ArrayDimFetch\ChangeFormArrayAccessToAnnotatedControlVariableRector`](../rules/NetteCodeQuality/Rector/ArrayDimFetch/ChangeFormArrayAccessToAnnotatedControlVariableRector.php)
2018-10-12 23:15:00 +00:00
```diff
use Nette\Application\UI\Form;
2018-10-12 23:15:00 +00:00
class SomePresenter
{
public function run()
{
$form = new Form();
$this->addText('email', 'Email');
- $form['email']->value = 'hey@hi.hello';
+ /** @var \Nette\Forms\Controls\TextInput $emailControl */
+ $emailControl = $form['email'];
+ $emailControl->value = 'hey@hi.hello';
}
}
```
2018-10-12 23:15:00 +00:00
<br>
2018-10-12 23:15:00 +00:00
### MakeGetComponentAssignAnnotatedRector
2018-10-12 23:15:00 +00:00
Add doc type for magic `$control->getComponent(...)` assign
2018-10-12 23:15:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\Assign\MakeGetComponentAssignAnnotatedRector`](../rules/NetteCodeQuality/Rector/Assign/MakeGetComponentAssignAnnotatedRector.php)
```diff
use Nette\Application\UI\Control;
final class SomeClass
{
public function run()
{
$externalControl = new ExternalControl();
+ /** @var AnotherControl $anotherControl */
$anotherControl = $externalControl->getComponent('another');
}
}
2018-10-12 23:15:00 +00:00
final class ExternalControl extends Control
{
public function createComponentAnother(): AnotherControl
{
return new AnotherControl();
}
}
2018-10-12 23:15:00 +00:00
final class AnotherControl extends Control
{
}
2018-10-12 23:15:00 +00:00
```
<br>
2018-10-12 23:15:00 +00:00
2021-02-13 14:57:30 +00:00
### MergeTemplateSetFileToTemplateRenderRector
Change `$this->template->setFile()` `$this->template->render()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\ClassMethod\MergeTemplateSetFileToTemplateRenderRector`](../rules/NetteCodeQuality/Rector/ClassMethod/MergeTemplateSetFileToTemplateRenderRector.php)
2021-02-13 14:57:30 +00:00
```diff
use Nette\Application\UI\Control;
final class SomeControl extends Control
{
public function render()
{
- $this->template->setFile(__DIR__ . '/someFile.latte');
- $this->template->render();
+ $this->template->render(__DIR__ . '/someFile.latte');
}
}
```
<br>
### MoveInjectToExistingConstructorRector
Move `@inject` properties to constructor, if there already is one
2018-10-12 23:15:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\Class_\MoveInjectToExistingConstructorRector`](../rules/NetteCodeQuality/Rector/Class_/MoveInjectToExistingConstructorRector.php)
2018-10-12 23:15:00 +00:00
```diff
final class SomeClass
{
/**
* @var SomeDependency
- * @inject
*/
- public $someDependency;
+ private $someDependency;
/**
* @var OtherDependency
*/
private $otherDependency;
- public function __construct(OtherDependency $otherDependency)
+ public function __construct(OtherDependency $otherDependency, SomeDependency $someDependency)
{
$this->otherDependency = $otherDependency;
+ $this->someDependency = $someDependency;
}
}
```
<br>
### SubstrMinusToStringEndsWithRector
Change `substr` function with minus to `Strings::endsWith()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteCodeQuality\Rector\Identical\SubstrMinusToStringEndsWithRector`](../rules/NetteCodeQuality/Rector/Identical/SubstrMinusToStringEndsWithRector.php)
```diff
-substr($var, -4) !== 'Test';
-substr($var, -4) === 'Test';
+! \Nette\Utils\Strings::endsWith($var, 'Test');
+\Nette\Utils\Strings::endsWith($var, 'Test');
```
<br>
## NetteKdyby
### ChangeNetteEventNamesInGetSubscribedEventsRector
Change EventSubscriber from Kdyby to Contributte
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteKdyby\Rector\ClassMethod\ChangeNetteEventNamesInGetSubscribedEventsRector`](../rules/NetteKdyby/Rector/ClassMethod/ChangeNetteEventNamesInGetSubscribedEventsRector.php)
```diff
+use Contributte\Events\Extra\Event\Application\ShutdownEvent;
use Kdyby\Events\Subscriber;
use Nette\Application\Application;
-use Nette\Application\UI\Presenter;
class GetApplesSubscriber implements Subscriber
{
- public function getSubscribedEvents()
+ public static function getSubscribedEvents()
{
return [
- Application::class . '::onShutdown',
+ ShutdownEvent::class => 'onShutdown',
];
}
- public function onShutdown(Presenter $presenter)
+ public function onShutdown(ShutdownEvent $shutdownEvent)
{
+ $presenter = $shutdownEvent->getPresenter();
$presenterName = $presenter->getName();
// ...
}
}
```
<br>
### ReplaceEventManagerWithEventSubscriberRector
Change Kdyby EventManager to EventDispatcher
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteKdyby\Rector\MethodCall\ReplaceEventManagerWithEventSubscriberRector`](../rules/NetteKdyby/Rector/MethodCall/ReplaceEventManagerWithEventSubscriberRector.php)
```diff
use Kdyby\Events\EventManager;
final class SomeClass
{
/**
* @var EventManager
*/
private $eventManager;
public function __construct(EventManager $eventManager)
{
$this->eventManager = eventManager;
}
public function run()
{
$key = '2000';
- $this->eventManager->dispatchEvent(static::class . '::onCopy', new EventArgsList([$this, $key]));
+ $this->eventManager->dispatch(new SomeClassCopyEvent($this, $key));
}
}
2018-10-12 23:15:00 +00:00
```
<br>
2020-03-23 16:13:04 +00:00
### ReplaceMagicPropertyEventWithEventClassRector
2018-10-12 23:15:00 +00:00
Change `$onProperty` magic call with event disptacher and class dispatch
2018-10-12 23:15:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteKdyby\Rector\MethodCall\ReplaceMagicPropertyEventWithEventClassRector`](../rules/NetteKdyby/Rector/MethodCall/ReplaceMagicPropertyEventWithEventClassRector.php)
2019-05-29 13:40:20 +00:00
```diff
final class FileManager
{
- public $onUpload;
+ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
+ public function __construct(EventDispatcherInterface $eventDispatcher)
+ {
+ $this->eventDispatcher = $eventDispatcher;
+ }
+
public function run(User $user)
{
- $this->onUpload($user);
+ $onFileManagerUploadEvent = new FileManagerUploadEvent($user);
+ $this->eventDispatcher->dispatch($onFileManagerUploadEvent);
}
2019-10-15 14:46:31 +00:00
}
```
<br>
2019-10-15 14:46:31 +00:00
### ReplaceMagicPropertyWithEventClassRector
Change `getSubscribedEvents()` from on magic property, to Event class
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteKdyby\Rector\ClassMethod\ReplaceMagicPropertyWithEventClassRector`](../rules/NetteKdyby/Rector/ClassMethod/ReplaceMagicPropertyWithEventClassRector.php)
```diff
use Kdyby\Events\Subscriber;
final class ActionLogEventSubscriber implements Subscriber
{
public function getSubscribedEvents(): array
{
return [
- AlbumService::class . '::onApprove' => 'onAlbumApprove',
+ AlbumServiceApproveEvent::class => 'onAlbumApprove',
];
}
- public function onAlbumApprove(Album $album, int $adminId): void
+ public function onAlbumApprove(AlbumServiceApproveEventAlbum $albumServiceApproveEventAlbum): void
{
+ $album = $albumServiceApproveEventAlbum->getAlbum();
$album->play();
}
}
```
<br>
## NetteTesterToPHPUnit
2018-10-12 23:15:00 +00:00
### NetteAssertToPHPUnitAssertRector
2018-10-12 23:15:00 +00:00
Migrate Nette/Assert calls to PHPUnit
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteTesterToPHPUnit\Rector\StaticCall\NetteAssertToPHPUnitAssertRector`](../rules/NetteTesterToPHPUnit/Rector/StaticCall/NetteAssertToPHPUnitAssertRector.php)
2019-05-29 13:40:20 +00:00
```diff
use Tester\Assert;
function someStaticFunctions()
{
- Assert::true(10 == 5);
+ \PHPUnit\Framework\Assert::assertTrue(10 == 5);
}
```
<br>
### NetteTesterClassToPHPUnitClassRector
Migrate Nette Tester test case to PHPUnit
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteTesterToPHPUnit\Rector\Class_\NetteTesterClassToPHPUnitClassRector`](../rules/NetteTesterToPHPUnit/Rector/Class_/NetteTesterClassToPHPUnitClassRector.php)
```diff
namespace KdybyTests\Doctrine;
use Tester\TestCase;
use Tester\Assert;
-require_once __DIR__ . '/../bootstrap.php';
-
-class ExtensionTest extends TestCase
+class ExtensionTest extends \PHPUnit\Framework\TestCase
{
public function testFunctionality()
{
- Assert::true($default instanceof Kdyby\Doctrine\EntityManager);
- Assert::true(5);
- Assert::same($container->getService('kdyby.doctrine.default.entityManager'), $default);
+ $this->assertInstanceOf(\Kdyby\Doctrine\EntityManager::cllass, $default);
+ $this->assertTrue(5);
+ $this->same($container->getService('kdyby.doctrine.default.entityManager'), $default);
}
-}
-
-(new \ExtensionTest())->run();
+}
```
<br>
### RenameTesterTestToPHPUnitToTestFileRector
2018-10-12 23:15:00 +00:00
Rename "*.phpt" file to "*Test.php" file
2018-10-12 23:15:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteTesterToPHPUnit\Rector\FileNode\RenameTesterTestToPHPUnitToTestFileRector`](../rules/NetteTesterToPHPUnit/Rector/FileNode/RenameTesterTestToPHPUnitToTestFileRector.php)
2018-10-12 23:15:00 +00:00
```diff
-// tests/SomeTestCase.phpt
+// tests/SomeTestCase.php
2018-10-12 23:15:00 +00:00
```
<br>
2018-10-23 18:58:57 +00:00
## NetteToSymfony
2019-10-15 14:46:31 +00:00
### DeleteFactoryInterfaceRector
2019-10-15 14:46:31 +00:00
Interface factories are not needed in Symfony. Clear constructor injection is used instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\Interface_\DeleteFactoryInterfaceRector`](../rules/NetteToSymfony/Rector/Interface_/DeleteFactoryInterfaceRector.php)
2019-10-15 14:46:31 +00:00
```diff
-interface SomeControlFactoryInterface
-{
- public function create();
-}
2019-10-15 14:46:31 +00:00
```
<br>
### FormControlToControllerAndFormTypeRector
Change Form that extends Control to Controller and decoupled FormType
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\Class_\FormControlToControllerAndFormTypeRector`](../rules/NetteToSymfony/Rector/Class_/FormControlToControllerAndFormTypeRector.php)
```diff
-use Nette\Application\UI\Form;
-use Nette\Application\UI\Control;
-
-class SomeForm extends Control
+class SomeFormController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
- public function createComponentForm()
+ /**
+ * @Route(...)
+ */
+ public function actionSomeForm(\Symfony\Component\HttpFoundation\Request $request): \Symfony\Component\HttpFoundation\Response
{
- $form = new Form();
- $form->addText('name', 'Your name');
+ $form = $this->createForm(SomeFormType::class);
+ $form->handleRequest($request);
- $form->onSuccess[] = [$this, 'processForm'];
- }
-
- public function processForm(Form $form)
- {
- // process me
+ if ($form->isSuccess() && $form->isValid()) {
+ // process me
+ }
}
}
```
Extra file:
2019-05-29 13:40:20 +00:00
```php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
2019-05-29 13:40:20 +00:00
class SomeFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $formBuilder, array $options)
{
$formBuilder->add('name', TextType::class, [
'label' => 'Your name',
]);
}
}
```
2019-05-29 13:40:20 +00:00
<br>
2019-05-29 13:40:20 +00:00
### FromHttpRequestGetHeaderToHeadersGetRector
2019-03-31 12:25:39 +00:00
Changes `getHeader()` to `$request->headers->get()`
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\MethodCall\FromHttpRequestGetHeaderToHeadersGetRector`](../rules/NetteToSymfony/Rector/MethodCall/FromHttpRequestGetHeaderToHeadersGetRector.php)
2019-05-29 13:40:20 +00:00
```diff
use Nette\Request;
final class SomeController
{
public static function someAction(Request $request)
{
- $header = $this->httpRequest->getHeader('x');
+ $header = $request->headers->get('x');
}
}
```
2019-05-29 13:40:20 +00:00
<br>
### FromRequestGetParameterToAttributesGetRector
Changes `"getParameter()"` to `"attributes->get()"` from Nette to Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\MethodCall\FromRequestGetParameterToAttributesGetRector`](../rules/NetteToSymfony/Rector/MethodCall/FromRequestGetParameterToAttributesGetRector.php)
2019-05-29 13:40:20 +00:00
```diff
use Nette\Request;
final class SomeController
{
public static function someAction(Request $request)
{
- $value = $request->getParameter('abz');
+ $value = $request->attribute->get('abz');
}
}
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
### NetteControlToSymfonyControllerRector
Migrate Nette Component to Symfony Controller
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\Class_\NetteControlToSymfonyControllerRector`](../rules/NetteToSymfony/Rector/Class_/NetteControlToSymfonyControllerRector.php)
```diff
-use Nette\Application\UI\Control;
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+use Symfony\Component\HttpFoundation\Response;
-class SomeControl extends Control
+class SomeController extends AbstractController
{
- public function render()
- {
- $this->template->param = 'some value';
- $this->template->render(__DIR__ . '/poll.latte');
- }
+ public function some(): Response
+ {
+ return $this->render(__DIR__ . '/poll.latte', ['param' => 'some value']);
+ }
}
```
<br>
### NetteFormToSymfonyFormRector
Migrate Nette\Forms in Presenter to Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\MethodCall\NetteFormToSymfonyFormRector`](../rules/NetteToSymfony/Rector/MethodCall/NetteFormToSymfonyFormRector.php)
```diff
use Nette\Application\UI;
class SomePresenter extends UI\Presenter
{
public function someAction()
{
- $form = new UI\Form;
- $form->addText('name', 'Name:');
- $form->addPassword('password', 'Password:');
- $form->addSubmit('login', 'Sign up');
+ $form = $this->createFormBuilder();
+ $form->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class, [
+ 'label' => 'Name:'
+ ]);
+ $form->add('password', \Symfony\Component\Form\Extension\Core\Type\PasswordType::class, [
+ 'label' => 'Password:'
+ ]);
+ $form->add('login', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, [
+ 'label' => 'Sign up'
+ ]);
}
}
2018-10-12 23:15:00 +00:00
```
<br>
### RenameEventNamesInEventSubscriberRector
2019-01-22 20:34:38 +00:00
Changes event names from Nette ones to Symfony ones
2019-01-22 20:34:38 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\ClassMethod\RenameEventNamesInEventSubscriberRector`](../rules/NetteToSymfony/Rector/ClassMethod/RenameEventNamesInEventSubscriberRector.php)
2019-01-22 20:34:38 +00:00
```diff
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class SomeClass implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- return ['nette.application' => 'someMethod'];
+ return [\SymfonyEvents::KERNEL => 'someMethod'];
}
}
2019-01-22 20:34:38 +00:00
```
<br>
2019-01-22 20:34:38 +00:00
### RouterListToControllerAnnotationsRector
Change new `Route()` from RouteFactory to `@Route` annotation above controller method
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\ClassMethod\RouterListToControllerAnnotationsRector`](../rules/NetteToSymfony/Rector/ClassMethod/RouterListToControllerAnnotationsRector.php)
```diff
final class RouterFactory
{
public function create(): RouteList
{
$routeList = new RouteList();
+
+ // case of single action controller, usually get() or __invoke() method
$routeList[] = new Route('some-path', SomePresenter::class);
return $routeList;
}
}
+use Symfony\Component\Routing\Annotation\Route;
+
final class SomePresenter
{
+ /**
+ * @Route(path="some-path")
+ */
public function run()
{
}
}
```
<br>
### WrapTransParameterNameRector
2018-12-14 19:35:35 +00:00
Adds %% to placeholder name of `trans()` method if missing
2018-12-14 19:35:35 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\NetteToSymfony\Rector\MethodCall\WrapTransParameterNameRector`](../rules/NetteToSymfony/Rector/MethodCall/WrapTransParameterNameRector.php)
2018-12-14 19:35:35 +00:00
```diff
use Symfony\Component\Translation\Translator;
final class SomeController
{
public function run()
{
$translator = new Translator('');
$translated = $translator->trans(
'Hello %name%',
- ['name' => $name]
+ ['%name%' => $name]
);
}
}
2018-12-14 19:35:35 +00:00
```
<br>
2018-10-12 23:15:00 +00:00
## Order
### OrderClassConstantsByIntegerValueRector
Order class constant order by their integer value
2018-10-12 23:15:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Order\Rector\Class_\OrderClassConstantsByIntegerValueRector`](../rules/Order/Rector/Class_/OrderClassConstantsByIntegerValueRector.php)
2018-10-12 23:15:00 +00:00
```diff
class SomeClass
{
const MODE_ON = 0;
+ const MODE_MAYBE = 1;
+
const MODE_OFF = 2;
-
- const MODE_MAYBE = 1;
}
2018-10-12 23:15:00 +00:00
```
<br>
### OrderConstantsByVisibilityRector
Orders constants by visibility
2021-03-12 23:52:38 +00:00
- class: [`Rector\Order\Rector\Class_\OrderConstantsByVisibilityRector`](../rules/Order/Rector/Class_/OrderConstantsByVisibilityRector.php)
```diff
final class SomeClass
{
+ public const PUBLIC_CONST = 'public';
+ protected const PROTECTED_CONST = 'protected';
private const PRIVATE_CONST = 'private';
- protected const PROTECTED_CONST = 'protected';
- public const PUBLIC_CONST = 'public';
}
```
<br>
### OrderFirstLevelClassStatementsRector
Orders first level Class statements
2021-03-12 23:52:38 +00:00
- class: [`Rector\Order\Rector\Class_\OrderFirstLevelClassStatementsRector`](../rules/Order/Rector/Class_/OrderFirstLevelClassStatementsRector.php)
```diff
final class SomeClass
{
+ use TraitName;
+ private const CONST_NAME = 'constant_value';
+ protected $propertyName;
public function functionName();
- protected $propertyName;
- private const CONST_NAME = 'constant_value';
- use TraitName;
}
```
<br>
### OrderMethodsByVisibilityRector
Orders method by visibility
2021-03-12 23:52:38 +00:00
- class: [`Rector\Order\Rector\Class_\OrderMethodsByVisibilityRector`](../rules/Order/Rector/Class_/OrderMethodsByVisibilityRector.php)
```diff
class SomeClass
{
+ public function publicFunctionName();
protected function protectedFunctionName();
private function privateFunctionName();
- public function publicFunctionName();
}
```
<br>
2019-11-06 23:52:19 +00:00
### OrderPrivateMethodsByUseRector
2019-11-06 23:52:19 +00:00
Order private methods in order of their use
2019-11-06 23:52:19 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Order\Rector\Class_\OrderPrivateMethodsByUseRector`](../rules/Order/Rector/Class_/OrderPrivateMethodsByUseRector.php)
2019-11-06 23:52:19 +00:00
```diff
class SomeClass
{
public function run()
2019-11-06 23:52:19 +00:00
{
$this->call1();
$this->call2();
2019-11-06 23:52:19 +00:00
}
- private function call2()
+ private function call1()
2019-11-06 23:52:19 +00:00
{
}
2019-08-05 21:10:47 +00:00
- private function call1()
+ private function call2()
2019-08-05 21:10:47 +00:00
{
}
}
```
<br>
### OrderPropertiesByVisibilityRector
Orders properties by visibility
2021-03-12 23:52:38 +00:00
- class: [`Rector\Order\Rector\Class_\OrderPropertiesByVisibilityRector`](../rules/Order/Rector/Class_/OrderPropertiesByVisibilityRector.php)
```diff
final class SomeClass
{
+ public $publicProperty;
protected $protectedProperty;
private $privateProperty;
- public $publicProperty;
}
```
<br>
## PHPOffice
2019-08-24 11:08:59 +00:00
### AddRemovedDefaultValuesRector
2020-05-31 15:26:08 +00:00
Complete removed default values explicitly
2020-05-31 15:26:08 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\StaticCall\AddRemovedDefaultValuesRector`](../rules/PHPOffice/Rector/StaticCall/AddRemovedDefaultValuesRector.php)
2020-05-31 15:26:08 +00:00
```diff
final class SomeClass
{
public function run(): void
{
$logger = new \PHPExcel_CalcEngine_Logger;
- $logger->setWriteDebugLog();
+ $logger->setWriteDebugLog(false);
}
}
```
<br>
### CellStaticToCoordinateRector
Methods to manipulate coordinates that used to exists in PHPExcel_Cell to PhpOffice\PhpSpreadsheet\Cell\Coordinate
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\StaticCall\CellStaticToCoordinateRector`](../rules/PHPOffice/Rector/StaticCall/CellStaticToCoordinateRector.php)
```diff
class SomeClass
{
public function run()
{
- \PHPExcel_Cell::stringFromColumnIndex();
+ \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex();
}
2018-10-12 23:15:00 +00:00
}
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
### ChangeChartRendererRector
2018-12-31 11:50:32 +00:00
Change chart renderer
2018-12-31 11:50:32 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeChartRendererRector`](../rules/PHPOffice/Rector/StaticCall/ChangeChartRendererRector.php)
```diff
final class SomeClass
{
public function run(): void
{
- \PHPExcel_Settings::setChartRenderer($rendererName, $rendererLibraryPath);
+ \PHPExcel_Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class);
}
}
```
<br>
### ChangeConditionalGetConditionRector
Change argument `PHPExcel_Style_Conditional->getCondition()` to `getConditions()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeConditionalGetConditionRector`](../rules/PHPOffice/Rector/MethodCall/ChangeConditionalGetConditionRector.php)
```diff
final class SomeClass
{
public function run(): void
{
$conditional = new \PHPExcel_Style_Conditional;
- $someCondition = $conditional->getCondition();
+ $someCondition = $conditional->getConditions()[0] ?? '';
}
}
```
<br>
2019-02-21 14:36:16 +00:00
### ChangeConditionalReturnedCellRector
2019-02-21 14:36:16 +00:00
Change conditional call to `getCell()`
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeConditionalReturnedCellRector`](../rules/PHPOffice/Rector/MethodCall/ChangeConditionalReturnedCellRector.php)
2019-02-21 14:36:16 +00:00
```diff
final class SomeClass
{
public function run(): void
{
$worksheet = new \PHPExcel_Worksheet();
- $cell = $worksheet->setCellValue('A1', 'value', true);
+ $cell = $worksheet->getCell('A1')->setValue('value');
}
}
```
2019-05-01 23:56:58 +00:00
<br>
2019-05-01 23:56:58 +00:00
### ChangeConditionalSetConditionRector
Change argument `PHPExcel_Style_Conditional->setCondition()` to `setConditions()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeConditionalSetConditionRector`](../rules/PHPOffice/Rector/MethodCall/ChangeConditionalSetConditionRector.php)
```diff
final class SomeClass
{
public function run(): void
{
$conditional = new \PHPExcel_Style_Conditional;
- $someCondition = $conditional->setCondition(1);
+ $someCondition = $conditional->setConditions((array) 1);
}
}
```
2019-09-25 08:49:53 +00:00
<br>
### ChangeDataTypeForValueRector
Change argument `DataType::dataTypeForValue()` to DefaultValueBinder
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeDataTypeForValueRector`](../rules/PHPOffice/Rector/StaticCall/ChangeDataTypeForValueRector.php)
```diff
final class SomeClass
{
public function run(): void
{
- $type = \PHPExcel_Cell_DataType::dataTypeForValue('value');
+ $type = \PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder::dataTypeForValue('value');
}
}
```
<br>
### ChangeDuplicateStyleArrayToApplyFromArrayRector
Change method call `duplicateStyleArray()` to `getStyle()` + `applyFromArray()`
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeDuplicateStyleArrayToApplyFromArrayRector`](../rules/PHPOffice/Rector/MethodCall/ChangeDuplicateStyleArrayToApplyFromArrayRector.php)
```diff
final class SomeClass
2019-09-25 08:49:53 +00:00
{
public function run(): void
2019-09-25 08:49:53 +00:00
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->duplicateStyleArray($styles, $range, $advanced);
+ $worksheet->getStyle($range)->applyFromArray($styles, $advanced);
2019-09-25 08:49:53 +00:00
}
}
```
<br>
### ChangeIOFactoryArgumentRector
2019-02-21 14:36:16 +00:00
Change argument of `PHPExcel_IOFactory::createReader()`, `PHPExcel_IOFactory::createWriter()` and `PHPExcel_IOFactory::identify()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeIOFactoryArgumentRector`](../rules/PHPOffice/Rector/StaticCall/ChangeIOFactoryArgumentRector.php)
2019-02-21 14:36:16 +00:00
```diff
final class SomeClass
{
public function run(): void
{
- $writer = \PHPExcel_IOFactory::createWriter('CSV');
+ $writer = \PHPExcel_IOFactory::createWriter('Csv');
}
}
```
<br>
### ChangePdfWriterRector
2019-05-29 13:40:20 +00:00
Change init of PDF writer
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangePdfWriterRector`](../rules/PHPOffice/Rector/StaticCall/ChangePdfWriterRector.php)
```diff
final class SomeClass
{
public function run(): void
{
- \PHPExcel_Settings::setPdfRendererName(PHPExcel_Settings::PDF_RENDERER_MPDF);
- \PHPExcel_Settings::setPdfRenderer($somePath);
- $writer = \PHPExcel_IOFactory::createWriter($spreadsheet, 'PDF');
+ $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
}
}
```
<br>
### ChangeSearchLocationToRegisterReaderRector
Change argument `addSearchLocation()` to `registerReader()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeSearchLocationToRegisterReaderRector`](../rules/PHPOffice/Rector/StaticCall/ChangeSearchLocationToRegisterReaderRector.php)
```diff
final class SomeClass
{
public function run(): void
{
- \PHPExcel_IOFactory::addSearchLocation($type, $location, $classname);
+ \PhpOffice\PhpSpreadsheet\IOFactory::registerReader($type, $classname);
}
}
```
<br>
### GetDefaultStyleToGetParentRector
Methods to (new `Worksheet())->getDefaultStyle()` to `getParent()->getDefaultStyle()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\MethodCall\GetDefaultStyleToGetParentRector`](../rules/PHPOffice/Rector/MethodCall/GetDefaultStyleToGetParentRector.php)
2019-03-09 13:24:30 +00:00
```diff
class SomeClass
{
public function run()
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->getDefaultStyle();
+ $worksheet->getParent()->getDefaultStyle();
}
}
```
<br>
### IncreaseColumnIndexRector
Column index changed from 0 to 1 - run only ONCE! changes current value without memory
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\MethodCall\IncreaseColumnIndexRector`](../rules/PHPOffice/Rector/MethodCall/IncreaseColumnIndexRector.php)
```diff
final class SomeClass
{
public function run(): void
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->setCellValueByColumnAndRow(0, 3, '1150');
+ $worksheet->setCellValueByColumnAndRow(1, 3, '1150');
}
}
2019-03-09 13:24:30 +00:00
```
<br>
2019-03-09 13:24:30 +00:00
### RemoveSetTempDirOnExcelWriterRector
Remove `setTempDir()` on PHPExcel_Writer_Excel5
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPOffice\Rector\MethodCall\RemoveSetTempDirOnExcelWriterRector`](../rules/PHPOffice/Rector/MethodCall/RemoveSetTempDirOnExcelWriterRector.php)
```diff
final class SomeClass
{
public function run(): void
{
$writer = new \PHPExcel_Writer_Excel5;
- $writer->setTempDir();
}
}
```
<br>
## PHPUnit
2018-12-31 11:50:32 +00:00
### AddDoesNotPerformAssertionToNonAssertingTestRector
2018-12-31 11:50:32 +00:00
Tests without assertion will have `@doesNotPerformAssertion`
2018-12-31 11:50:32 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\ClassMethod\AddDoesNotPerformAssertionToNonAssertingTestRector`](../rules/PHPUnit/Rector/ClassMethod/AddDoesNotPerformAssertionToNonAssertingTestRector.php)
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
+ /**
+ * @doesNotPerformAssertions
+ */
public function test()
{
$nothing = 5;
}
}
```
2019-09-25 08:49:53 +00:00
<br>
2019-09-25 08:49:53 +00:00
### AddProphecyTraitRector
2019-09-25 08:49:53 +00:00
Add Prophecy trait for method using `$this->prophesize()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\Class_\AddProphecyTraitRector`](../rules/PHPUnit/Rector/Class_/AddProphecyTraitRector.php)
2018-10-21 22:26:45 +00:00
2018-10-23 18:58:57 +00:00
```diff
use PHPUnit\Framework\TestCase;
+use Prophecy\PhpUnit\ProphecyTrait;
final class ExampleTest extends TestCase
{
+ use ProphecyTrait;
+
public function testOne(): void
{
$prophecy = $this->prophesize(\AnInterface::class);
}
}
2018-10-23 18:58:57 +00:00
```
2018-10-21 22:26:45 +00:00
<br>
2018-10-21 22:26:45 +00:00
### AddSeeTestAnnotationRector
Add `@see` annotation test of the class for faster jump to test. Make it FQN, so it stays in the annotation, not in the PHP source code.
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\Class_\AddSeeTestAnnotationRector`](../rules/PHPUnit/Rector/Class_/AddSeeTestAnnotationRector.php)
```diff
+/**
+ * @see \SomeServiceTest
+ */
class SomeService
{
}
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
{
}
```
<br>
2021-02-13 14:57:30 +00:00
### ArrayArgumentToDataProviderRector
Move array argument from tests into data provider [configurable]
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\Class_\ArrayArgumentToDataProviderRector`](../rules/PHPUnit/Rector/Class_/ArrayArgumentToDataProviderRector.php)
```php
use Rector\PHPUnit\Rector\Class_\ArrayArgumentToDataProviderRector;
use Rector\PHPUnit\ValueObject\ArrayArgumentToDataProvider;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArrayArgumentToDataProviderRector::class)
->call('configure', [[
ArrayArgumentToDataProviderRector::ARRAY_ARGUMENTS_TO_DATA_PROVIDERS => ValueObjectInliner::inline([
new ArrayArgumentToDataProvider('PHPUnit\Framework\TestCase', 'doTestMultiple', 'doTestSingle', 'number'),
]),
]]);
};
```
```diff
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
{
- public function test()
+ /**
+ * @dataProvider provideData()
+ */
+ public function test(int $number)
{
- $this->doTestMultiple([1, 2, 3]);
+ $this->doTestSingle($number);
+ }
+
+ public function provideData(): \Iterator
+ {
+ yield [1];
+ yield [2];
+ yield [3];
}
}
```
<br>
### AssertCompareToSpecificMethodRector
2019-02-21 14:36:16 +00:00
Turns vague php-only method in PHPUnit TestCase to more specific
2019-02-21 14:36:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertCompareToSpecificMethodRector`](../rules/PHPUnit/Rector/MethodCall/AssertCompareToSpecificMethodRector.php)
2019-02-21 14:36:16 +00:00
```diff
-$this->assertSame(10, count($anything), "message");
+$this->assertCount(10, $anything, "message");
```
<br>
```diff
-$this->assertNotEquals(get_class($value), stdClass::class);
+$this->assertNotInstanceOf(stdClass::class, $value);
```
<br>
### AssertComparisonToSpecificMethodRector
Turns comparison operations to their method name alternatives in PHPUnit TestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertComparisonToSpecificMethodRector`](../rules/PHPUnit/Rector/MethodCall/AssertComparisonToSpecificMethodRector.php)
```diff
-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
```
<br>
```diff
-$this->assertFalse($foo >= $bar, "message");
+$this->assertLessThanOrEqual($bar, $foo, "message");
2019-02-21 14:36:16 +00:00
```
<br>
2019-02-21 14:36:16 +00:00
### AssertEqualsParameterToSpecificMethodsTypeRector
2018-12-31 11:50:32 +00:00
Change `assertEquals()/assertNotEquals()` method parameters to new specific alternatives
2018-12-31 11:50:32 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertEqualsParameterToSpecificMethodsTypeRector`](../rules/PHPUnit/Rector/MethodCall/AssertEqualsParameterToSpecificMethodsTypeRector.php)
2018-12-31 11:50:32 +00:00
```diff
final class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
$value = 'value';
- $this->assertEquals('string', $value, 'message', 5.0);
+ $this->assertEqualsWithDelta('string', $value, 5.0, 'message');
- $this->assertEquals('string', $value, 'message', 0.0, 20);
+ $this->assertEquals('string', $value, 'message', 0.0);
- $this->assertEquals('string', $value, 'message', 0.0, 10, true);
+ $this->assertEqualsCanonicalizing('string', $value, 'message');
- $this->assertEquals('string', $value, 'message', 0.0, 10, false, true);
+ $this->assertEqualsIgnoringCase('string', $value, 'message');
}
}
2018-12-31 11:50:32 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
### AssertEqualsToSameRector
Turns `assertEquals()` into stricter `assertSame()` for scalar values in PHPUnit TestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertEqualsToSameRector`](../rules/PHPUnit/Rector/MethodCall/AssertEqualsToSameRector.php)
```diff
-$this->assertEquals(2, $result, "message");
+$this->assertSame(2, $result, "message");
```
<br>
```diff
-$this->assertEquals($aString, $result, "message");
+$this->assertSame($aString, $result, "message");
```
<br>
### AssertFalseStrposToContainsRector
2019-05-29 13:40:20 +00:00
Turns `strpos`/`stripos` comparisons to their method name alternatives in PHPUnit TestCase
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertFalseStrposToContainsRector`](../rules/PHPUnit/Rector/MethodCall/AssertFalseStrposToContainsRector.php)
2019-05-29 13:40:20 +00:00
```diff
-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
```
<br>
```diff
-$this->assertNotFalse(stripos($anything, "foo"), "message");
+$this->assertContains("foo", $anything, "message");
```
<br>
2019-05-29 13:40:20 +00:00
### AssertInstanceOfComparisonRector
2019-05-29 13:40:20 +00:00
Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertInstanceOfComparisonRector`](../rules/PHPUnit/Rector/MethodCall/AssertInstanceOfComparisonRector.php)
2019-09-25 08:49:53 +00:00
```diff
-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertInstanceOf("Foo", $foo, "message");
```
<br>
```diff
-$this->assertFalse($foo instanceof Foo, "message");
+$this->assertNotInstanceOf("Foo", $foo, "message");
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
### AssertIssetToSpecificMethodRector
2019-05-19 08:27:38 +00:00
Turns isset comparisons to their method name alternatives in PHPUnit TestCase
2019-05-19 08:27:38 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertIssetToSpecificMethodRector`](../rules/PHPUnit/Rector/MethodCall/AssertIssetToSpecificMethodRector.php)
2019-05-19 08:27:38 +00:00
```diff
-$this->assertTrue(isset($anything->foo));
+$this->assertObjectHasAttribute("foo", $anything);
2019-05-19 08:27:38 +00:00
```
<br>
```diff
-$this->assertFalse(isset($anything["foo"]), "message");
+$this->assertArrayNotHasKey("foo", $anything, "message");
```
2018-10-23 18:58:57 +00:00
<br>
### AssertNotOperatorRector
Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertNotOperatorRector`](../rules/PHPUnit/Rector/MethodCall/AssertNotOperatorRector.php)
```diff
-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
```
<br>
2018-10-21 22:26:45 +00:00
```diff
-$this->assertFalse(!$foo, "message");
+$this->assertTrue($foo, "message");
2018-08-01 20:09:34 +00:00
```
2018-07-31 12:50:39 +00:00
<br>
### AssertPropertyExistsRector
Turns `property_exists` comparisons to their method name alternatives in PHPUnit TestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertPropertyExistsRector`](../rules/PHPUnit/Rector/MethodCall/AssertPropertyExistsRector.php)
```diff
-$this->assertTrue(property_exists(new Class, "property"), "message");
+$this->assertClassHasAttribute("property", "Class", "message");
```
<br>
```diff
-$this->assertFalse(property_exists(new Class, "property"), "message");
+$this->assertClassNotHasAttribute("property", "Class", "message");
```
<br>
### AssertRegExpRector
Turns `preg_match` comparisons to their method name alternatives in PHPUnit TestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertRegExpRector`](../rules/PHPUnit/Rector/MethodCall/AssertRegExpRector.php)
```diff
-$this->assertSame(1, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertRegExp("/^Message for ".*"\.$/", $string, $message);
```
<br>
```diff
-$this->assertEquals(false, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertNotRegExp("/^Message for ".*"\.$/", $string, $message);
```
<br>
### AssertResourceToClosedResourceRector
Turns `assertIsNotResource()` into stricter `assertIsClosedResource()` for resource values in PHPUnit TestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertResourceToClosedResourceRector`](../rules/PHPUnit/Rector/MethodCall/AssertResourceToClosedResourceRector.php)
```diff
-$this->assertIsNotResource($aResource, "message");
+$this->assertIsClosedResource($aResource, "message");
```
<br>
### AssertSameBoolNullToSpecificMethodRector
2018-07-31 12:50:39 +00:00
Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase
2018-07-31 12:50:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertSameBoolNullToSpecificMethodRector`](../rules/PHPUnit/Rector/MethodCall/AssertSameBoolNullToSpecificMethodRector.php)
```diff
-$this->assertSame(null, $anything);
+$this->assertNull($anything);
2018-07-31 12:50:39 +00:00
```
<br>
```diff
-$this->assertNotSame(false, $anything);
+$this->assertNotFalse($anything);
```
<br>
### AssertSameTrueFalseToAssertTrueFalseRector
Change `$this->assertSame(true,` ...) to `assertTrue()`
2018-07-31 12:50:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertSameTrueFalseToAssertTrueFalseRector`](../rules/PHPUnit/Rector/MethodCall/AssertSameTrueFalseToAssertTrueFalseRector.php)
2018-07-31 12:50:39 +00:00
```diff
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
public function test()
{
$value = (bool) mt_rand(0, 1);
- $this->assertSame(true, $value);
+ $this->assertTrue($value);
}
}
2018-08-01 20:09:34 +00:00
```
<br>
2018-10-12 23:15:00 +00:00
### AssertTrueFalseInternalTypeToSpecificMethodRector
Turns true/false with internal type comparisons to their method name alternatives in PHPUnit TestCase
2019-03-09 13:24:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertTrueFalseInternalTypeToSpecificMethodRector`](../rules/PHPUnit/Rector/MethodCall/AssertTrueFalseInternalTypeToSpecificMethodRector.php)
2019-09-25 08:49:53 +00:00
```diff
-$this->assertTrue(is_{internal_type}($anything), "message");
+$this->assertInternalType({internal_type}, $anything, "message");
```
2019-03-09 13:24:30 +00:00
<br>
```diff
-$this->assertFalse(is_{internal_type}($anything), "message");
+$this->assertNotInternalType({internal_type}, $anything, "message");
2019-03-09 13:24:30 +00:00
```
<br>
### AssertTrueFalseToSpecificMethodRector
Turns true/false comparisons to their method name alternatives in PHPUnit TestCase when possible
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertTrueFalseToSpecificMethodRector`](../rules/PHPUnit/Rector/MethodCall/AssertTrueFalseToSpecificMethodRector.php)
2018-12-31 11:50:32 +00:00
```diff
-$this->assertTrue(is_readable($readmeFile), "message");
+$this->assertIsReadable($readmeFile, "message");
2018-12-31 11:50:32 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
### ConstructClassMethodToSetUpTestCaseRector
2018-10-12 23:15:00 +00:00
Change `__construct()` method in tests of `PHPUnit\Framework\TestCase` to `setUp()`, to prevent dangerous override
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\Class_\ConstructClassMethodToSetUpTestCaseRector`](../rules/PHPUnit/Rector/Class_/ConstructClassMethodToSetUpTestCaseRector.php)
2018-10-12 23:15:00 +00:00
2018-08-01 20:09:34 +00:00
```diff
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
private $someValue;
- public function __construct(?string $name = null, array $data = [], string $dataName = '')
+ protected function setUp()
{
+ parent::setUp();
+
$this->someValue = 1000;
- parent::__construct($name, $data, $dataName);
}
}
2018-05-05 12:48:33 +00:00
```
<br>
### CreateMockToCreateStubRector
2019-05-01 23:56:58 +00:00
Replaces `createMock()` with `createStub()` when relevant
2019-05-01 23:56:58 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\CreateMockToCreateStubRector`](../rules/PHPUnit/Rector/MethodCall/CreateMockToCreateStubRector.php)
2019-05-01 23:56:58 +00:00
```diff
use PHPUnit\Framework\TestCase
class MyTest extends TestCase
{
public function testItBehavesAsExpected(): void
{
- $stub = $this->createMock(\Exception::class);
+ $stub = $this->createStub(\Exception::class);
$stub->method('getMessage')
->willReturn('a message');
$mock = $this->createMock(\Exception::class);
$mock->expects($this->once())
->method('getMessage')
->willReturn('a message');
self::assertSame('a message', $stub->getMessage());
self::assertSame('a message', $mock->getMessage());
}
}
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
### DelegateExceptionArgumentsRector
Takes `setExpectedException()` 2nd and next arguments to own methods in PHPUnit.
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\DelegateExceptionArgumentsRector`](../rules/PHPUnit/Rector/MethodCall/DelegateExceptionArgumentsRector.php)
```diff
-$this->setExpectedException(Exception::class, "Message", "CODE");
+$this->setExpectedException(Exception::class);
+$this->expectExceptionMessage('Message');
+$this->expectExceptionCode('CODE');
```
<br>
### ExceptionAnnotationRector
Changes ``@expectedException` annotations to `expectException*()` methods
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\ClassMethod\ExceptionAnnotationRector`](../rules/PHPUnit/Rector/ClassMethod/ExceptionAnnotationRector.php)
```diff
-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
public function test()
{
+ $this->expectException('Exception');
+ $this->expectExceptionMessage('Message');
// tested code
}
```
<br>
### ExplicitPhpErrorApiRector
2019-05-24 20:30:15 +00:00
Use explicit API for expecting PHP errors, warnings, and notices
2019-05-24 20:30:15 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\ExplicitPhpErrorApiRector`](../rules/PHPUnit/Rector/MethodCall/ExplicitPhpErrorApiRector.php)
2019-05-24 20:30:15 +00:00
```diff
final class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
- $this->expectException(\PHPUnit\Framework\TestCase\Deprecated::class);
- $this->expectException(\PHPUnit\Framework\TestCase\Error::class);
- $this->expectException(\PHPUnit\Framework\TestCase\Notice::class);
- $this->expectException(\PHPUnit\Framework\TestCase\Warning::class);
+ $this->expectDeprecation();
+ $this->expectError();
+ $this->expectNotice();
+ $this->expectWarning();
}
}
```
<br>
### GetMockBuilderGetMockToCreateMockRector
Remove `getMockBuilder()` to `createMock()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\GetMockBuilderGetMockToCreateMockRector`](../rules/PHPUnit/Rector/MethodCall/GetMockBuilderGetMockToCreateMockRector.php)
```diff
class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
- $applicationMock = $this->getMockBuilder('SomeClass')
- ->disableOriginalConstructor()
- ->getMock();
+ $applicationMock = $this->createMock('SomeClass');
}
2019-09-25 08:49:53 +00:00
}
```
<br>
### GetMockRector
Turns getMock*() methods to `createMock()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\StaticCall\GetMockRector`](../rules/PHPUnit/Rector/StaticCall/GetMockRector.php)
```diff
-$this->getMock("Class");
+$this->createMock("Class");
```
<br>
```diff
-$this->getMockWithoutInvokingTheOriginalConstructor("Class");
+$this->createMock("Class");
```
<br>
### RemoveDataProviderTestPrefixRector
Data provider methods cannot start with "test" prefix
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\Class_\RemoveDataProviderTestPrefixRector`](../rules/PHPUnit/Rector/Class_/RemoveDataProviderTestPrefixRector.php)
```diff
class SomeClass extends PHPUnit\Framework\TestCase
{
/**
- * @dataProvider testProvideData()
+ * @dataProvider provideData()
*/
public function test()
{
$nothing = 5;
}
- public function testProvideData()
+ public function provideData()
{
return ['123'];
}
}
```
<br>
### RemoveEmptyTestMethodRector
2018-08-01 20:09:34 +00:00
Remove empty test methods
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\ClassMethod\RemoveEmptyTestMethodRector`](../rules/PHPUnit/Rector/ClassMethod/RemoveEmptyTestMethodRector.php)
2018-08-01 20:09:34 +00:00
```diff
class SomeTest extends \PHPUnit\Framework\TestCase
{
- /**
- * testGetTranslatedModelField method
- *
- * @return void
- */
- public function testGetTranslatedModelField()
- {
- }
}
```
2019-09-25 08:49:53 +00:00
<br>
### RemoveExpectAnyFromMockRector
Remove `expect($this->any())` from mocks as it has no added value
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\RemoveExpectAnyFromMockRector`](../rules/PHPUnit/Rector/MethodCall/RemoveExpectAnyFromMockRector.php)
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
public function test()
{
$translator = $this->getMock('SomeClass');
- $translator->expects($this->any())
- ->method('trans')
+ $translator->method('trans')
->willReturn('translated max {{ max }}!');
}
}
2018-08-01 20:09:34 +00:00
```
<br>
### ReplaceAssertArraySubsetWithDmsPolyfillRector
2019-05-01 23:56:58 +00:00
Change `assertArraySubset()` to static call of DMS\PHPUnitExtensions\ArraySubset\Assert
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\ReplaceAssertArraySubsetWithDmsPolyfillRector`](../rules/PHPUnit/Rector/MethodCall/ReplaceAssertArraySubsetWithDmsPolyfillRector.php)
2019-05-01 23:56:58 +00:00
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
public function test()
{
- self::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
+ \DMS\PHPUnitExtensions\ArraySubset\Assert::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
- $this->assertArraySubset(['bar' => 0], ['bar' => '0'], true);
+ \DMS\PHPUnitExtensions\ArraySubset\Assert::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
}
}
```
<br>
### SimplifyForeachInstanceOfRector
Simplify unnecessary foreach check of instances
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\Foreach_\SimplifyForeachInstanceOfRector`](../rules/PHPUnit/Rector/Foreach_/SimplifyForeachInstanceOfRector.php)
```diff
-foreach ($foos as $foo) {
- $this->assertInstanceOf(SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
### SpecificAssertContainsRector
2018-12-31 19:29:12 +00:00
Change `assertContains()/assertNotContains()` method to new string and iterable alternatives
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\SpecificAssertContainsRector`](../rules/PHPUnit/Rector/MethodCall/SpecificAssertContainsRector.php)
```diff
final class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
- $this->assertContains('foo', 'foo bar');
- $this->assertNotContains('foo', 'foo bar');
+ $this->assertStringContainsString('foo', 'foo bar');
+ $this->assertStringNotContainsString('foo', 'foo bar');
}
}
2018-08-01 20:09:34 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
### SpecificAssertContainsWithoutIdentityRector
2019-02-21 14:36:16 +00:00
Change `assertContains()/assertNotContains()` with non-strict comparison to new specific alternatives
2019-02-21 14:36:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\SpecificAssertContainsWithoutIdentityRector`](../rules/PHPUnit/Rector/MethodCall/SpecificAssertContainsWithoutIdentityRector.php)
2019-02-21 14:36:16 +00:00
```diff
-final class SomeTest extends \PHPUnit\Framework\TestCase
+final class SomeTest extends TestCase
{
public function test()
{
$objects = [ new \stdClass(), new \stdClass(), new \stdClass() ];
- $this->assertContains(new \stdClass(), $objects, 'message', false, false);
- $this->assertNotContains(new \stdClass(), $objects, 'message', false, false);
+ $this->assertContainsEquals(new \stdClass(), $objects, 'message');
+ $this->assertNotContainsEquals(new \stdClass(), $objects, 'message');
}
}
```
<br>
### SpecificAssertInternalTypeRector
Change `assertInternalType()/assertNotInternalType()` method to new specific alternatives
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\SpecificAssertInternalTypeRector`](../rules/PHPUnit/Rector/MethodCall/SpecificAssertInternalTypeRector.php)
2020-01-21 14:55:01 +00:00
```diff
final class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
$value = 'value';
- $this->assertInternalType('string', $value);
- $this->assertNotInternalType('array', $value);
+ $this->assertIsString($value);
+ $this->assertIsNotArray($value);
}
}
2020-01-21 14:55:01 +00:00
```
<br>
2020-01-21 14:55:01 +00:00
### TestListenerToHooksRector
2019-05-29 13:40:20 +00:00
Refactor "*TestListener.php" to particular "*Hook.php" files
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\Class_\TestListenerToHooksRector`](../rules/PHPUnit/Rector/Class_/TestListenerToHooksRector.php)
2019-05-29 13:40:20 +00:00
```diff
namespace App\Tests;
-use PHPUnit\Framework\TestListener;
-
-final class BeforeListHook implements TestListener
+final class BeforeListHook implements \PHPUnit\Runner\BeforeTestHook, \PHPUnit\Runner\AfterTestHook
{
- public function addError(Test $test, \Throwable $t, float $time): void
+ public function executeBeforeTest(Test $test): void
{
- }
-
- public function addWarning(Test $test, Warning $e, float $time): void
- {
- }
-
- public function addFailure(Test $test, AssertionFailedError $e, float $time): void
- {
- }
-
- public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
- {
- }
-
- public function addRiskyTest(Test $test, \Throwable $t, float $time): void
- {
- }
-
- public function addSkippedTest(Test $test, \Throwable $t, float $time): void
- {
- }
-
- public function startTestSuite(TestSuite $suite): void
- {
- }
-
- public function endTestSuite(TestSuite $suite): void
- {
- }
-
- public function startTest(Test $test): void
- {
echo 'start test!';
}
- public function endTest(Test $test, float $time): void
+ public function executeAfterTest(Test $test, float $time): void
{
echo $time;
}
}
2019-02-21 14:36:16 +00:00
```
<br>
2019-02-21 14:36:16 +00:00
### TryCatchToExpectExceptionRector
2018-12-31 19:29:12 +00:00
Turns try/catch to `expectException()` call
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\ClassMethod\TryCatchToExpectExceptionRector`](../rules/PHPUnit/Rector/ClassMethod/TryCatchToExpectExceptionRector.php)
2018-12-31 19:29:12 +00:00
2019-05-29 13:40:20 +00:00
```diff
-try {
- $someService->run();
-} catch (Throwable $exception) {
- $this->assertInstanceOf(RuntimeException::class, $e);
- $this->assertContains('There was an error executing the following script', $e->getMessage());
-}
+$this->expectException(RuntimeException::class);
+$this->expectExceptionMessage('There was an error executing the following script');
+$someService->run();
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
### UseSpecificWillMethodRector
2019-05-29 13:40:20 +00:00
Changes `->will($this->xxx())` to one specific method
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\UseSpecificWillMethodRector`](../rules/PHPUnit/Rector/MethodCall/UseSpecificWillMethodRector.php)
2019-05-29 13:40:20 +00:00
```diff
class SomeClass extends PHPUnit\Framework\TestCase
{
public function test()
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')->getMock();
$translator->expects($this->any())
->method('trans')
- ->with($this->equalTo('old max {{ max }}!'))
- ->will($this->returnValue('translated max {{ max }}!'));
+ ->with('old max {{ max }}!')
+ ->willReturnValue('translated max {{ max }}!');
}
2019-09-25 08:49:53 +00:00
}
2018-12-31 19:29:12 +00:00
```
<br>
2018-12-31 19:29:12 +00:00
### WithConsecutiveArgToArrayRector
2018-08-01 20:09:34 +00:00
Split `withConsecutive()` arg to array
2018-10-12 23:15:00 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\WithConsecutiveArgToArrayRector`](../rules/PHPUnit/Rector/MethodCall/WithConsecutiveArgToArrayRector.php)
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
public function run($one, $two)
{
}
}
2018-08-01 20:09:34 +00:00
class SomeTestCase extends \PHPUnit\Framework\TestCase
{
public function test()
{
$someClassMock = $this->createMock(SomeClass::class);
$someClassMock
->expects($this->exactly(2))
->method('run')
- ->withConsecutive(1, 2, 3, 5);
+ ->withConsecutive([1, 2], [3, 5]);
}
}
```
<br>
## PSR4
2018-08-01 20:09:34 +00:00
### MultipleClassFileToPsr4ClassesRector
Change multiple classes in one file to standalone PSR-4 classes.
2018-08-01 20:09:34 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PSR4\Rector\Namespace_\MultipleClassFileToPsr4ClassesRector`](../rules/PSR4/Rector/Namespace_/MultipleClassFileToPsr4ClassesRector.php)
2018-12-31 19:29:12 +00:00
```diff
+// new file: "app/Exceptions/FirstException.php"
namespace App\Exceptions;
2018-12-31 19:29:12 +00:00
use Exception;
final class FirstException extends Exception
{
}
+
+// new file: "app/Exceptions/SecondException.php"
+namespace App\Exceptions;
+
+use Exception;
final class SecondException extends Exception
{
}
```
<br>
### 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"
2021-03-12 23:52:38 +00:00
- class: [`Rector\PSR4\Rector\FileWithoutNamespace\NormalizeNamespaceByPSR4ComposerAutoloadRector`](../rules/PSR4/Rector/FileWithoutNamespace/NormalizeNamespaceByPSR4ComposerAutoloadRector.php)
- with `composer.json`:
```json
{
"autoload": {
"psr-4": {
"App\\CustomNamespace\\": "src"
}
}
}
```
2018-12-31 19:29:12 +00:00
```diff
// src/SomeClass.php
2021-01-30 20:30:37 +00:00
+namespace App\CustomNamespace;
+
class SomeClass
{
}
2018-12-31 19:29:12 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
## Php52
### ContinueToBreakInSwitchRector
2020-04-24 22:57:13 +00:00
Use break instead of continue in switch statements
2020-04-24 22:57:13 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php52\Rector\Switch_\ContinueToBreakInSwitchRector`](../rules/Php52/Rector/Switch_/ContinueToBreakInSwitchRector.php)
2020-04-24 22:57:13 +00:00
```diff
function some_run($value)
2020-04-24 22:57:13 +00:00
{
switch ($value) {
case 1:
echo 'Hi';
- continue;
+ break;
case 2:
echo 'Hello';
break;
}
2020-04-24 22:57:13 +00:00
}
```
<br>
2020-04-24 22:57:13 +00:00
### VarToPublicPropertyRector
2020-04-29 20:01:42 +00:00
Remove unused private method
2020-04-29 20:01:42 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php52\Rector\Property\VarToPublicPropertyRector`](../rules/Php52/Rector/Property/VarToPublicPropertyRector.php)
2020-04-29 20:01:42 +00:00
```diff
final class SomeController
{
- var $name = 'Tom';
+ public $name = 'Tom';
}
```
<br>
## Php53
2020-04-29 21:23:14 +00:00
### ClearReturnNewByReferenceRector
2020-04-29 21:23:14 +00:00
Remove reference from "$assign = &new Value;"
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php53\Rector\AssignRef\ClearReturnNewByReferenceRector`](../rules/Php53/Rector/AssignRef/ClearReturnNewByReferenceRector.php)
2020-04-29 21:23:14 +00:00
```diff
-$assign = &new Value;
+$assign = new Value;
2020-04-29 21:23:14 +00:00
```
<br>
2020-04-29 21:23:14 +00:00
### DirNameFileConstantToDirConstantRector
2020-06-05 10:33:30 +00:00
Convert dirname(__FILE__) to __DIR__
2020-06-05 10:33:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php53\Rector\FuncCall\DirNameFileConstantToDirConstantRector`](../rules/Php53/Rector/FuncCall/DirNameFileConstantToDirConstantRector.php)
2020-06-05 10:33:30 +00:00
```diff
class SomeClass
{
public function run()
{
- return dirname(__FILE__);
+ return __DIR__;
}
}
2020-06-05 10:33:30 +00:00
```
<br>
2020-06-05 10:33:30 +00:00
### ReplaceHttpServerVarsByServerRector
2020-03-26 22:22:29 +00:00
Rename old `$HTTP_*` variable names to new replacements
2020-03-26 22:22:29 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php53\Rector\Variable\ReplaceHttpServerVarsByServerRector`](../rules/Php53/Rector/Variable/ReplaceHttpServerVarsByServerRector.php)
2020-03-26 22:22:29 +00:00
```diff
-$serverVars = $HTTP_SERVER_VARS;
+$serverVars = $_SERVER;
```
2020-03-26 22:22:29 +00:00
<br>
2020-03-26 22:22:29 +00:00
### TernaryToElvisRector
2020-04-23 22:28:33 +00:00
Use ?: instead of ?, where useful
2020-04-23 22:28:33 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php53\Rector\Ternary\TernaryToElvisRector`](../rules/Php53/Rector/Ternary/TernaryToElvisRector.php)
2020-04-23 22:28:33 +00:00
```diff
function elvis()
{
- $value = $a ? $a : false;
+ $value = $a ?: false;
}
2020-04-23 22:28:33 +00:00
```
<br>
2020-04-23 22:28:33 +00:00
## Php54
2020-04-23 12:34:27 +00:00
### RemoveReferenceFromCallRector
2020-04-23 12:34:27 +00:00
Remove & from function and method calls
2020-04-23 12:34:27 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php54\Rector\FuncCall\RemoveReferenceFromCallRector`](../rules/Php54/Rector/FuncCall/RemoveReferenceFromCallRector.php)
```diff
final class SomeClass
{
public function run($one)
{
- return strlen(&$one);
+ return strlen($one);
}
}
2020-04-23 12:34:27 +00:00
```
<br>
2020-04-23 12:34:27 +00:00
### RemoveZeroBreakContinueRector
2020-04-24 12:00:49 +00:00
Remove 0 from break and continue
2020-04-24 12:00:49 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php54\Rector\Break_\RemoveZeroBreakContinueRector`](../rules/Php54/Rector/Break_/RemoveZeroBreakContinueRector.php)
2020-04-24 12:00:49 +00:00
```diff
class SomeClass
{
public function run($random)
{
- continue 0;
- break 0;
+ continue;
+ break;
$five = 5;
- continue $five;
+ continue 5;
- break $random;
+ break;
}
}
2020-04-24 12:00:49 +00:00
```
<br>
2020-04-24 12:00:49 +00:00
## Php55
2020-06-05 10:33:30 +00:00
### ClassConstantToSelfClassRector
Change `__CLASS__` to self::class
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php55\Rector\Class_\ClassConstantToSelfClassRector`](../rules/Php55/Rector/Class_/ClassConstantToSelfClassRector.php)
```diff
class SomeClass
{
public function callOnMe()
{
- var_dump(__CLASS__);
+ var_dump(self::class);
}
}
```
<br>
### PregReplaceEModifierRector
2020-06-05 10:33:30 +00:00
The /e modifier is no longer supported, use `preg_replace_callback` instead
2020-06-05 10:33:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php55\Rector\FuncCall\PregReplaceEModifierRector`](../rules/Php55/Rector/FuncCall/PregReplaceEModifierRector.php)
```diff
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);
}
}
2020-06-05 10:33:30 +00:00
```
<br>
2020-06-05 10:33:30 +00:00
### StringClassNameToClassConstantRector
Replace string class names by <class>::class constant
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php55\Rector\String_\StringClassNameToClassConstantRector`](../rules/Php55/Rector/String_/StringClassNameToClassConstantRector.php)
```php
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'],
]]);
};
```
```diff
class AnotherClass
{
}
class SomeClass
{
public function run()
{
- return 'AnotherClass';
+ return \AnotherClass::class;
}
}
```
<br>
## Php56
### AddDefaultValueForUndefinedVariableRector
Adds default value for undefined variable
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector`](../rules/Php56/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php)
```diff
class SomeClass
{
public function run()
{
+ $a = null;
if (rand(0, 1)) {
$a = 5;
}
echo $a;
}
}
```
<br>
### PowToExpRector
Changes pow(val, val2) to ** `(exp)` parameter
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php56\Rector\FuncCall\PowToExpRector`](../rules/Php56/Rector/FuncCall/PowToExpRector.php)
```diff
-pow(1, 2);
+1**2;
```
2019-03-31 12:25:39 +00:00
<br>
2019-03-31 12:25:39 +00:00
## Php70
2019-03-31 12:25:39 +00:00
### BreakNotInLoopOrSwitchToReturnRector
2019-03-31 12:25:39 +00:00
Convert break outside for/foreach/switch context to return
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\Break_\BreakNotInLoopOrSwitchToReturnRector`](../rules/Php70/Rector/Break_/BreakNotInLoopOrSwitchToReturnRector.php)
2019-03-31 12:25:39 +00:00
```diff
class SomeClass
{
public function run()
{
if ($isphp5)
return 1;
else
return 2;
- break;
+ return;
}
}
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
### CallUserMethodRector
2019-03-31 12:25:39 +00:00
Changes `call_user_method()/call_user_method_array()` to `call_user_func()/call_user_func_array()`
2019-03-31 12:25:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\FuncCall\CallUserMethodRector`](../rules/Php70/Rector/FuncCall/CallUserMethodRector.php)
2019-03-31 12:25:39 +00:00
```diff
-call_user_method($method, $obj, "arg1", "arg2");
+call_user_func(array(&$obj, "method"), "arg1", "arg2");
```
2019-03-31 12:25:39 +00:00
<br>
2019-03-31 12:25:39 +00:00
### EmptyListRector
2019-03-16 20:31:46 +00:00
`list()` cannot be empty
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\List_\EmptyListRector`](../rules/Php70/Rector/List_/EmptyListRector.php)
```diff
-'list() = $values;'
+'list($unusedGenerated) = $values;'
```
2019-03-16 20:31:46 +00:00
<br>
### EregToPregMatchRector
Changes ereg*() to preg*() calls
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\FuncCall\EregToPregMatchRector`](../rules/Php70/Rector/FuncCall/EregToPregMatchRector.php)
2019-03-16 20:31:46 +00:00
```diff
-ereg("hi")
+preg_match("#hi#");
```
2019-03-16 20:31:46 +00:00
<br>
### ExceptionHandlerTypehintRector
Changes property `@var` annotations from annotation to type.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\FunctionLike\ExceptionHandlerTypehintRector`](../rules/Php70/Rector/FunctionLike/ExceptionHandlerTypehintRector.php)
```diff
-function handler(Exception $exception) { ... }
+function handler(Throwable $exception) { ... }
set_exception_handler('handler');
```
<br>
### IfToSpaceshipRector
Changes if/else to spaceship <=> where useful
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\If_\IfToSpaceshipRector`](../rules/Php70/Rector/If_/IfToSpaceshipRector.php)
```diff
class SomeClass
2019-03-16 20:31:46 +00:00
{
public function run()
2019-03-16 20:31:46 +00:00
{
usort($languages, function ($a, $b) {
- if ($a[0] === $b[0]) {
- return 0;
- }
-
- return ($a[0] < $b[0]) ? 1 : -1;
+ return $b[0] <=> $a[0];
});
2019-03-16 20:31:46 +00:00
}
}
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
### ListSplitStringRector
2019-03-31 12:25:39 +00:00
`list()` cannot split string directly anymore, use `str_split()`
2019-03-16 20:31:46 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\Assign\ListSplitStringRector`](../rules/Php70/Rector/Assign/ListSplitStringRector.php)
2019-03-31 12:25:39 +00:00
```diff
-list($foo) = "string";
+list($foo) = str_split("string");
2019-03-16 20:31:46 +00:00
```
<br>
### ListSwapArrayOrderRector
2020-01-06 15:06:07 +00:00
`list()` assigns variables in reverse order - relevant in array assign
2020-01-06 15:06:07 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\Assign\ListSwapArrayOrderRector`](../rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php)
2020-01-06 15:06:07 +00:00
```diff
-list($a[], $a[]) = [1, 2];
+list($a[], $a[]) = array_reverse([1, 2]);
2020-01-06 15:06:07 +00:00
```
<br>
2020-01-06 15:06:07 +00:00
### MultiDirnameRector
Changes multiple `dirname()` calls to one with nesting level
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\FuncCall\MultiDirnameRector`](../rules/Php70/Rector/FuncCall/MultiDirnameRector.php)
```diff
-dirname(dirname($path));
+dirname($path, 2);
```
<br>
### NonVariableToVariableOnFunctionCallRector
2020-03-28 23:06:05 +00:00
Transform non variable like arguments to variable where a function or method expects an argument passed by reference
2020-05-12 15:09:29 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\FuncCall\NonVariableToVariableOnFunctionCallRector`](../rules/Php70/Rector/FuncCall/NonVariableToVariableOnFunctionCallRector.php)
2020-05-12 15:09:29 +00:00
```diff
-reset(a());
+$a = a(); reset($a);
```
<br>
### Php4ConstructorRector
Changes PHP 4 style constructor to __construct.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\ClassMethod\Php4ConstructorRector`](../rules/Php70/Rector/ClassMethod/Php4ConstructorRector.php)
2020-05-12 15:09:29 +00:00
```diff
class SomeClass
2020-05-12 15:09:29 +00:00
{
- public function SomeClass()
+ public function __construct()
2020-05-12 15:09:29 +00:00
{
}
}
```
<br>
2020-05-12 15:09:29 +00:00
### RandomFunctionRector
2020-05-29 10:41:25 +00:00
Changes rand, `srand` and `getrandmax` by new mt_* alternatives.
2020-05-29 10:41:25 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\FuncCall\RandomFunctionRector`](../rules/Php70/Rector/FuncCall/RandomFunctionRector.php)
2020-05-29 10:41:25 +00:00
```diff
-rand();
+mt_rand();
```
<br>
### ReduceMultipleDefaultSwitchRector
Remove first default switch, that is ignored
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\Switch_\ReduceMultipleDefaultSwitchRector`](../rules/Php70/Rector/Switch_/ReduceMultipleDefaultSwitchRector.php)
```diff
switch ($expr) {
default:
- echo "Hello World";
-
- default:
echo "Goodbye Moon!";
break;
2020-05-29 10:41:25 +00:00
}
```
<br>
2020-05-29 10:41:25 +00:00
### RenameMktimeWithoutArgsToTimeRector
Renames `mktime()` without arguments to `time()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\FuncCall\RenameMktimeWithoutArgsToTimeRector`](../rules/Php70/Rector/FuncCall/RenameMktimeWithoutArgsToTimeRector.php)
```diff
class SomeClass
{
public function run()
{
$time = mktime(1, 2, 3);
- $nextTime = mktime();
+ $nextTime = time();
}
}
```
<br>
### StaticCallOnNonStaticToInstanceCallRector
Changes static call to instance call, where not useful
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector`](../rules/Php70/Rector/StaticCall/StaticCallOnNonStaticToInstanceCallRector.php)
```diff
class Something
{
public function doWork()
{
}
}
class Another
{
public function run()
{
- return Something::doWork();
+ return (new Something)->doWork();
}
}
```
<br>
### TernaryToNullCoalescingRector
Changes unneeded null check to ?? operator
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\Ternary\TernaryToNullCoalescingRector`](../rules/Php70/Rector/Ternary/TernaryToNullCoalescingRector.php)
```diff
-$value === null ? 10 : $value;
+$value ?? 10;
```
<br>
```diff
-isset($value) ? $value : 10;
+$value ?? 10;
```
<br>
### TernaryToSpaceshipRector
2020-03-28 23:06:05 +00:00
Use <=> spaceship instead of ternary with same effect
2020-03-28 23:06:05 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\Ternary\TernaryToSpaceshipRector`](../rules/Php70/Rector/Ternary/TernaryToSpaceshipRector.php)
2020-03-28 23:06:05 +00:00
```diff
function order_func($a, $b) {
- return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
+ return $a <=> $b;
}
2020-03-28 23:06:05 +00:00
```
<br>
2020-03-28 23:06:05 +00:00
### ThisCallOnStaticMethodToStaticCallRector
Changes `$this->call()` to static method to static call
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\MethodCall\ThisCallOnStaticMethodToStaticCallRector`](../rules/Php70/Rector/MethodCall/ThisCallOnStaticMethodToStaticCallRector.php)
```diff
class SomeClass
{
public static function run()
{
- $this->eat();
+ static::eat();
}
public static function eat()
{
}
}
```
<br>
### WrapVariableVariableNameInCurlyBracesRector
Ensure variable variables are wrapped in curly braces
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php70\Rector\Variable\WrapVariableVariableNameInCurlyBracesRector`](../rules/Php70/Rector/Variable/WrapVariableVariableNameInCurlyBracesRector.php)
```diff
function run($foo)
{
- global $$foo->bar;
+ global ${$foo->bar};
}
```
<br>
## Php71
### AssignArrayToStringRector
String cannot be turned into array by assignment anymore
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\Assign\AssignArrayToStringRector`](../rules/Php71/Rector/Assign/AssignArrayToStringRector.php)
```diff
-$string = '';
+$string = [];
$string[] = 1;
```
<br>
### BinaryOpBetweenNumberAndStringRector
2019-09-25 08:49:53 +00:00
Change binary operation between some number + string to PHP 7.1 compatible version
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\BinaryOp\BinaryOpBetweenNumberAndStringRector`](../rules/Php71/Rector/BinaryOp/BinaryOpBetweenNumberAndStringRector.php)
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
{
public function run()
{
- $value = 5 + '';
- $value = 5.0 + 'hi';
+ $value = 5 + 0;
+ $value = 5.0 + 0
}
}
```
<br>
### CountOnNullRector
Changes `count()` on null to safe ternary check
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\FuncCall\CountOnNullRector`](../rules/Php71/Rector/FuncCall/CountOnNullRector.php)
2019-09-25 08:49:53 +00:00
```diff
$values = null;
-$count = count($values);
+$count = count((array) $values);
```
2019-09-25 08:49:53 +00:00
<br>
### IsIterableRector
Changes `is_array` + Traversable check to `is_iterable`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\BooleanOr\IsIterableRector`](../rules/Php71/Rector/BooleanOr/IsIterableRector.php)
```diff
-is_array($foo) || $foo instanceof Traversable;
+is_iterable($foo);
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
### ListToArrayDestructRector
2019-09-25 08:49:53 +00:00
Remove & from new &X
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\List_\ListToArrayDestructRector`](../rules/Php71/Rector/List_/ListToArrayDestructRector.php)
2020-07-24 11:46:57 +00:00
```diff
class SomeClass
{
public function run()
{
- list($id1, $name1) = $data;
+ [$id1, $name1] = $data;
- foreach ($data as list($id, $name)) {
+ foreach ($data as [$id, $name]) {
}
}
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
### MultiExceptionCatchRector
2019-09-25 08:49:53 +00:00
Changes multi catch of same exception to single one | separated.
2019-11-06 23:52:19 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\TryCatch\MultiExceptionCatchRector`](../rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php)
```diff
try {
- // Some code...
-} catch (ExceptionType1 $exception) {
- $sameCode;
-} catch (ExceptionType2 $exception) {
- $sameCode;
+ // Some code...
+} catch (ExceptionType1 | ExceptionType2 $exception) {
+ $sameCode;
}
```
2019-09-25 08:49:53 +00:00
<br>
2019-09-25 08:49:53 +00:00
### PublicConstantVisibilityRector
2019-09-25 08:49:53 +00:00
Add explicit public constant visibility.
2020-07-24 11:46:57 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\ClassConst\PublicConstantVisibilityRector`](../rules/Php71/Rector/ClassConst/PublicConstantVisibilityRector.php)
2020-07-24 11:46:57 +00:00
```diff
class SomeClass
{
- const HEY = 'you';
+ public const HEY = 'you';
}
```
<br>
### RemoveExtraParametersRector
Remove extra parameters
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector`](../rules/Php71/Rector/FuncCall/RemoveExtraParametersRector.php)
2019-09-25 08:49:53 +00:00
```diff
-strlen("asdf", 1);
+strlen("asdf");
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
### ReservedObjectRector
2019-09-25 08:49:53 +00:00
Changes reserved "Object" name to "<Smart>Object" where <Smart> can be configured
2019-09-25 08:49:53 +00:00
:wrench: **configure it!**
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php71\Rector\Name\ReservedObjectRector`](../rules/Php71/Rector/Name/ReservedObjectRector.php)
2019-09-25 08:49:53 +00:00
```php
use Rector\Php71\Rector\Name\ReservedObjectRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-09-25 08:49:53 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-09-25 08:49:53 +00:00
$services->set(ReservedObjectRector::class)
->call('configure', [[
ReservedObjectRector::RESERVED_KEYWORDS_TO_REPLACEMENTS => [
2021-03-12 23:52:38 +00:00
'ReservedObject' => 'SmartObject', 'Object' => 'AnotherSmartObject',
], ]]);
};
```
2019-09-25 08:49:53 +00:00
2019-09-25 08:49:53 +00:00
```diff
-class Object
+class SmartObject
{
}
```
2019-09-25 08:49:53 +00:00
<br>
2020-07-24 11:46:57 +00:00
## Php72
2020-07-24 11:46:57 +00:00
### CreateFunctionToAnonymousFunctionRector
Use anonymous functions instead of deprecated `create_function()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector`](../rules/Php72/Rector/FuncCall/CreateFunctionToAnonymousFunctionRector.php)
```diff
class ClassWithCreateFunction
2019-09-25 08:49:53 +00:00
{
public function run()
2019-09-25 08:49:53 +00:00
{
- $callable = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);");
+ $callable = function($matches) use ($delimiter) {
+ return $delimiter . strtolower($matches[1]);
+ };
2019-09-25 08:49:53 +00:00
}
}
```
<br>
2019-09-25 08:49:53 +00:00
### GetClassOnNullRector
2019-09-25 08:49:53 +00:00
Null is no more allowed in `get_class()`
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\FuncCall\GetClassOnNullRector`](../rules/Php72/Rector/FuncCall/GetClassOnNullRector.php)
2019-09-25 08:49:53 +00:00
```diff
final class SomeClass
{
public function getItem()
{
$value = null;
- return get_class($value);
+ return $value !== null ? get_class($value) : self::class;
}
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
### IsObjectOnIncompleteClassRector
2019-09-25 08:49:53 +00:00
Incomplete class returns inverted bool on `is_object()`
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\FuncCall\IsObjectOnIncompleteClassRector`](../rules/Php72/Rector/FuncCall/IsObjectOnIncompleteClassRector.php)
2019-09-25 08:49:53 +00:00
```diff
$incompleteObject = new __PHP_Incomplete_Class;
-$isObject = is_object($incompleteObject);
+$isObject = ! is_object($incompleteObject);
```
<br>
### ListEachRector
`each()` function is deprecated, use `key()` and `current()` instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\Assign\ListEachRector`](../rules/Php72/Rector/Assign/ListEachRector.php)
```diff
-list($key, $callback) = each($callbacks);
+$key = key($callbacks);
+$callback = current($callbacks);
+next($callbacks);
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
### ParseStrWithResultArgumentRector
2019-09-25 08:49:53 +00:00
Use `$result` argument in `parse_str()` function
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\FuncCall\ParseStrWithResultArgumentRector`](../rules/Php72/Rector/FuncCall/ParseStrWithResultArgumentRector.php)
```diff
-parse_str($this->query);
-$data = get_defined_vars();
+parse_str($this->query, $result);
+$data = $result;
```
<br>
### ReplaceEachAssignmentWithKeyCurrentRector
Replace `each()` assign outside loop
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\Assign\ReplaceEachAssignmentWithKeyCurrentRector`](../rules/Php72/Rector/Assign/ReplaceEachAssignmentWithKeyCurrentRector.php)
```diff
$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);
```
<br>
### StringifyDefineRector
Make first argument of `define()` string
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\FuncCall\StringifyDefineRector`](../rules/Php72/Rector/FuncCall/StringifyDefineRector.php)
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
{
public function run(int $a)
{
- define(CONSTANT_2, 'value');
+ define('CONSTANT_2', 'value');
define('CONSTANT', 'value');
}
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
### StringsAssertNakedRector
2019-09-25 08:49:53 +00:00
String asserts must be passed directly to `assert()`
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\FuncCall\StringsAssertNakedRector`](../rules/Php72/Rector/FuncCall/StringsAssertNakedRector.php)
2019-09-25 08:49:53 +00:00
```diff
function nakedAssert()
{
- assert('true === true');
- assert("true === true");
+ assert(true === true);
+ assert(true === true);
}
```
2019-09-25 08:49:53 +00:00
<br>
2020-07-24 11:46:57 +00:00
### UnsetCastRector
2020-07-24 11:46:57 +00:00
Removes (unset) cast
2020-02-13 21:48:16 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\Unset_\UnsetCastRector`](../rules/Php72/Rector/Unset_/UnsetCastRector.php)
2020-02-13 21:48:16 +00:00
```diff
-$different = (unset) $value;
+$different = null;
-$value = (unset) $value;
+unset($value);
```
<br>
### WhileEachToForeachRector
2019-09-25 08:49:53 +00:00
`each()` function is deprecated, use `foreach()` instead.
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php72\Rector\While_\WhileEachToForeachRector`](../rules/Php72/Rector/While_/WhileEachToForeachRector.php)
2020-07-24 11:46:57 +00:00
```diff
-while (list($key, $callback) = each($callbacks)) {
+foreach ($callbacks as $key => $callback) {
// ...
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
```diff
-while (list($key) = each($callbacks)) {
+foreach (array_keys($callbacks) as $key) {
// ...
}
```
<br>
## Php73
### ArrayKeyFirstLastRector
Make use of `array_key_first()` and `array_key_last()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\FuncCall\ArrayKeyFirstLastRector`](../rules/Php73/Rector/FuncCall/ArrayKeyFirstLastRector.php)
```diff
-reset($items);
-$firstKey = key($items);
+$firstKey = array_key_first($items);
```
<br>
```diff
-end($items);
-$lastKey = key($items);
+$lastKey = array_key_last($items);
```
<br>
2020-07-24 11:46:57 +00:00
### IsCountableRector
2020-07-24 11:46:57 +00:00
Changes `is_array` + Countable check to `is_countable`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\BooleanOr\IsCountableRector`](../rules/Php73/Rector/BooleanOr/IsCountableRector.php)
```diff
-is_array($foo) || $foo instanceof Countable;
+is_countable($foo);
```
2019-05-01 23:56:58 +00:00
<br>
2020-07-24 11:46:57 +00:00
### JsonThrowOnErrorRector
2020-07-24 11:46:57 +00:00
Adds JSON_THROW_ON_ERROR to `json_encode()` and `json_decode()` to throw JsonException on error
2019-05-01 23:56:58 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector`](../rules/Php73/Rector/FuncCall/JsonThrowOnErrorRector.php)
2019-05-01 23:56:58 +00:00
```diff
-json_encode($content);
-json_decode($json);
+json_encode($content, JSON_THROW_ON_ERROR);
+json_decode($json, null, null, JSON_THROW_ON_ERROR);
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
### RegexDashEscapeRector
2019-05-01 23:56:58 +00:00
Escape - in some cases
2019-05-01 23:56:58 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\FuncCall\RegexDashEscapeRector`](../rules/Php73/Rector/FuncCall/RegexDashEscapeRector.php)
2019-05-01 23:56:58 +00:00
```diff
-preg_match("#[\w-()]#", 'some text');
+preg_match("#[\w\-()]#", 'some text');
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
### SensitiveConstantNameRector
2020-07-24 11:46:57 +00:00
Changes case insensitive constants to sensitive ones.
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\ConstFetch\SensitiveConstantNameRector`](../rules/Php73/Rector/ConstFetch/SensitiveConstantNameRector.php)
2019-09-25 08:49:53 +00:00
```diff
define('FOO', 42, true);
var_dump(FOO);
-var_dump(foo);
+var_dump(FOO);
2019-05-29 13:40:20 +00:00
```
2019-05-01 23:56:58 +00:00
<br>
2019-05-29 13:40:20 +00:00
### SensitiveDefineRector
2019-08-05 21:10:47 +00:00
Changes case insensitive constants to sensitive ones.
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\FuncCall\SensitiveDefineRector`](../rules/Php73/Rector/FuncCall/SensitiveDefineRector.php)
2019-08-05 21:10:47 +00:00
```diff
-define('FOO', 42, true);
+define('FOO', 42);
```
2019-08-05 21:10:47 +00:00
<br>
2020-07-24 11:46:57 +00:00
### SensitiveHereNowDocRector
2020-07-24 11:46:57 +00:00
Changes heredoc/nowdoc that contains closing word to safe wrapper name
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\String_\SensitiveHereNowDocRector`](../rules/Php73/Rector/String_/SensitiveHereNowDocRector.php)
2019-08-05 21:10:47 +00:00
```diff
-$value = <<<A
+$value = <<<A_WRAP
A
-A
+A_WRAP
2019-08-05 21:10:47 +00:00
```
<br>
### SetCookieRector
Convert `setcookie` argument to PHP7.3 option array
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\FuncCall\SetCookieRector`](../rules/Php73/Rector/FuncCall/SetCookieRector.php)
```diff
-setcookie('name', $value, 360);
+setcookie('name', $value, ['expires' => 360]);
```
<br>
2020-07-24 11:46:57 +00:00
```diff
-setcookie('name', $name, 0, '', '', true, true);
+setcookie('name', $name, ['expires' => 0, 'path' => '', 'domain' => '', 'secure' => true, 'httponly' => true]);
```
<br>
### StringifyStrNeedlesRector
Makes needles explicit strings
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php73\Rector\FuncCall\StringifyStrNeedlesRector`](../rules/Php73/Rector/FuncCall/StringifyStrNeedlesRector.php)
```diff
$needle = 5;
-$fivePosition = strpos('725', $needle);
+$fivePosition = strpos('725', (string) $needle);
```
<br>
2019-08-05 21:10:47 +00:00
## Php74
### AddLiteralSeparatorToNumberRector
Add "_" as thousands separator in numbers for higher or equals to limitValue config
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector`](../rules/Php74/Rector/LNumber/AddLiteralSeparatorToNumberRector.php)
```php
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,
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $int = 500000;
- $float = 1000500.001;
+ $int = 500_000;
+ $float = 1_000_500.001;
}
}
```
<br>
### ArrayKeyExistsOnPropertyRector
Change `array_key_exists()` on property to `property_exists()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\FuncCall\ArrayKeyExistsOnPropertyRector`](../rules/Php74/Rector/FuncCall/ArrayKeyExistsOnPropertyRector.php)
```diff
class SomeClass
{
public $value;
}
$someClass = new SomeClass;
-array_key_exists('value', $someClass);
+property_exists($someClass, 'value');
```
<br>
### ArraySpreadInsteadOfArrayMergeRector
Change `array_merge()` to spread operator, except values with possible string `key` values
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\FuncCall\ArraySpreadInsteadOfArrayMergeRector`](../rules/Php74/Rector/FuncCall/ArraySpreadInsteadOfArrayMergeRector.php)
```diff
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];
}
}
```
<br>
### ChangeReflectionTypeToStringToGetNameRector
Change string calls on ReflectionType
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\MethodCall\ChangeReflectionTypeToStringToGetNameRector`](../rules/Php74/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php)
```diff
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();
}
}
```
<br>
### ClosureToArrowFunctionRector
Change closure to arrow function
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector`](../rules/Php74/Rector/Closure/ClosureToArrowFunctionRector.php)
```diff
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));
}
}
```
<br>
### ExportToReflectionFunctionRector
Change `export()` to ReflectionFunction alternatives
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\StaticCall\ExportToReflectionFunctionRector`](../rules/Php74/Rector/StaticCall/ExportToReflectionFunctionRector.php)
```diff
-$reflectionFunction = ReflectionFunction::export('foo');
-$reflectionFunctionAsString = ReflectionFunction::export('foo', true);
+$reflectionFunction = new ReflectionFunction('foo');
+$reflectionFunctionAsString = (string) new ReflectionFunction('foo');
```
<br>
### FilterVarToAddSlashesRector
2020-01-06 15:06:07 +00:00
Change `filter_var()` with slash escaping to `addslashes()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\FuncCall\FilterVarToAddSlashesRector`](../rules/Php74/Rector/FuncCall/FilterVarToAddSlashesRector.php)
```diff
$var= "Satya's here!";
-filter_var($var, FILTER_SANITIZE_MAGIC_QUOTES);
+addslashes($var);
```
2020-01-06 15:06:07 +00:00
<br>
### GetCalledClassToStaticClassRector
Change `get_called_class()` to static::class
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\FuncCall\GetCalledClassToStaticClassRector`](../rules/Php74/Rector/FuncCall/GetCalledClassToStaticClassRector.php)
2020-01-06 15:06:07 +00:00
```diff
class SomeClass
2020-01-06 15:06:07 +00:00
{
public function callOnMe()
{
- var_dump(get_called_class());
+ var_dump(static::class);
}
2020-01-06 15:06:07 +00:00
}
```
<br>
2020-01-06 15:06:07 +00:00
### MbStrrposEncodingArgumentPositionRector
Change `mb_strrpos()` encoding argument position
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\FuncCall\MbStrrposEncodingArgumentPositionRector`](../rules/Php74/Rector/FuncCall/MbStrrposEncodingArgumentPositionRector.php)
```diff
-mb_strrpos($text, "abc", "UTF-8");
+mb_strrpos($text, "abc", 0, "UTF-8");
```
<br>
### NullCoalescingOperatorRector
Use null coalescing operator ??=
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\Assign\NullCoalescingOperatorRector`](../rules/Php74/Rector/Assign/NullCoalescingOperatorRector.php)
```diff
$array = [];
-$array['user_id'] = $array['user_id'] ?? 'value';
+$array['user_id'] ??= 'value';
```
<br>
### RealToFloatTypeCastRector
Change deprecated (real) to (float)
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\Double\RealToFloatTypeCastRector`](../rules/Php74/Rector/Double/RealToFloatTypeCastRector.php)
```diff
class SomeClass
{
public function run()
{
- $number = (real) 5;
+ $number = (float) 5;
$number = (float) 5;
$number = (double) 5;
}
}
```
<br>
### ReservedFnFunctionRector
2019-05-29 13:40:20 +00:00
Change `fn()` function name, since it will be reserved keyword
2019-05-29 13:40:20 +00:00
:wrench: **configure it!**
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\Function_\ReservedFnFunctionRector`](../rules/Php74/Rector/Function_/ReservedFnFunctionRector.php)
2019-05-01 23:56:58 +00:00
```php
use Rector\Php74\Rector\Function_\ReservedFnFunctionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-05-01 23:56:58 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReservedFnFunctionRector::class)
->call('configure', [[
ReservedFnFunctionRector::RESERVED_NAMES_TO_NEW_ONES => [
'fn' => 'someFunctionName',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
class SomeClass
{
public function run()
{
- function fn($value)
+ function f($value)
{
return $value;
}
- fn(5);
+ f(5);
}
}
```
<br>
### RestoreDefaultNullToNullableTypePropertyRector
2020-01-03 18:20:13 +00:00
Add null default to properties with PHP 7.4 property nullable type
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector`](../rules/Php74/Rector/Property/RestoreDefaultNullToNullableTypePropertyRector.php)
2020-01-03 18:20:13 +00:00
```diff
class SomeClass
{
- public ?string $name;
+ public ?string $name = null;
}
2020-01-03 18:20:13 +00:00
```
<br>
### TypedPropertyRector
Changes property `@var` annotations from annotation to type.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php74\Rector\Property\TypedPropertyRector`](../rules/Php74/Rector/Property/TypedPropertyRector.php)
```php
use Rector\Php74\Rector\Property\TypedPropertyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-10-15 14:46:31 +00:00
$services->set(TypedPropertyRector::class)
->call('configure', [[
TypedPropertyRector::CLASS_LIKE_TYPE_ONLY => false,
]]);
};
```
2019-10-15 14:46:31 +00:00
2019-10-15 14:46:31 +00:00
```diff
final class SomeClass
{
- /**
- * @var int
- */
- private count;
+ private int count;
}
2019-10-15 14:46:31 +00:00
```
<br>
2019-10-15 14:46:31 +00:00
## Php80
### AnnotationToAttributeRector
Change annotation to attribute
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Class_\AnnotationToAttributeRector`](../rules/Php80/Rector/Class_/AnnotationToAttributeRector.php)
```diff
use Symfony\Component\Routing\Annotation\Route;
class SymfonyRoute
{
- /**
- * @Route("/path", name="action")
- */
+ #[Route(path: '/path', name: 'action')]
public function action()
{
}
}
```
<br>
2020-06-06 13:07:56 +00:00
### ChangeSwitchToMatchRector
2018-12-31 11:50:32 +00:00
Change `switch()` to `match()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Switch_\ChangeSwitchToMatchRector`](../rules/Php80/Rector/Switch_/ChangeSwitchToMatchRector.php)
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
public function run()
{
- switch ($this->lexer->lookahead['type']) {
- case Lexer::T_SELECT:
- $statement = $this->SelectStatement();
- break;
-
- case Lexer::T_UPDATE:
- $statement = $this->UpdateStatement();
- break;
-
- default:
- $statement = $this->syntaxError('SELECT, UPDATE or DELETE');
- break;
- }
+ $statement = match ($this->lexer->lookahead['type']) {
+ Lexer::T_SELECT => $this->SelectStatement(),
+ Lexer::T_UPDATE => $this->UpdateStatement(),
+ default => $this->syntaxError('SELECT, UPDATE or DELETE'),
+ };
}
}
2019-10-15 14:46:31 +00:00
```
<br>
2019-10-15 14:46:31 +00:00
### ClassOnObjectRector
2018-10-21 22:26:45 +00:00
Change get_class($object) to faster `$object::class`
2018-10-21 22:26:45 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\FuncCall\ClassOnObjectRector`](../rules/Php80/Rector/FuncCall/ClassOnObjectRector.php)
2018-10-21 22:26:45 +00:00
```diff
class SomeClass
{
public function run($object)
{
- return get_class($object);
+ return $object::class;
}
}
2018-10-21 22:26:45 +00:00
```
<br>
2018-08-01 20:09:34 +00:00
### ClassPropertyAssignToConstructorPromotionRector
2018-09-28 16:33:35 +00:00
Change simple property init and assign to constructor promotion
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector`](../rules/Php80/Rector/Class_/ClassPropertyAssignToConstructorPromotionRector.php)
2018-09-28 16:33:35 +00:00
```diff
class SomeClass
{
- public float $someVariable;
-
- public function __construct(float $someVariable = 0.0)
+ public function __construct(private float $someVariable = 0.0)
{
- $this->someVariable = $someVariable;
}
}
2018-09-28 16:33:35 +00:00
```
<br>
### FinalPrivateToPrivateVisibilityRector
Changes method visibility from final private to only private
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\ClassMethod\FinalPrivateToPrivateVisibilityRector`](../rules/Php80/Rector/ClassMethod/FinalPrivateToPrivateVisibilityRector.php)
```diff
class SomeClass
{
- final private function getter() {
+ private function getter() {
return $this;
}
}
```
<br>
### GetDebugTypeRector
Change ternary type resolve to `get_debug_type()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Ternary\GetDebugTypeRector`](../rules/Php80/Rector/Ternary/GetDebugTypeRector.php)
```diff
class SomeClass
{
public function run($value)
{
- return is_object($value) ? get_class($value) : gettype($value);
+ return get_debug_type($value);
}
}
```
<br>
### NullsafeOperatorRector
Change if null check with nullsafe operator ?-> with full short circuiting
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\If_\NullsafeOperatorRector`](../rules/Php80/Rector/If_/NullsafeOperatorRector.php)
```diff
class SomeClass
{
public function run($someObject)
{
- $someObject2 = $someObject->mayFail1();
- if ($someObject2 === null) {
- return null;
- }
-
- return $someObject2->mayFail2();
+ return $someObject->mayFail1()?->mayFail2();
}
}
```
<br>
### OptionalParametersAfterRequiredRector
Move required parameters after optional ones
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\ClassMethod\OptionalParametersAfterRequiredRector`](../rules/Php80/Rector/ClassMethod/OptionalParametersAfterRequiredRector.php)
```diff
class SomeObject
{
- public function run($optional = 1, $required)
+ public function run($required, $optional = 1)
{
}
}
```
<br>
### RemoveUnusedVariableInCatchRector
Remove unused variable in `catch()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Catch_\RemoveUnusedVariableInCatchRector`](../rules/Php80/Rector/Catch_/RemoveUnusedVariableInCatchRector.php)
```diff
final class SomeClass
{
public function run()
{
try {
- } catch (Throwable $notUsedThrowable) {
+ } catch (Throwable) {
}
}
}
```
<br>
### SetStateToStaticRector
Adds static visibility to `__set_state()` methods
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\ClassMethod\SetStateToStaticRector`](../rules/Php80/Rector/ClassMethod/SetStateToStaticRector.php)
```diff
class SomeClass
{
- public function __set_state($properties) {
+ public static function __set_state($properties) {
}
}
```
<br>
### StrContainsRector
2019-05-01 23:56:58 +00:00
Replace `strpos()` !== false and `strstr()` with `str_contains()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\NotIdentical\StrContainsRector`](../rules/Php80/Rector/NotIdentical/StrContainsRector.php)
2019-05-01 23:56:58 +00:00
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
- return strpos('abc', 'a') !== false;
+ return str_contains('abc', 'a');
}
}
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
### StrEndsWithRector
2019-10-15 14:46:31 +00:00
Change helper functions to `str_ends_with()`
2019-10-15 14:46:31 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Identical\StrEndsWithRector`](../rules/Php80/Rector/Identical/StrEndsWithRector.php)
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
{
public function run()
{
- $isMatch = substr($haystack, -strlen($needle)) === $needle;
+ $isMatch = str_ends_with($haystack, $needle);
}
}
2019-10-15 14:46:31 +00:00
```
<br>
2019-10-15 14:46:31 +00:00
### StrStartsWithRector
Change helper functions to `str_starts_with()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Identical\StrStartsWithRector`](../rules/Php80/Rector/Identical/StrStartsWithRector.php)
```diff
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);
}
}
```
<br>
### StringableForToStringRector
Add `Stringable` interface to classes with `__toString()` method
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\Class_\StringableForToStringRector`](../rules/Php80/Rector/Class_/StringableForToStringRector.php)
2018-07-31 12:50:39 +00:00
```diff
-class SomeClass
+class SomeClass implements Stringable
{
- public function __toString()
+ public function __toString(): string
{
return 'I can stringz';
}
}
2018-07-31 12:50:39 +00:00
```
<br>
### TokenGetAllToObjectRector
2019-03-31 12:25:39 +00:00
Complete missing constructor dependency instance by type
2019-03-31 12:25:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\FuncCall\TokenGetAllToObjectRector`](../rules/Php80/Rector/FuncCall/TokenGetAllToObjectRector.php)
2019-03-31 12:25:39 +00:00
```diff
final class SomeClass
2019-03-31 12:25:39 +00:00
{
public function run()
2019-03-31 12:25:39 +00:00
{
- $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::getAll($code);
+ foreach ($tokens as $phpToken) {
+ $name = $phpToken->getTokenName();
+ $text = $phpToken->text;
}
2019-03-31 12:25:39 +00:00
}
}
```
<br>
2019-03-31 12:25:39 +00:00
### UnionTypesRector
2018-05-04 22:30:32 +00:00
Change docs types to union types, where possible (properties are covered by TypedPropertiesRector)
2021-03-12 23:52:38 +00:00
- class: [`Rector\Php80\Rector\FunctionLike\UnionTypesRector`](../rules/Php80/Rector/FunctionLike/UnionTypesRector.php)
```diff
class SomeClass
{
- /**
- * @param array|int $number
- * @return bool|float
- */
- public function go($number)
+ public function go(array|int $number): bool|float
{
}
}
```
<br>
## PhpSpecToPHPUnit
### AddMockPropertiesRector
Migrate PhpSpec behavior to PHPUnit test
2021-03-12 23:52:38 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\Class_\AddMockPropertiesRector`](../rules/PhpSpecToPHPUnit/Rector/Class_/AddMockPropertiesRector.php)
```diff
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);
}
}
```
<br>
### MockVariableToPropertyFetchRector
2018-05-04 22:30:32 +00:00
Migrate PhpSpec behavior to PHPUnit test
2021-03-12 23:52:38 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\Variable\MockVariableToPropertyFetchRector`](../rules/PhpSpecToPHPUnit/Rector/Variable/MockVariableToPropertyFetchRector.php)
```diff
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);
}
}
```
<br>
### PhpSpecClassToPHPUnitClassRector
Migrate PhpSpec behavior to PHPUnit test
2021-03-12 23:52:38 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\Class_\PhpSpecClassToPHPUnitClassRector`](../rules/PhpSpecToPHPUnit/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php)
```diff
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);
}
}
2018-05-04 22:30:32 +00:00
```
<br>
### PhpSpecMethodToPHPUnitMethodRector
Migrate PhpSpec behavior to PHPUnit test
2021-03-12 23:52:38 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\ClassMethod\PhpSpecMethodToPHPUnitMethodRector`](../rules/PhpSpecToPHPUnit/Rector/ClassMethod/PhpSpecMethodToPHPUnitMethodRector.php)
```diff
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);
}
}
```
<br>
### PhpSpecMocksToPHPUnitMocksRector
2018-05-04 22:30:32 +00:00
Migrate PhpSpec behavior to PHPUnit test
2018-05-04 22:30:32 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecMocksToPHPUnitMocksRector`](../rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php)
2018-05-04 22:30:32 +00:00
```diff
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);
}
}
```
2018-10-23 18:58:57 +00:00
<br>
### PhpSpecPromisesToPHPUnitAssertRector
2018-10-23 18:58:57 +00:00
Migrate PhpSpec behavior to PHPUnit test
2018-10-23 18:58:57 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecPromisesToPHPUnitAssertRector`](../rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecPromisesToPHPUnitAssertRector.php)
```diff
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);
}
2019-05-29 13:40:20 +00:00
}
2018-10-12 23:15:00 +00:00
```
<br>
2018-10-23 18:58:57 +00:00
### RenameSpecFileToTestFileRector
2018-10-23 18:58:57 +00:00
Rename "*Spec.php" file to "*Test.php" file
2021-03-12 23:52:38 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\FileNode\RenameSpecFileToTestFileRector`](../rules/PhpSpecToPHPUnit/Rector/FileNode/RenameSpecFileToTestFileRector.php)
```diff
-// tests/SomeSpec.php
+// tests/SomeTest.php
```
<br>
2021-03-03 21:28:27 +00:00
## PostRector
### ClassRenamingPostRector
Rename references for classes that were renamed during Rector run
2021-03-12 23:52:38 +00:00
- class: [`Rector\PostRector\Rector\ClassRenamingPostRector`](../packages/PostRector/Rector/ClassRenamingPostRector.php)
2021-03-03 21:28:27 +00:00
```diff
-function (OriginalClass $someClass)
+function (RenamedClass $someClass)
{
}
```
<br>
### NameImportingPostRector
Imports fully qualified names
2021-03-12 23:52:38 +00:00
- class: [`Rector\PostRector\Rector\NameImportingPostRector`](../packages/PostRector/Rector/NameImportingPostRector.php)
2021-03-03 21:28:27 +00:00
```diff
+use App\AnotherClass;
+
class SomeClass
{
- public function run(App\AnotherClass $anotherClass)
+ public function run(AnotherClass $anotherClass)
{
}
}
```
<br>
### NodeAddingPostRector
Add nodes on weird positions
2021-03-12 23:52:38 +00:00
- class: [`Rector\PostRector\Rector\NodeAddingPostRector`](../packages/PostRector/Rector/NodeAddingPostRector.php)
2021-03-03 21:28:27 +00:00
```diff
class SomeClass
{
public function run($value)
{
- return 1;
+ if ($value) {
+ return 1;
+ }
}
}
```
<br>
### NodeRemovingPostRector
Remove nodes from weird positions
2021-03-12 23:52:38 +00:00
- class: [`Rector\PostRector\Rector\NodeRemovingPostRector`](../packages/PostRector/Rector/NodeRemovingPostRector.php)
2021-03-03 21:28:27 +00:00
```diff
class SomeClass
{
public function run($value)
{
- if ($value) {
- return 1;
- }
+ return 1;
}
}
```
<br>
### NodeToReplacePostRector
Replaces nodes on weird positions
2021-03-12 23:52:38 +00:00
- class: [`Rector\PostRector\Rector\NodeToReplacePostRector`](../packages/PostRector/Rector/NodeToReplacePostRector.php)
2021-03-03 21:28:27 +00:00
```diff
class SomeClass
{
public function run($value)
{
- return 1;
+ return $value;
}
}
```
<br>
### PropertyAddingPostRector
Add dependency properties
2021-03-12 23:52:38 +00:00
- class: [`Rector\PostRector\Rector\PropertyAddingPostRector`](../packages/PostRector/Rector/PropertyAddingPostRector.php)
2021-03-03 21:28:27 +00:00
```diff
class SomeClass
{
+ private $value;
public function run()
{
return $this->value;
}
}
```
<br>
### UseAddingPostRector
Add unique use imports collected during Rector run
2021-03-12 23:52:38 +00:00
- class: [`Rector\PostRector\Rector\UseAddingPostRector`](../packages/PostRector/Rector/UseAddingPostRector.php)
2021-03-03 21:28:27 +00:00
```diff
+use App\AnotherClass;
+
class SomeClass
{
public function run(AnotherClass $anotherClass)
{
}
}
```
<br>
## Privatization
### ChangeGlobalVariablesToPropertiesRector
Change global `$variables` to private properties
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\ClassMethod\ChangeGlobalVariablesToPropertiesRector`](../rules/Privatization/Rector/ClassMethod/ChangeGlobalVariablesToPropertiesRector.php)
```diff
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);
}
}
```
<br>
### ChangeLocalPropertyToVariableRector
Change local property used in single method to local variable
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Class_\ChangeLocalPropertyToVariableRector`](../rules/Privatization/Rector/Class_/ChangeLocalPropertyToVariableRector.php)
```diff
class SomeClass
{
- private $count;
public function run()
{
- $this->count = 5;
- return $this->count;
+ $count = 5;
+ return $count;
}
}
```
<br>
### ChangeReadOnlyPropertyWithDefaultValueToConstantRector
Change property with read only status with default value to constant
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Property\ChangeReadOnlyPropertyWithDefaultValueToConstantRector`](../rules/Privatization/Rector/Property/ChangeReadOnlyPropertyWithDefaultValueToConstantRector.php)
```diff
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;
}
}
}
```
<br>
### ChangeReadOnlyVariableWithDefaultValueToConstantRector
Change variable with read only status with default value to constant
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Class_\ChangeReadOnlyVariableWithDefaultValueToConstantRector`](../rules/Privatization/Rector/Class_/ChangeReadOnlyVariableWithDefaultValueToConstantRector.php)
```diff
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) {
}
}
}
```
<br>
### FinalizeClassesWithoutChildrenRector
Finalize every class that has no children
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Class_\FinalizeClassesWithoutChildrenRector`](../rules/Privatization/Rector/Class_/FinalizeClassesWithoutChildrenRector.php)
```diff
-class FirstClass
+final class FirstClass
{
}
class SecondClass
{
}
-class ThirdClass extends SecondClass
+final class ThirdClass extends SecondClass
{
}
```
<br>
### MakeOnlyUsedByChildrenProtectedRector
Make public class method protected, if only used by its children
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\ClassMethod\MakeOnlyUsedByChildrenProtectedRector`](../rules/Privatization/Rector/ClassMethod/MakeOnlyUsedByChildrenProtectedRector.php)
```diff
abstract class AbstractSomeClass
{
- public function run()
+ protected function run()
{
}
}
class ChildClass extends AbstractSomeClass
{
public function go()
{
$this->run();
}
}
```
<br>
### MakeUnusedClassesWithChildrenAbstractRector
Classes that have no children nor are used, should have abstract
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Class_\MakeUnusedClassesWithChildrenAbstractRector`](../rules/Privatization/Rector/Class_/MakeUnusedClassesWithChildrenAbstractRector.php)
```diff
class SomeClass extends PossibleAbstractClass
{
}
-class PossibleAbstractClass
+abstract class PossibleAbstractClass
{
}
```
<br>
### PrivatizeFinalClassMethodRector
Change protected class method to private if possible
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\ClassMethod\PrivatizeFinalClassMethodRector`](../rules/Privatization/Rector/ClassMethod/PrivatizeFinalClassMethodRector.php)
2019-09-25 08:49:53 +00:00
```diff
final class SomeClass
2019-09-25 08:49:53 +00:00
{
- protected function someMethod()
+ private function someMethod()
{
}
2019-09-25 08:49:53 +00:00
}
```
<br>
2019-09-25 08:49:53 +00:00
### PrivatizeFinalClassPropertyRector
2019-05-29 13:40:20 +00:00
Change property to private if possible
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector`](../rules/Privatization/Rector/Property/PrivatizeFinalClassPropertyRector.php)
2019-05-29 13:40:20 +00:00
```diff
final class SomeClass
{
- protected $value;
+ private $value;
}
```
<br>
2019-05-29 13:40:20 +00:00
### PrivatizeLocalClassConstantRector
Finalize every class constant that is used only locally
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\ClassConst\PrivatizeLocalClassConstantRector`](../rules/Privatization/Rector/ClassConst/PrivatizeLocalClassConstantRector.php)
2019-05-29 13:40:20 +00:00
```diff
class ClassWithConstantUsedOnlyHere
{
- const LOCAL_ONLY = true;
+ private const LOCAL_ONLY = true;
public function isLocalOnly()
{
return self::LOCAL_ONLY;
}
}
```
2018-10-23 18:58:57 +00:00
<br>
### PrivatizeLocalGetterToPropertyRector
2018-05-04 22:30:32 +00:00
Privatize getter of local property to property
2018-07-31 12:50:39 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\MethodCall\PrivatizeLocalGetterToPropertyRector`](../rules/Privatization/Rector/MethodCall/PrivatizeLocalGetterToPropertyRector.php)
```diff
class SomeClass
{
private $some;
public function run()
{
- return $this->getSome() + 5;
+ return $this->some + 5;
}
private function getSome()
{
return $this->some;
}
}
```
<br>
### PrivatizeLocalOnlyMethodRector
Privatize local-only use methods
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\ClassMethod\PrivatizeLocalOnlyMethodRector`](../rules/Privatization/Rector/ClassMethod/PrivatizeLocalOnlyMethodRector.php)
```diff
class SomeClass
{
/**
* @api
*/
public function run()
{
return $this->useMe();
}
2021-01-30 20:30:37 +00:00
- public function useMe()
+ private function useMe()
{
}
}
```
<br>
### PrivatizeLocalPropertyToPrivatePropertyRector
Privatize local-only property to private property
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Property\PrivatizeLocalPropertyToPrivatePropertyRector`](../rules/Privatization/Rector/Property/PrivatizeLocalPropertyToPrivatePropertyRector.php)
2021-01-30 20:30:37 +00:00
```diff
class SomeClass
{
- public $value;
+ private $value;
public function run()
{
return $this->value;
}
}
```
<br>
### RepeatedLiteralToClassConstantRector
Replace repeated strings with constant
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\Class_\RepeatedLiteralToClassConstantRector`](../rules/Privatization/Rector/Class_/RepeatedLiteralToClassConstantRector.php)
2021-01-30 20:30:37 +00:00
```diff
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];
}
}
}
```
<br>
### ReplaceStringWithClassConstantRector
Replace string values in specific method call by constant of provided class
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Privatization\Rector\MethodCall\ReplaceStringWithClassConstantRector`](../rules/Privatization/Rector/MethodCall/ReplaceStringWithClassConstantRector.php)
2021-01-30 20:30:37 +00:00
```php
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', 'Placeholder', 0),
]),
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $this->call('name');
+ $this->call(Placeholder::NAME);
}
}
```
<br>
## Removing
### ArgumentRemoverRector
Removes defined arguments in defined methods and their calls.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Removing\Rector\ClassMethod\ArgumentRemoverRector`](../rules/Removing/Rector/ClassMethod/ArgumentRemoverRector.php)
2021-01-30 20:30:37 +00:00
```php
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'),
]),
]]);
};
```
```diff
$someObject = new SomeClass;
-$someObject->someMethod(true);
+$someObject->someMethod();'
```
<br>
### RemoveFuncCallArgRector
Remove argument by position by function name
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Removing\Rector\FuncCall\RemoveFuncCallArgRector`](../rules/Removing/Rector/FuncCall/RemoveFuncCallArgRector.php)
2021-01-30 20:30:37 +00:00
```php
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),
]),
]]);
};
```
```diff
-remove_last_arg(1, 2);
+remove_last_arg(1);
```
<br>
### RemoveFuncCallRector
Remove `ini_get` by configuration
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Removing\Rector\FuncCall\RemoveFuncCallRector`](../rules/Removing/Rector/FuncCall/RemoveFuncCallRector.php)
2021-01-30 20:30:37 +00:00
```php
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']]), ]
),
]]);
};
```
```diff
-ini_get('y2k_compliance');
ini_get('keep_me');
```
<br>
2021-01-30 20:30:37 +00:00
### RemoveInterfacesRector
2021-01-30 20:30:37 +00:00
Removes interfaces usage from class.
2021-01-30 20:30:37 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Removing\Rector\Class_\RemoveInterfacesRector`](../rules/Removing/Rector/Class_/RemoveInterfacesRector.php)
2021-01-30 20:30:37 +00:00
```php
use Rector\Removing\Rector\Class_\RemoveInterfacesRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2021-01-30 20:30:37 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2021-01-30 20:30:37 +00:00
$services->set(RemoveInterfacesRector::class)
->call('configure', [[
RemoveInterfacesRector::INTERFACES_TO_REMOVE => ['SomeInterface'],
]]);
};
```
2021-01-30 20:30:37 +00:00
```diff
2021-01-30 20:30:37 +00:00
-class SomeClass implements SomeInterface
+class SomeClass
{
}
```
<br>
2021-01-30 20:30:37 +00:00
### RemoveParentRector
2021-01-30 20:30:37 +00:00
Removes extends class by name
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Removing\Rector\Class_\RemoveParentRector`](../rules/Removing/Rector/Class_/RemoveParentRector.php)
```php
2021-01-30 20:30:37 +00:00
use Rector\Removing\Rector\Class_\RemoveParentRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2021-01-30 20:30:37 +00:00
$services->set(RemoveParentRector::class)
->call('configure', [[
2021-01-30 20:30:37 +00:00
RemoveParentRector::PARENT_TYPES_TO_REMOVE => ['SomeParentClass'],
]]);
};
```
```diff
2021-01-30 20:30:37 +00:00
-final class SomeClass extends SomeParentClass
+final class SomeClass
{
}
```
<br>
2021-01-30 20:30:37 +00:00
### RemoveTraitRector
2021-01-30 20:30:37 +00:00
Remove specific traits from code
2021-01-30 20:30:37 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Removing\Rector\Class_\RemoveTraitRector`](../rules/Removing/Rector/Class_/RemoveTraitRector.php)
2021-01-30 20:30:37 +00:00
```php
use Rector\Removing\Rector\Class_\RemoveTraitRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2021-01-30 20:30:37 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveTraitRector::class)
->call('configure', [[
RemoveTraitRector::TRAITS_TO_REMOVE => ['TraitNameToRemove'],
]]);
};
```
```diff
class SomeClass
{
- use SomeTrait;
}
```
<br>
## RemovingStatic
### DesiredClassTypeToDynamicRector
Change full static service, to dynamic one
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\Class_\DesiredClassTypeToDynamicRector`](../rules/RemovingStatic/Rector/Class_/DesiredClassTypeToDynamicRector.php)
```diff
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()
{
}
}
```
<br>
### DesiredPropertyClassMethodTypeToDynamicRector
Change defined static properties and methods to dynamic
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\Property\DesiredPropertyClassMethodTypeToDynamicRector`](../rules/RemovingStatic/Rector/Property/DesiredPropertyClassMethodTypeToDynamicRector.php)
```diff
final class SomeClass
{
- public static $name;
+ public $name;
- public static function go()
+ public function go()
{
}
}
```
<br>
### DesiredStaticCallTypeToDynamicRector
Change defined static service to dynamic one
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\StaticCall\DesiredStaticCallTypeToDynamicRector`](../rules/RemovingStatic/Rector/StaticCall/DesiredStaticCallTypeToDynamicRector.php)
```diff
final class SomeClass
{
public function run()
{
- SomeStaticMethod::someStatic();
+ $this->someStaticMethod::someStatic();
}
}
```
<br>
### DesiredStaticPropertyFetchTypeToDynamicRector
Change defined static service to dynamic one
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\StaticPropertyFetch\DesiredStaticPropertyFetchTypeToDynamicRector`](../rules/RemovingStatic/Rector/StaticPropertyFetch/DesiredStaticPropertyFetchTypeToDynamicRector.php)
```diff
final class SomeClass
{
public function run()
{
- SomeStaticMethod::$someStatic;
+ $this->someStaticMethod::$someStatic;
}
}
```
<br>
### LocallyCalledStaticMethodToNonStaticRector
Change static method and local-only calls to non-static
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\ClassMethod\LocallyCalledStaticMethodToNonStaticRector`](../rules/RemovingStatic/Rector/ClassMethod/LocallyCalledStaticMethodToNonStaticRector.php)
```diff
class SomeClass
{
public function run()
{
- self::someStatic();
+ $this->someStatic();
}
- private static function someStatic()
+ private function someStatic()
{
}
}
2018-05-04 22:30:32 +00:00
```
<br>
### NewUniqueObjectToEntityFactoryRector
Convert new X to new factories
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\Class_\NewUniqueObjectToEntityFactoryRector`](../rules/RemovingStatic/Rector/Class_/NewUniqueObjectToEntityFactoryRector.php)
```php
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'],
]]);
};
```
2019-05-29 13:40:20 +00:00
```diff
-<?php
-
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();
}
}
```
<br>
### PHPUnitStaticToKernelTestCaseGetRector
Convert static calls in PHPUnit test cases, to `get()` from the container of KernelTestCase
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\Class_\PHPUnitStaticToKernelTestCaseGetRector`](../rules/RemovingStatic/Rector/Class_/PHPUnitStaticToKernelTestCaseGetRector.php)
2019-05-29 13:40:20 +00:00
```php
use Rector\RemovingStatic\Rector\Class_\PHPUnitStaticToKernelTestCaseGetRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-05-29 13:40:20 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-29 13:40:20 +00:00
$services->set(PHPUnitStaticToKernelTestCaseGetRector::class)
->call('configure', [[
PHPUnitStaticToKernelTestCaseGetRector::STATIC_CLASS_TYPES => ['EntityFactory'],
]]);
};
```
2019-05-29 13:40:20 +00:00
2019-05-29 13:40:20 +00:00
```diff
-<?php
+use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
-use PHPUnit\Framework\TestCase;
+final class SomeTestCase extends KernelTestCase
+{
+ /**
+ * @var EntityFactory
+ */
+ private $entityFactory;
-final class SomeTestCase extends TestCase
-{
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->entityFactory = $this->getService(EntityFactory::class);
+ }
+
public function test()
{
- $product = EntityFactory::create('product');
+ $product = $this->entityFactory->create('product');
}
}
```
<br>
### PassFactoryToUniqueObjectRector
Convert new `X/Static::call()` to factories in entities, pass them via constructor to each other
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\Class_\PassFactoryToUniqueObjectRector`](../rules/RemovingStatic/Rector/Class_/PassFactoryToUniqueObjectRector.php)
```php
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'],
]]);
};
```
```diff
-<?php
-
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);
}
}
```
<br>
### StaticTypeToSetterInjectionRector
Changes types to setter injection
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\RemovingStatic\Rector\Class_\StaticTypeToSetterInjectionRector`](../rules/RemovingStatic/Rector/Class_/StaticTypeToSetterInjectionRector.php)
```php
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'],
]]);
};
```
```diff
<?php
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();
}
}
```
<br>
## Renaming
### PseudoNamespaceToNamespaceRector
Replaces defined Pseudo_Namespaces by Namespace\Ones.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\FileWithoutNamespace\PseudoNamespaceToNamespaceRector`](../rules/Renaming/Rector/FileWithoutNamespace/PseudoNamespaceToNamespaceRector.php)
```php
use Rector\Renaming\Rector\FileWithoutNamespace\PseudoNamespaceToNamespaceRector;
2021-01-30 20:30:37 +00:00
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']), ]
),
]]);
};
```
```diff
-/** @var Some_Chicken $someService */
-$someService = new Some_Chicken;
+/** @var Some\Chicken $someService */
+$someService = new Some\Chicken;
$someClassToKeep = new Some_Class_To_Keep;
```
<br>
### RenameAnnotationRector
Turns defined annotations above properties and methods to their new values.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\ClassMethod\RenameAnnotationRector`](../rules/Renaming/Rector/ClassMethod/RenameAnnotationRector.php)
```php
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 {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(RenameAnnotationRector::class)
->call('configure', [[
RenameAnnotationRector::RENAMED_ANNOTATIONS_IN_TYPES => ValueObjectInliner::inline([
new RenameAnnotation('PHPUnit\Framework\TestCase', 'test', 'scenario'),
]),
]]);
};
```
```diff
class SomeTest extends PHPUnit\Framework\TestCase
{
/**
- * @test
+ * @scenario
*/
public function someMethod()
{
}
}
```
<br>
2019-08-05 21:10:47 +00:00
### RenameClassConstFetchRector
Replaces defined class constants in their calls.
2019-08-05 21:10:47 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\ClassConstFetch\RenameClassConstFetchRector`](../rules/Renaming/Rector/ClassConstFetch/RenameClassConstFetchRector.php)
```php
use Rector\Renaming\Rector\ClassConstFetch\RenameClassConstFetchRector;
use Rector\Renaming\ValueObject\RenameClassAndConstFetch;
use Rector\Renaming\ValueObject\RenameClassConstFetch;
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 RenameClassConstFetch('SomeClass', 'OLD_CONSTANT', 'NEW_CONSTANT'),
new RenameClassAndConstFetch('SomeClass', 'OTHER_OLD_CONSTANT', 'NEW_CONSTANT', 'DifferentClass'),
]),
]]);
};
```
```diff
-$value = SomeClass::OLD_CONSTANT;
-$value = SomeClass::OTHER_OLD_CONSTANT;
+$value = SomeClass::NEW_CONSTANT;
+$value = DifferentClass::NEW_CONSTANT;
```
2019-08-05 21:10:47 +00:00
<br>
### RenameClassRector
Replaces defined classes by new ones.
2019-08-05 21:10:47 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\Name\RenameClassRector`](../rules/Renaming/Rector/Name/RenameClassRector.php)
2019-08-05 21:10:47 +00:00
```php
use Rector\Renaming\Rector\Name\RenameClassRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-08-05 21:10:47 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameClassRector::class)
->call('configure', [[
RenameClassRector::OLD_TO_NEW_CLASSES => [
'App\SomeOldClass' => 'App\SomeNewClass',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
namespace App;
2019-09-21 22:14:49 +00:00
-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;
}
}
```
<br>
### RenameConstantRector
Replace constant by new ones
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\ConstFetch\RenameConstantRector`](../rules/Renaming/Rector/ConstFetch/RenameConstantRector.php)
```php
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 => [
2021-03-12 23:52:38 +00:00
'MYSQL_ASSOC' => 'MYSQLI_ASSOC', 'OLD_CONSTANT' => 'NEW_CONSTANT',
], ]]);
};
```
```diff
final class SomeClass
{
public function run()
{
- return MYSQL_ASSOC;
+ return MYSQLI_ASSOC;
}
}
```
<br>
### RenameFunctionRector
Turns defined function call new one.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\FuncCall\RenameFunctionRector`](../rules/Renaming/Rector/FuncCall/RenameFunctionRector.php)
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
-view("...", []);
+Laravel\Templating\render("...", []);
```
<br>
### RenameMethodRector
Turns method names to new ones.
:wrench: **configure it!**
2018-09-28 16:33:35 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\MethodCall\RenameMethodRector`](../rules/Renaming/Rector/MethodCall/RenameMethodRector.php)
2018-09-28 16:33:35 +00:00
```php
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'),
]),
]]);
};
```
2018-09-28 16:33:35 +00:00
```diff
$someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();
2018-09-28 16:33:35 +00:00
```
<br>
### RenameNamespaceRector
2019-08-17 13:06:02 +00:00
Replaces old namespace by new one.
2019-08-17 13:06:02 +00:00
:wrench: **configure it!**
2019-08-17 13:06:02 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\Namespace_\RenameNamespaceRector`](../rules/Renaming/Rector/Namespace_/RenameNamespaceRector.php)
2019-08-17 13:06:02 +00:00
```php
use Rector\Renaming\Rector\Namespace_\RenameNamespaceRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-08-17 13:06:02 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-08-17 13:06:02 +00:00
$services->set(RenameNamespaceRector::class)
->call('configure', [[
RenameNamespaceRector::OLD_TO_NEW_NAMESPACES => [
'SomeOldNamespace' => 'SomeNewNamespace',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
2019-08-17 13:06:02 +00:00
2019-08-17 13:06:02 +00:00
```diff
-$someObject = new SomeOldNamespace\SomeClass;
+$someObject = new SomeNewNamespace\SomeClass;
```
<br>
### RenamePropertyRector
Replaces defined old properties by new ones.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\PropertyFetch\RenamePropertyRector`](../rules/Renaming/Rector/PropertyFetch/RenamePropertyRector.php)
2019-08-17 13:06:02 +00:00
```php
use Rector\Renaming\Rector\PropertyFetch\RenamePropertyRector;
use Rector\Renaming\ValueObject\RenameProperty;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
2019-08-17 13:06:02 +00:00
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'),
]),
]]);
};
```
```diff
-$someObject->someOldProperty;
+$someObject->someNewProperty;
```
<br>
### RenameStaticMethodRector
Turns method names to new ones.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector`](../rules/Renaming/Rector/StaticCall/RenameStaticMethodRector.php)
```php
use Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector;
use Rector\Renaming\ValueObject\RenameStaticMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
2019-05-19 08:27:38 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-19 08:27:38 +00:00
$services->set(RenameStaticMethodRector::class)
->call('configure', [[
RenameStaticMethodRector::OLD_TO_NEW_METHODS_BY_CLASSES => ValueObjectInliner::inline([
new RenameStaticMethod('SomeClass', 'oldMethod', 'AnotherExampleClass', 'newStaticMethod'),
]),
]]);
};
```
2019-05-19 08:27:38 +00:00
```diff
-SomeClass::oldStaticMethod();
+AnotherExampleClass::newStaticMethod();
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
```php
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'),
]),
]]);
};
```
```diff
-SomeClass::oldStaticMethod();
+SomeClass::newStaticMethod();
```
<br>
### RenameStringRector
Change string value
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Renaming\Rector\String_\RenameStringRector`](../rules/Renaming/Rector/String_/RenameStringRector.php)
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
class SomeClass
{
public function run()
{
- return 'ROLE_PREVIOUS_ADMIN';
+ return 'IS_IMPERSONATOR';
}
}
```
<br>
## Restoration
### CompleteImportForPartialAnnotationRector
In case you have accidentally removed use imports but code still contains partial use statements, this will save you
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector`](../rules/Restoration/Rector/Namespace_/CompleteImportForPartialAnnotationRector.php)
```php
use Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector;
use Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
2019-09-25 08:49:53 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-09-25 08:49:53 +00:00
$services->set(CompleteImportForPartialAnnotationRector::class)
->call('configure', [[
CompleteImportForPartialAnnotationRector::USE_IMPORTS_TO_RESTORE => ValueObjectInliner::inline([
new CompleteImportForPartialAnnotation('Doctrine\ORM\Mapping', 'ORM'),
]),
]]);
};
```
2019-09-25 08:49:53 +00:00
```diff
+use Doctrine\ORM\Mapping as ORM;
+
2019-09-25 08:49:53 +00:00
class SomeClass
{
/**
* @ORM\Id
*/
public $id;
2019-09-25 08:49:53 +00:00
}
```
<br>
2019-09-25 08:49:53 +00:00
### CompleteMissingDependencyInNewRector
2020-07-24 11:46:57 +00:00
Complete missing constructor dependency instance by type
2019-12-18 09:53:46 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\New_\CompleteMissingDependencyInNewRector`](../rules/Restoration/Rector/New_/CompleteMissingDependencyInNewRector.php)
```php
use Rector\Restoration\Rector\New_\CompleteMissingDependencyInNewRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(CompleteMissingDependencyInNewRector::class)
->call('configure', [[
CompleteMissingDependencyInNewRector::CLASS_TO_INSTANTIATE_BY_TYPE => [
'RandomDependency' => 'RandomDependency',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
2019-12-18 09:53:46 +00:00
```diff
final class SomeClass
2019-12-18 09:53:46 +00:00
{
public function run()
2019-12-18 09:53:46 +00:00
{
- $valueObject = new RandomValueObject();
+ $valueObject = new RandomValueObject(new RandomDependency());
2019-12-18 09:53:46 +00:00
}
}
2019-09-25 08:49:53 +00:00
class RandomValueObject
2019-09-25 08:49:53 +00:00
{
public function __construct(RandomDependency $randomDependency)
2019-09-25 08:49:53 +00:00
{
2019-05-19 08:27:38 +00:00
}
}
```
<br>
2019-05-19 08:27:38 +00:00
### InferParamFromClassMethodReturnRector
2019-05-19 08:27:38 +00:00
Change `@param` doc based on another method return type
2019-05-19 08:27:38 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\ClassMethod\InferParamFromClassMethodReturnRector`](../rules/Restoration/Rector/ClassMethod/InferParamFromClassMethodReturnRector.php)
```php
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'),
]),
]]);
};
```
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
{
public function getNodeTypes(): array
{
return [String_::class];
}
+ /**
+ * @param String_ $node
+ */
public function process(Node $node)
{
}
}
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
### MakeTypedPropertyNullableIfCheckedRector
2019-08-05 21:10:47 +00:00
Make typed property nullable if checked
2019-08-05 21:10:47 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\Property\MakeTypedPropertyNullableIfCheckedRector`](../rules/Restoration/Rector/Property/MakeTypedPropertyNullableIfCheckedRector.php)
2019-08-05 21:10:47 +00:00
```diff
final class SomeClass
{
- private AnotherClass $anotherClass;
+ private ?AnotherClass $anotherClass = null;
public function run()
{
if ($this->anotherClass === null) {
$this->anotherClass = new AnotherClass;
}
}
}
```
<br>
2019-08-05 21:10:47 +00:00
### MissingClassConstantReferenceToStringRector
2018-05-04 22:30:32 +00:00
Convert missing class reference to string
2018-08-01 20:09:34 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\ClassConstFetch\MissingClassConstantReferenceToStringRector`](../rules/Restoration/Rector/ClassConstFetch/MissingClassConstantReferenceToStringRector.php)
2018-05-04 22:30:32 +00:00
```diff
class SomeClass
{
public function run()
{
- return NonExistingClass::class;
+ return 'NonExistingClass';
}
}
```
<br>
### RemoveFinalFromEntityRector
Remove final from Doctrine entities
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\Class_\RemoveFinalFromEntityRector`](../rules/Restoration/Rector/Class_/RemoveFinalFromEntityRector.php)
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
-final class SomeClass
+class SomeClass
{
}
```
<br>
### RestoreFullyQualifiedNameRector
Restore accidentally shortened class names to its fully qualified form.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\Use_\RestoreFullyQualifiedNameRector`](../rules/Restoration/Rector/Use_/RestoreFullyQualifiedNameRector.php)
```diff
-use ShortClassOnly;
+use App\Whatever\ShortClassOnly;
class AnotherClass
{
}
```
<br>
### UpdateFileNameByClassNameFileSystemRector
2019-12-19 22:07:06 +00:00
Rename file to respect class name
2019-12-19 22:07:06 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Restoration\Rector\ClassLike\UpdateFileNameByClassNameFileSystemRector`](../rules/Restoration/Rector/ClassLike/UpdateFileNameByClassNameFileSystemRector.php)
2019-12-19 22:07:06 +00:00
```diff
-// app/SomeClass.php
+// app/AnotherClass.php
class AnotherClass
{
}
```
2020-07-24 11:46:57 +00:00
<br>
## Symfony
### ActionSuffixRemoverRector
Removes Action suffixes from methods in Symfony Controllers
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony\Rector\ClassMethod\ActionSuffixRemoverRector`](../rules/Symfony/Rector/ClassMethod/ActionSuffixRemoverRector.php)
```diff
class SomeController
{
- public function indexAction()
+ public function index()
{
}
}
```
<br>
2021-03-12 23:52:38 +00:00
### AddMessageToEqualsResponseCodeRector
Add response content to response code assert, so it is easier to debug
- class: [`Rector\Symfony\Rector\StaticCall\AddMessageToEqualsResponseCodeRector`](../rules/Symfony/Rector/StaticCall/AddMessageToEqualsResponseCodeRector.php)
```diff
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
final class SomeClassTest extends TestCase
{
public function test(Response $response)
{
$this->assertEquals(
Response::HTTP_NO_CONTENT,
$response->getStatusCode()
+ $response->getContent()
);
}
}
```
<br>
### ChangeFileLoaderInExtensionAndKernelRector
Change XML loader to YAML in Bundle Extension
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony\Rector\Class_\ChangeFileLoaderInExtensionAndKernelRector`](../rules/Symfony/Rector/Class_/ChangeFileLoaderInExtensionAndKernelRector.php)
```php
use Rector\Symfony\Rector\Class_\ChangeFileLoaderInExtensionAndKernelRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangeFileLoaderInExtensionAndKernelRector::class)
->call('configure', [[
2021-03-12 23:52:38 +00:00
ChangeFileLoaderInExtensionAndKernelRector::FROM => 'xml', ChangeFileLoaderInExtensionAndKernelRector::TO => 'yaml',
]]);
};
```
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
+use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
final class SomeExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
- $loader = new XmlFileLoader($container, new FileLocator());
- $loader->load(__DIR__ . '/../Resources/config/controller.xml');
- $loader->load(__DIR__ . '/../Resources/config/events.xml');
+ $loader = new YamlFileLoader($container, new FileLocator());
+ $loader->load(__DIR__ . '/../Resources/config/controller.yaml');
+ $loader->load(__DIR__ . '/../Resources/config/events.yaml');
}
}
```
<br>
2021-03-12 23:52:38 +00:00
### EventListenerToEventSubscriberRector
Change Symfony Event listener class to Event Subscriber based on configuration in service.yaml file
- class: [`Rector\Symfony\Rector\Class_\EventListenerToEventSubscriberRector`](../rules/Symfony/Rector/Class_/EventListenerToEventSubscriberRector.php)
```diff
-class SomeListener
+use Symfony\Component\EventDispatcher\EventSubscriberInterface;
+
+class SomeEventSubscriber implements EventSubscriberInterface
{
+ /**
+ * @return string[]
+ */
+ public static function getSubscribedEvents(): array
+ {
+ return ['some_event' => 'methodToBeCalled'];
+ }
+
public function methodToBeCalled()
{
}
-}
-
-// in config.yaml
-services:
- SomeListener:
- tags:
- - { name: kernel.event_listener, event: 'some_event', method: 'methodToBeCalled' }
+}
```
<br>
### ExtractAttributeRouteNameConstantsRector
`Extract` #[Route] attribute name argument from string to constant
- class: [`Rector\Symfony\Rector\Attribute\ExtractAttributeRouteNameConstantsRector`](../rules/Symfony/Rector/Attribute/ExtractAttributeRouteNameConstantsRector.php)
```diff
use Symfony\Component\Routing\Annotation\Route;
class SomeClass
{
- #[Route(path: "path", name: "/name")]
+ #[Route(path: "path", name: RouteName::NAME)]
public function run()
{
}
}
```
Extra file:
```php
final class RouteName
{
/**
* @var string
*/
public NAME = 'name';
}
```
<br>
### GetParameterToConstructorInjectionRector
Turns fetching of parameters via `getParameter()` in ContainerAware to constructor injection in Command and Controller in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony\Rector\MethodCall\GetParameterToConstructorInjectionRector`](../rules/Symfony/Rector/MethodCall/GetParameterToConstructorInjectionRector.php)
```diff
-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
{
+ private $someParameter;
+
+ public function __construct($someParameter)
+ {
+ $this->someParameter = $someParameter;
+ }
+
public function someMethod()
{
- $this->getParameter('someParameter');
+ $this->someParameter;
}
}
```
<br>
### GetToConstructorInjectionRector
Turns fetching of dependencies via `$this->get()` to constructor injection in Command and Controller in Symfony
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony\Rector\MethodCall\GetToConstructorInjectionRector`](../rules/Symfony/Rector/MethodCall/GetToConstructorInjectionRector.php)
```php
use Rector\Symfony\Rector\MethodCall\GetToConstructorInjectionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(GetToConstructorInjectionRector::class)
->call('configure', [[
2021-03-12 23:52:38 +00:00
GetToConstructorInjectionRector::GET_METHOD_AWARE_TYPES => ['SymfonyControllerClassName', 'GetTraitClassName'],
]]);
};
```
```diff
-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
{
+ public function __construct(SomeService $someService)
+ {
+ $this->someService = $someService;
+ }
+
public function someMethod()
{
- // ...
- $this->get('some_service');
+ $this->someService;
}
}
2018-05-04 22:30:32 +00:00
```
<br>
### MakeCommandLazyRector
2020-07-24 11:46:57 +00:00
Make Symfony commands lazy
2018-05-05 00:04:41 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony\Rector\Class_\MakeCommandLazyRector`](../rules/Symfony/Rector/Class_/MakeCommandLazyRector.php)
2018-08-01 20:09:34 +00:00
```diff
use Symfony\Component\Console\Command\Command
class SunshineCommand extends Command
{
+ protected static $defaultName = 'sunshine';
public function configure()
{
- $this->setName('sunshine');
}
}
2018-05-05 00:04:41 +00:00
```
<br>
### RemoveServiceFromSensioRouteRector
Remove service from Sensio `@Route`
- class: [`Rector\Symfony\Rector\ClassMethod\RemoveServiceFromSensioRouteRector`](../rules/Symfony/Rector/ClassMethod/RemoveServiceFromSensioRouteRector.php)
```diff
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
final class SomeClass
{
/**
- * @Route(service="some_service")
+ * @Route()
*/
public function run()
{
}
}
```
<br>
### ReplaceSensioRouteAnnotationWithSymfonyRector
Replace Sensio `@Route` annotation with Symfony one
- class: [`Rector\Symfony\Rector\ClassMethod\ReplaceSensioRouteAnnotationWithSymfonyRector`](../rules/Symfony/Rector/ClassMethod/ReplaceSensioRouteAnnotationWithSymfonyRector.php)
```diff
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
+use Symfony\Component\Routing\Annotation\Route;
final class SomeClass
{
/**
* @Route()
*/
public function run()
{
}
}
```
<br>
### ResponseStatusCodeRector
2020-07-24 11:46:57 +00:00
Turns status code numbers to constants
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony\Rector\BinaryOp\ResponseStatusCodeRector`](../rules/Symfony/Rector/BinaryOp/ResponseStatusCodeRector.php)
```diff
class SomeController
{
public function index()
{
$response = new \Symfony\Component\HttpFoundation\Response();
- $response->setStatusCode(200);
+ $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
- if ($response->getStatusCode() === 200) {}
+ if ($response->getStatusCode() === \Symfony\Component\HttpFoundation\Response::HTTP_OK) {}
}
}
```
<br>
2019-05-29 13:40:20 +00:00
### SimpleFunctionAndFilterRector
Changes Twig_Function_Method to Twig_SimpleFunction calls in Twig_Extension.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony\Rector\Return_\SimpleFunctionAndFilterRector`](../rules/Symfony/Rector/Return_/SimpleFunctionAndFilterRector.php)
```diff
class SomeExtension extends Twig_Extension
{
public function getFunctions()
{
return [
- 'is_mobile' => new Twig_Function_Method($this, 'isMobile'),
+ new Twig_SimpleFunction('is_mobile', [$this, 'isMobile']),
];
}
public function getFilters()
{
return [
- 'is_mobile' => new Twig_Filter_Method($this, 'isMobile'),
+ new Twig_SimpleFilter('is_mobile', [$this, 'isMobile']),
];
}
}
```
<br>
### TemplateAnnotationToThisRenderRector
Turns `@Template` annotation to explicit method call in Controller of FrameworkExtraBundle in Symfony
- class: [`Rector\Symfony\Rector\ClassMethod\TemplateAnnotationToThisRenderRector`](../rules/Symfony/Rector/ClassMethod/TemplateAnnotationToThisRenderRector.php)
```diff
-/**
- * @Template()
- */
public function indexAction()
{
+ return $this->render('index.html.twig');
}
```
<br>
## Symfony2
2020-07-24 11:46:57 +00:00
### AddFlashRector
2019-11-06 23:52:19 +00:00
Turns long flash adding to short helper method in Controller in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony2\Rector\MethodCall\AddFlashRector`](../rules/Symfony2/Rector/MethodCall/AddFlashRector.php)
```diff
class SomeController extends Controller
{
public function some(Request $request)
{
- $request->getSession()->getFlashBag()->add("success", "something");
+ $this->addFlash("success", "something");
}
}
```
<br>
### ParseFileRector
session > use_strict_mode is true by default and can be removed
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony2\Rector\StaticCall\ParseFileRector`](../rules/Symfony2/Rector/StaticCall/ParseFileRector.php)
```diff
-session > use_strict_mode: true
+session:
```
<br>
### RedirectToRouteRector
Turns redirect to route to short helper method in Controller in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony2\Rector\MethodCall\RedirectToRouteRector`](../rules/Symfony2/Rector/MethodCall/RedirectToRouteRector.php)
2019-11-06 23:52:19 +00:00
```diff
-$this->redirect($this->generateUrl("homepage"));
+$this->redirectToRoute("homepage");
```
<br>
## Symfony3
### CascadeValidationFormBuilderRector
Change "cascade_validation" option to specific node attribute
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\MethodCall\CascadeValidationFormBuilderRector`](../rules/Symfony3/Rector/MethodCall/CascadeValidationFormBuilderRector.php)
```diff
class SomeController
2019-11-06 23:52:19 +00:00
{
public function someMethod()
2019-11-06 23:52:19 +00:00
{
- $form = $this->createFormBuilder($article, ['cascade_validation' => true])
- ->add('author', new AuthorType())
+ $form = $this->createFormBuilder($article)
+ ->add('author', new AuthorType(), [
+ 'constraints' => new \Symfony\Component\Validator\Constraints\Valid(),
+ ])
->getForm();
}
protected function createFormBuilder()
{
return new FormBuilder();
2019-11-06 23:52:19 +00:00
}
}
```
<br>
2019-11-06 23:52:19 +00:00
### ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector
2020-07-28 15:15:30 +00:00
Rename `type` option to `entry_type` in CollectionType
2020-07-28 15:15:30 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\MethodCall\ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector`](../rules/Symfony3/Rector/MethodCall/ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector.php)
2020-07-28 15:15:30 +00:00
```diff
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tags', CollectionType::class, [
- 'type' => ChoiceType::class,
- 'options' => [1, 2, 3],
+ 'entry_type' => ChoiceType::class,
+ 'entry_options' => [1, 2, 3],
]);
}
2020-07-28 15:15:30 +00:00
}
```
<br>
2020-07-28 15:15:30 +00:00
### ChangeStringCollectionOptionToConstantRector
Change type in CollectionType from alias string to class reference
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\MethodCall\ChangeStringCollectionOptionToConstantRector`](../rules/Symfony3/Rector/MethodCall/ChangeStringCollectionOptionToConstantRector.php)
```diff
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tags', CollectionType::class, [
- 'type' => 'choice',
+ 'type' => \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class,
]);
$builder->add('tags', 'collection', [
- 'type' => 'choice',
+ 'type' => \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class,
]);
}
}
```
<br>
### ConsoleExceptionToErrorEventConstantRector
Turns old event name with EXCEPTION to ERROR constant in Console in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\ClassConstFetch\ConsoleExceptionToErrorEventConstantRector`](../rules/Symfony3/Rector/ClassConstFetch/ConsoleExceptionToErrorEventConstantRector.php)
```diff
-"console.exception"
+Symfony\Component\Console\ConsoleEvents::ERROR
```
<br>
```diff
-Symfony\Component\Console\ConsoleEvents::EXCEPTION
+Symfony\Component\Console\ConsoleEvents::ERROR
```
<br>
### FormTypeGetParentRector
2020-07-24 11:46:57 +00:00
Turns string Form Type references to their `CONSTANT` alternatives in `getParent()` and `getExtendedType()` methods in Form in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\ClassMethod\FormTypeGetParentRector`](../rules/Symfony3/Rector/ClassMethod/FormTypeGetParentRector.php)
```diff
use Symfony\Component\Form\AbstractType;
class SomeType extends AbstractType
2019-05-29 13:40:20 +00:00
{
public function getParent()
{
- return 'collection';
+ return \Symfony\Component\Form\Extension\Core\Type\CollectionType::class;
}
2019-05-29 13:40:20 +00:00
}
```
<br>
```diff
use Symfony\Component\Form\AbstractTypeExtension;
2018-07-31 12:50:39 +00:00
class SomeExtension extends AbstractTypeExtension
{
public function getExtendedType()
{
- return 'collection';
+ return \Symfony\Component\Form\Extension\Core\Type\CollectionType::class;
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
### FormTypeInstanceToClassConstRector
2018-05-04 22:30:32 +00:00
Changes createForm(new FormType), add(new FormType) to ones with "FormType::class"
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\MethodCall\FormTypeInstanceToClassConstRector`](../rules/Symfony3/Rector/MethodCall/FormTypeInstanceToClassConstRector.php)
2018-08-01 20:09:34 +00:00
```diff
class SomeController
{
public function action()
{
- $form = $this->createForm(new TeamType, $entity);
+ $form = $this->createForm(TeamType::class, $entity);
}
}
```
<br>
2019-05-29 13:40:20 +00:00
### GetRequestRector
2019-05-29 13:40:20 +00:00
Turns fetching of dependencies via `$this->get()` to constructor injection in Command and Controller in Symfony
2019-05-29 13:40:20 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\ClassMethod\GetRequestRector`](../rules/Symfony3/Rector/ClassMethod/GetRequestRector.php)
2019-05-29 13:40:20 +00:00
```diff
+use Symfony\Component\HttpFoundation\Request;
+
class SomeController
{
- public function someAction()
+ public function someAction(Request $request)
{
- $this->getRequest()->...();
+ $request->...();
}
}
```
2020-07-24 11:46:57 +00:00
<br>
### MergeMethodAnnotationToRouteAnnotationRector
Merge removed `@Method` annotation to `@Route` one
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\ClassMethod\MergeMethodAnnotationToRouteAnnotationRector`](../rules/Symfony3/Rector/ClassMethod/MergeMethodAnnotationToRouteAnnotationRector.php)
```diff
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends Controller
{
/**
- * @Route("/show/{id}")
- * @Method({"GET", "HEAD"})
+ * @Route("/show/{id}", methods={"GET","HEAD"})
*/
public function show($id)
{
}
}
```
<br>
### OptionNameRector
Turns old option names to new ones in FormTypes in Form in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\MethodCall\OptionNameRector`](../rules/Symfony3/Rector/MethodCall/OptionNameRector.php)
```diff
$builder = new FormBuilder;
-$builder->add("...", ["precision" => "...", "virtual" => "..."];
+$builder->add("...", ["scale" => "...", "inherit_data" => "..."];
```
<br>
### ReadOnlyOptionToAttributeRector
Change "read_only" option in form to attribute
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\MethodCall\ReadOnlyOptionToAttributeRector`](../rules/Symfony3/Rector/MethodCall/ReadOnlyOptionToAttributeRector.php)
```diff
use Symfony\Component\Form\FormBuilderInterface;
function buildForm(FormBuilderInterface $builder, array $options)
{
- $builder->add('cuid', TextType::class, ['read_only' => true]);
+ $builder->add('cuid', TextType::class, ['attr' => ['read_only' => true]]);
}
```
<br>
### RemoveDefaultGetBlockPrefixRector
Rename `getBlockPrefix()` if it returns the default value - class to underscore, e.g. UserFormType = user_form
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\ClassMethod\RemoveDefaultGetBlockPrefixRector`](../rules/Symfony3/Rector/ClassMethod/RemoveDefaultGetBlockPrefixRector.php)
```diff
use Symfony\Component\Form\AbstractType;
class TaskType extends AbstractType
{
- public function getBlockPrefix()
- {
- return 'task';
- }
}
```
<br>
### StringFormTypeToClassRector
Turns string Form Type references to their `CONSTANT` alternatives in FormTypes in Form in Symfony. To enable custom types, add `link` to your container XML `dump` in "$parameters->set(Option::SYMFONY_CONTAINER_XML_PATH_PARAMETER, ...);"
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony3\Rector\MethodCall\StringFormTypeToClassRector`](../rules/Symfony3/Rector/MethodCall/StringFormTypeToClassRector.php)
```diff
$formBuilder = new Symfony\Component\Form\FormBuilder;
-$formBuilder->add('name', 'form.type.text');
+$formBuilder->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class);
```
<br>
## Symfony4
### ConsoleExecuteReturnIntRector
Returns int from Command::execute command
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\ClassMethod\ConsoleExecuteReturnIntRector`](../rules/Symfony4/Rector/ClassMethod/ConsoleExecuteReturnIntRector.php)
```diff
class SomeCommand extends Command
{
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
{
- return null;
+ return 0;
}
}
```
<br>
### ConstraintUrlOptionRector
Turns true value to `Url::CHECK_DNS_TYPE_ANY` in Validator in Symfony.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\ConstFetch\ConstraintUrlOptionRector`](../rules/Symfony4/Rector/ConstFetch/ConstraintUrlOptionRector.php)
```diff
-$constraint = new Url(["checkDNS" => true]);
+$constraint = new Url(["checkDNS" => Url::CHECK_DNS_TYPE_ANY]);
```
<br>
### ContainerBuilderCompileEnvArgumentRector
Turns old default value to parameter in `ContainerBuilder->build()` method in DI in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\MethodCall\ContainerBuilderCompileEnvArgumentRector`](../rules/Symfony4/Rector/MethodCall/ContainerBuilderCompileEnvArgumentRector.php)
2018-09-28 16:33:35 +00:00
```diff
use Symfony\Component\DependencyInjection\ContainerBuilder;
$containerBuilder = new ContainerBuilder();
-$containerBuilder->compile();
+$containerBuilder->compile(true);
2018-09-28 16:33:35 +00:00
```
<br>
### ContainerGetToConstructorInjectionRector
Turns fetching of dependencies via `$container->get()` in ContainerAware to constructor injection in Command and Controller in Symfony
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\MethodCall\ContainerGetToConstructorInjectionRector`](../rules/Symfony4/Rector/MethodCall/ContainerGetToConstructorInjectionRector.php)
```php
use Rector\Symfony4\Rector\MethodCall\ContainerGetToConstructorInjectionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ContainerGetToConstructorInjectionRector::class)
->call('configure', [[
ContainerGetToConstructorInjectionRector::CONTAINER_AWARE_PARENT_TYPES => [
'ContainerAwareParentClassName',
'ContainerAwareParentCommandClassName',
'ThisClassCallsMethodInConstructorClassName',
],
]]);
};
```
```diff
-final class SomeCommand extends ContainerAwareCommand
+final class SomeCommand extends Command
{
+ public function __construct(SomeService $someService)
+ {
+ $this->someService = $someService;
+ }
+
public function someMethod()
{
// ...
- $this->getContainer()->get('some_service');
- $this->container->get('some_service');
+ $this->someService;
+ $this->someService;
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
### FormIsValidRector
Adds `$form->isSubmitted()` validation to all `$form->isValid()` calls in Form in Symfony
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\MethodCall\FormIsValidRector`](../rules/Symfony4/Rector/MethodCall/FormIsValidRector.php)
```diff
-if ($form->isValid()) {
+if ($form->isSubmitted() && $form->isValid()) {
}
```
<br>
### MakeDispatchFirstArgumentEventRector
Make event object a first argument of `dispatch()` method, event name as second
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\MethodCall\MakeDispatchFirstArgumentEventRector`](../rules/Symfony4/Rector/MethodCall/MakeDispatchFirstArgumentEventRector.php)
```diff
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class SomeClass
{
public function run(EventDispatcherInterface $eventDispatcher)
{
- $eventDispatcher->dispatch('event_name', new Event());
+ $eventDispatcher->dispatch(new Event(), 'event_name');
}
}
```
<br>
### ProcessBuilderGetProcessRector
2020-07-24 11:46:57 +00:00
Removes `$processBuilder->getProcess()` calls to `$processBuilder` in Process in Symfony, because ProcessBuilder was removed. This is part of multi-step Rector and has very narrow focus.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\MethodCall\ProcessBuilderGetProcessRector`](../rules/Symfony4/Rector/MethodCall/ProcessBuilderGetProcessRector.php)
```diff
$processBuilder = new Symfony\Component\Process\ProcessBuilder;
-$process = $processBuilder->getProcess();
-$commamdLine = $processBuilder->getProcess()->getCommandLine();
+$process = $processBuilder;
+$commamdLine = $processBuilder->getCommandLine();
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
### ProcessBuilderInstanceRector
2020-07-24 11:46:57 +00:00
Turns `ProcessBuilder::instance()` to new ProcessBuilder in Process in Symfony. Part of multi-step Rector.
2020-05-31 15:26:08 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\StaticCall\ProcessBuilderInstanceRector`](../rules/Symfony4/Rector/StaticCall/ProcessBuilderInstanceRector.php)
2020-05-31 15:26:08 +00:00
```diff
-$processBuilder = Symfony\Component\Process\ProcessBuilder::instance($args);
+$processBuilder = new Symfony\Component\Process\ProcessBuilder($args);
2020-05-31 15:26:08 +00:00
```
<br>
2020-05-31 15:26:08 +00:00
### RootNodeTreeBuilderRector
Changes Process string argument to an array
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\New_\RootNodeTreeBuilderRector`](../rules/Symfony4/Rector/New_/RootNodeTreeBuilderRector.php)
```diff
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
-$treeBuilder = new TreeBuilder();
-$rootNode = $treeBuilder->root('acme_root');
+$treeBuilder = new TreeBuilder('acme_root');
+$rootNode = $treeBuilder->getRootNode();
$rootNode->someCall();
```
<br>
### SimplifyWebTestCaseAssertionsRector
2020-07-24 11:46:57 +00:00
Simplify use of assertions in WebTestCase
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\MethodCall\SimplifyWebTestCaseAssertionsRector`](../rules/Symfony4/Rector/MethodCall/SimplifyWebTestCaseAssertionsRector.php)
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
public function test()
{
- $this->assertSame(200, $client->getResponse()->getStatusCode());
+ $this->assertResponseIsSuccessful();
}
public function testUrl()
{
- $this->assertSame(301, $client->getResponse()->getStatusCode());
- $this->assertSame('https://example.com', $client->getResponse()->headers->get('Location'));
+ $this->assertResponseRedirects('https://example.com', 301);
}
2020-07-29 23:39:41 +00:00
public function testContains()
{
- $this->assertContains('Hello World', $crawler->filter('h1')->text());
+ $this->assertSelectorTextContains('h1', 'Hello World');
}
}
```
<br>
2020-07-29 23:39:41 +00:00
### StringToArrayArgumentProcessRector
Changes Process string argument to an array
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\New_\StringToArrayArgumentProcessRector`](../rules/Symfony4/Rector/New_/StringToArrayArgumentProcessRector.php)
```diff
use Symfony\Component\Process\Process;
-$process = new Process('ls -l');
+$process = new Process(['ls', '-l']);
```
<br>
### VarDumperTestTraitMethodArgsRector
Adds a new `$filter` argument in `VarDumperTestTrait->assertDumpEquals()` and `VarDumperTestTrait->assertDumpMatchesFormat()` in Validator in Symfony.
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony4\Rector\MethodCall\VarDumperTestTraitMethodArgsRector`](../rules/Symfony4/Rector/MethodCall/VarDumperTestTraitMethodArgsRector.php)
```diff
-$varDumperTestTrait->assertDumpEquals($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpEquals($dump, $data, $filter = 0, $message = "");
```
<br>
```diff
-$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $filter = 0, $message = "");
```
<br>
## Symfony5
### BinaryFileResponseCreateToNewInstanceRector
Change deprecated `BinaryFileResponse::create()` to use `__construct()` instead
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\StaticCall\BinaryFileResponseCreateToNewInstanceRector`](../rules/Symfony5/Rector/StaticCall/BinaryFileResponseCreateToNewInstanceRector.php)
```diff
use Symfony\Component\HttpFoundation;
class SomeClass
{
public function run()
{
- $binaryFile = BinaryFileResponse::create();
+ $binaryFile = new BinaryFileResponse(null);
}
}
```
<br>
### DefinitionAliasSetPrivateToSetPublicRector
Migrates from deprecated `Definition/Alias->setPrivate()` to `Definition/Alias->setPublic()`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\MethodCall\DefinitionAliasSetPrivateToSetPublicRector`](../rules/Symfony5/Rector/MethodCall/DefinitionAliasSetPrivateToSetPublicRector.php)
```diff
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Definition;
class SomeClass
{
public function run()
{
$definition = new Definition('Example\Foo');
- $definition->setPrivate(false);
+ $definition->setPublic(true);
$alias = new Alias('Example\Foo');
- $alias->setPrivate(false);
+ $alias->setPublic(true);
}
}
```
<br>
### FormBuilderSetDataMapperRector
Migrates from deprecated Form Builder->setDataMapper(new `PropertyPathMapper())` to Builder->setDataMapper(new DataMapper(new `PropertyPathAccessor()))`
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\MethodCall\FormBuilderSetDataMapperRector`](../rules/Symfony5/Rector/MethodCall/FormBuilderSetDataMapperRector.php)
```diff
use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper;
use Symfony\Component\Form\FormConfigBuilderInterface;
2021-03-12 23:52:38 +00:00
+use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper;
+use Symfony\Component\Form\Extension\Core\DataAccessor\PropertyPathAccessor;
class SomeClass
{
public function run(FormConfigBuilderInterface $builder)
{
- $builder->setDataMapper(new PropertyPathMapper());
2021-03-12 23:52:38 +00:00
+ $builder->setDataMapper(new DataMapper(new PropertyPathAccessor()));
}
}
```
<br>
### LogoutHandlerToLogoutEventSubscriberRector
2021-01-30 20:30:37 +00:00
Change logout handler to an event listener that listens to LogoutEvent
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\Class_\LogoutHandlerToLogoutEventSubscriberRector`](../rules/Symfony5/Rector/Class_/LogoutHandlerToLogoutEventSubscriberRector.php)
```diff
-use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
-use Symfony\Component\HttpFoundation\Request;
-use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
+use Symfony\Component\EventDispatcher\EventSubscriberInterface;
+use Symfony\Component\Security\Http\Event\LogoutEvent;
-final class SomeLogoutHandler implements LogoutHandlerInterface
+final class SomeLogoutHandler implements EventSubscriberInterface
{
- public function logout(Request $request, Response $response, TokenInterface $token)
+ public function onLogout(LogoutEvent $logoutEvent): void
{
+ $request = $logoutEvent->getRequest();
+ $response = $logoutEvent->getResponse();
+ $token = $logoutEvent->getToken();
+ }
+
+ /**
+ * @return array<string, string[]>
+ */
+ public static function getSubscribedEvents(): array
+ {
+ return [
+ LogoutEvent::class => ['onLogout'],
+ ];
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### LogoutSuccessHandlerToLogoutEventSubscriberRector
Change logout success handler to an event listener that listens to LogoutEvent
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\Class_\LogoutSuccessHandlerToLogoutEventSubscriberRector`](../rules/Symfony5/Rector/Class_/LogoutSuccessHandlerToLogoutEventSubscriberRector.php)
2021-01-30 20:30:37 +00:00
```diff
-use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
-use Symfony\Component\HttpFoundation\Request;
-use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
+use Symfony\Component\EventDispatcher\EventSubscriberInterface;
+use Symfony\Component\Security\Http\Event\LogoutEvent;
-final class SomeLogoutHandler implements LogoutSuccessHandlerInterface
+final class SomeLogoutHandler implements EventSubscriberInterface
{
/**
* @var HttpUtils
*/
private $httpUtils;
- public function __construct(HttpUtils $httpUtils)
+ public function onLogout(LogoutEvent $logoutEvent): void
{
- $this->httpUtils = $httpUtils;
+ if ($logoutEvent->getResponse() !== null) {
+ return;
+ }
+
+ $response = $this->httpUtils->createRedirectResponse($logoutEvent->getRequest(), 'some_url');
+ $logoutEvent->setResponse($response);
}
- public function onLogoutSuccess(Request $request)
+ /**
+ * @return array<string, mixed>
+ */
+ public static function getSubscribedEvents(): array
{
- $response = $this->httpUtils->createRedirectResponse($request, 'some_url');
- return $response;
+ return [
+ LogoutEvent::class => [['onLogout', 64]],
+ ];
}
}
```
<br>
### PropertyAccessorCreationBooleanToFlagsRector
Changes first argument of `PropertyAccessor::__construct()` to flags from boolean
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\New_\PropertyAccessorCreationBooleanToFlagsRector`](../rules/Symfony5/Rector/New_/PropertyAccessorCreationBooleanToFlagsRector.php)
```diff
class SomeClass
{
public function run()
{
- $propertyAccessor = new PropertyAccessor(true);
+ $propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_CALL | PropertyAccessor::MAGIC_GET | PropertyAccessor::MAGIC_SET);
}
}
```
<br>
### PropertyPathMapperToDataMapperRector
Migrate from PropertyPathMapper to DataMapper and PropertyPathAccessor
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\New_\PropertyPathMapperToDataMapperRector`](../rules/Symfony5/Rector/New_/PropertyPathMapperToDataMapperRector.php)
```diff
use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper;
class SomeClass
{
public function run()
{
- return new PropertyPathMapper();
+ return new \Symfony\Component\Form\Extension\Core\DataMapper\DataMapper(new \Symfony\Component\Form\Extension\Core\DataAccessor\PropertyPathAccessor());
}
}
```
<br>
### ReflectionExtractorEnableMagicCallExtractorRector
Migrates from deprecated enable_magic_call_extraction context option in ReflectionExtractor
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\MethodCall\ReflectionExtractorEnableMagicCallExtractorRector`](../rules/Symfony5/Rector/MethodCall/ReflectionExtractorEnableMagicCallExtractorRector.php)
```diff
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
class SomeClass
{
public function run()
{
$reflectionExtractor = new ReflectionExtractor();
$readInfo = $reflectionExtractor->getReadInfo(Dummy::class, 'bar', [
- 'enable_magic_call_extraction' => true,
+ 'enable_magic_methods_extraction' => ReflectionExtractor::MAGIC_CALL | ReflectionExtractor::MAGIC_GET | ReflectionExtractor::MAGIC_SET,
]);
}
}
```
<br>
### RouteCollectionBuilderToRoutingConfiguratorRector
Change RouteCollectionBuilder to RoutingConfiguratorRector
- class: [`Rector\Symfony5\Rector\ClassMethod\RouteCollectionBuilderToRoutingConfiguratorRector`](../rules/Symfony5/Rector/ClassMethod/RouteCollectionBuilderToRoutingConfiguratorRector.php)
```diff
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel;
-use Symfony\Component\Routing\RouteCollectionBuilder;
+use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
final class ConcreteMicroKernel extends Kernel
{
use MicroKernelTrait;
- protected function configureRoutes(RouteCollectionBuilder $routes)
+ protected function configureRouting(RoutingConfigurator $routes): void
{
- $routes->add('/admin', 'App\Controller\AdminController::dashboard', 'admin_dashboard');
- }
-}
+ $routes->add('admin_dashboard', '/admin')
+ ->controller('App\Controller\AdminController::dashboard')
+ }}
```
<br>
2021-01-30 20:30:37 +00:00
### ValidatorBuilderEnableAnnotationMappingRector
Migrates from deprecated ValidatorBuilder->enableAnnotationMapping($reader) to ValidatorBuilder->enableAnnotationMapping(true)->setDoctrineAnnotationReader($reader)
2021-03-12 23:52:38 +00:00
- class: [`Rector\Symfony5\Rector\MethodCall\ValidatorBuilderEnableAnnotationMappingRector`](../rules/Symfony5/Rector/MethodCall/ValidatorBuilderEnableAnnotationMappingRector.php)
2021-01-30 20:30:37 +00:00
```diff
use Doctrine\Common\Annotations\Reader;
use Symfony\Component\Validator\ValidatorBuilder;
class SomeClass
{
public function run(ValidatorBuilder $builder, Reader $reader)
{
- $builder->enableAnnotationMapping($reader);
+ $builder->enableAnnotationMapping(true)->setDoctrineAnnotationReader($reader);
}
}
```
<br>
## Transform
2021-02-20 23:02:05 +00:00
### AddInterfaceByTraitRector
Add interface by used trait
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Class_\AddInterfaceByTraitRector`](../rules/Transform/Rector/Class_/AddInterfaceByTraitRector.php)
2021-02-20 23:02:05 +00:00
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
2021-02-20 23:02:05 +00:00
};
```
```diff
-class SomeClass
+class SomeClass implements SomeInterface
{
use SomeTrait;
}
```
<br>
2021-01-30 20:30:37 +00:00
### ArgumentFuncCallToMethodCallRector
Move help facade-like function calls to constructor injection
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\FuncCall\ArgumentFuncCallToMethodCallRector`](../rules/Transform/Rector/FuncCall/ArgumentFuncCallToMethodCallRector.php)
2021-01-30 20:30:37 +00:00
```php
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', null, 'make'),
]),
]]);
};
```
```diff
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;
}
}
```
<br>
### CallableInMethodCallToVariableRector
2021-01-30 20:30:37 +00:00
Change a callable in method call to standalone variable assign
2021-01-30 20:30:37 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\MethodCall\CallableInMethodCallToVariableRector`](../rules/Transform/Rector/MethodCall/CallableInMethodCallToVariableRector.php)
2021-01-30 20:30:37 +00:00
```php
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),
]),
]]);
};
```
```diff
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);
}
}
```
<br>
2021-03-12 23:52:38 +00:00
### ChangeSingletonToServiceRector
Change singleton class to normal class that can be registered as a service
- class: [`Rector\Transform\Rector\Class_\ChangeSingletonToServiceRector`](../rules/Transform/Rector/Class_/ChangeSingletonToServiceRector.php)
```diff
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;
}
}
```
<br>
2021-02-13 14:57:30 +00:00
### ClassConstFetchToValueRector
Replaces constant by value
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\ClassConstFetch\ClassConstFetchToValueRector`](../rules/Transform/Rector/ClassConstFetch/ClassConstFetchToValueRector.php)
```php
use Rector\Transform\Rector\ClassConstFetch\ClassConstFetchToValueRector;
2021-01-30 20:30:37 +00:00
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)
2021-01-30 20:30:37 +00:00
->call('configure', [[
ClassConstFetchToValueRector::CLASS_CONST_FETCHES_TO_VALUES => ValueObjectInliner::inline([
2021-01-30 20:30:37 +00:00
new ClassConstFetchToValue('Nette\Configurator', 'DEVELOPMENT', 'development'),
new ClassConstFetchToValue('Nette\Configurator', 'PRODUCTION', 'production'),
]),
]]);
};
```
2021-01-30 20:30:37 +00:00
```diff
-$value === Nette\Configurator::DEVELOPMENT
+$value === "development"
```
<br>
2021-02-13 14:57:30 +00:00
### CommunityTestCaseRector
Change Rector test case to Community version
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Class_\CommunityTestCaseRector`](../rules/Transform/Rector/Class_/CommunityTestCaseRector.php)
2021-02-13 14:57:30 +00:00
```diff
-use Rector\Testing\PHPUnit\AbstractRectorTestCase;
+use Rector\Testing\PHPUnit\AbstractCommunityRectorTestCase;
-final class SomeClassTest extends AbstractRectorTestCase
+final class SomeClassTest extends AbstractCommunityRectorTestCase
{
- public function getRectorClass(): string
+ public function provideConfigFilePath(): string
{
- return SomeRector::class;
+ return __DIR__ . '/config/configured_rule.php';
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### DimFetchAssignToMethodCallRector
2021-01-30 20:30:37 +00:00
Change magic array access add to `$list[],` to explicit `$list->addMethod(...)`
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Assign\DimFetchAssignToMethodCallRector`](../rules/Transform/Rector/Assign/DimFetchAssignToMethodCallRector.php)
```php
2021-01-30 20:30:37 +00:00
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();
2021-01-30 20:30:37 +00:00
$services->set(DimFetchAssignToMethodCallRector::class)
->call('configure', [[
2021-01-30 20:30:37 +00:00
DimFetchAssignToMethodCallRector::DIM_FETCH_ASSIGN_TO_METHOD_CALL => ValueObjectInliner::inline([
new DimFetchAssignToMethodCall('Nette\Application\Routers\RouteList', 'Nette\Application\Routers\Route', 'addRoute'),
]),
]]);
};
```
```diff
2021-01-30 20:30:37 +00:00
-use Nette\Application\Routers\Route;
use Nette\Application\Routers\RouteList;
class RouterFactory
{
2021-01-30 20:30:37 +00:00
public static function createRouter()
{
2021-01-30 20:30:37 +00:00
$routeList = new RouteList();
- $routeList[] = new Route('...');
+ $routeList->addRoute('...');
}
}
```
<br>
### FuncCallToConstFetchRector
Changes use of function calls to use constants
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\FuncCall\FuncCallToConstFetchRector`](../rules/Transform/Rector/FuncCall/FuncCallToConstFetchRector.php)
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $value = php_sapi_name();
+ $value = PHP_SAPI;
}
}
```
<br>
### FuncCallToMethodCallRector
Turns defined function calls to local method calls.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\FuncCall\FuncCallToMethodCallRector`](../rules/Transform/Rector/FuncCall/FuncCallToMethodCallRector.php)
```php
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'),
]),
]]);
};
```
```diff
class SomeClass
{
+ /**
+ * @var \Namespaced\SomeRenderer
+ */
+ private $someRenderer;
+
+ public function __construct(\Namespaced\SomeRenderer $someRenderer)
+ {
+ $this->someRenderer = $someRenderer;
+ }
+
public function run()
{
- view('...');
+ $this->someRenderer->view('...');
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### FuncCallToNewRector
Change configured function calls to new Instance
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\FuncCall\FuncCallToNewRector`](../rules/Transform/Rector/FuncCall/FuncCallToNewRector.php)
2021-01-30 20:30:37 +00:00
```php
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'],
2021-03-12 23:52:38 +00:00
], ]]);
2021-01-30 20:30:37 +00:00
};
```
```diff
class SomeClass
{
public function run()
{
- $array = collection([]);
+ $array = new \Collection([]);
}
}
```
<br>
### FuncCallToStaticCallRector
Turns defined function call to static method call.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\FuncCall\FuncCallToStaticCallRector`](../rules/Transform/Rector/FuncCall/FuncCallToStaticCallRector.php)
2021-01-30 20:30:37 +00:00
```php
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'),
]),
]]);
};
```
```diff
-view("...", []);
+SomeClass::render("...", []);
```
<br>
2021-02-20 23:02:05 +00:00
### FunctionToStaticMethodRector
Change functions to static calls, so composer can autoload them
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\FileWithoutNamespace\FunctionToStaticMethodRector`](../rules/Transform/Rector/FileWithoutNamespace/FunctionToStaticMethodRector.php)
2021-02-20 23:02:05 +00:00
```diff
-function some_function()
+class SomeUtilsClass
{
+ public static function someFunction()
+ {
+ }
}
-some_function('lol');
+SomeUtilsClass::someFunction('lol');
```
<br>
### GetAndSetToMethodCallRector
Turns defined `__get`/`__set` to specific method calls.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Assign\GetAndSetToMethodCallRector`](../rules/Transform/Rector/Assign/GetAndSetToMethodCallRector.php)
```php
use Rector\Transform\Rector\Assign\GetAndSetToMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(GetAndSetToMethodCallRector::class)
->call('configure', [[
GetAndSetToMethodCallRector::TYPE_TO_METHOD_CALLS => [
'SomeContainer' => [
'set' => 'addService',
2021-03-12 23:52:38 +00:00
], ], ]]);
};
```
```diff
$container = new SomeContainer;
-$container->someService = $someService;
+$container->setService("someService", $someService);
```
<br>
```php
use Rector\Transform\Rector\Assign\GetAndSetToMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(GetAndSetToMethodCallRector::class)
->call('configure', [[
GetAndSetToMethodCallRector::TYPE_TO_METHOD_CALLS => [
'SomeContainer' => [
'get' => 'getService',
2021-03-12 23:52:38 +00:00
], ], ]]);
};
```
```diff
$container = new SomeContainer;
-$someService = $container->someService;
+$someService = $container->getService("someService");
```
<br>
2021-02-20 23:02:05 +00:00
### MergeInterfacesRector
Merges old interface to a new one, that already has its methods
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Class_\MergeInterfacesRector`](../rules/Transform/Rector/Class_/MergeInterfacesRector.php)
2021-02-20 23:02:05 +00:00
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
2021-02-20 23:02:05 +00:00
};
```
```diff
-class SomeClass implements SomeInterface, SomeOldInterface
+class SomeClass implements SomeInterface
{
}
```
<br>
### MethodCallToAnotherMethodCallWithArgumentsRector
Turns old method call with specific types to new one with arguments
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector`](../rules/Transform/Rector/MethodCall/MethodCallToAnotherMethodCallWithArgumentsRector.php)
```php
use Rector\Renaming\ValueObject\MethodCallRenameWithArrayKey;
use Rector\Transform\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector;
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 MethodCallRenameWithArrayKey('Nette\DI\ServiceDefinition', 'setInject', 'addTag', 'inject'),
]),
]]);
};
```
```diff
$serviceDefinition = new Nette\DI\ServiceDefinition;
-$serviceDefinition->setInject();
+$serviceDefinition->addTag('inject');
```
<br>
### MethodCallToPropertyFetchRector
Turns method call `"$this->something()"` to property fetch "$this->something"
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\MethodCall\MethodCallToPropertyFetchRector`](../rules/Transform/Rector/MethodCall/MethodCallToPropertyFetchRector.php)
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $this->someMethod();
+ $this->someProperty;
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### MethodCallToReturnRector
Wrap method call to return
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Expression\MethodCallToReturnRector`](../rules/Transform/Rector/Expression/MethodCallToReturnRector.php)
2021-01-30 20:30:37 +00:00
```php
use Rector\Transform\Rector\Expression\MethodCallToReturnRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MethodCallToReturnRector::class)
->call('configure', [[
MethodCallToReturnRector::METHOD_CALL_WRAPS => [
'SomeClass' => ['deny'],
2021-03-12 23:52:38 +00:00
], ]]);
2021-01-30 20:30:37 +00:00
};
```
```diff
class SomeClass
{
public function run()
{
- $this->deny();
+ return $this->deny();
}
public function deny()
{
return 1;
}
}
```
<br>
### MethodCallToStaticCallRector
Change method call to desired static call
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\MethodCall\MethodCallToStaticCallRector`](../rules/Transform/Rector/MethodCall/MethodCallToStaticCallRector.php)
```php
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'),
]),
]]);
};
```
```diff
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');
}
}
```
<br>
### NativeTestCaseRector
Change Rector test case to Community version
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Class_\NativeTestCaseRector`](../rules/Transform/Rector/Class_/NativeTestCaseRector.php)
```diff
-use Rector\Testing\PHPUnit\AbstractRectorTestCase;
+use Rector\Testing\PHPUnit\AbstractCommunityRectorTestCase;
-final class SomeClassTest extends AbstractRectorTestCase
+final class SomeClassTest extends AbstractCommunityRectorTestCase
{
- public function getRectorClass(): string
+ public function provideConfigFilePath(): string
{
- return SomeRector::class;
+ return __DIR__ . '/config/configured_rule.php';
}
}
```
<br>
### NewArgToMethodCallRector
Change new with specific argument to method call
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\New_\NewArgToMethodCallRector`](../rules/Transform/Rector/New_/NewArgToMethodCallRector.php)
```php
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'),
]),
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $dotenv = new Dotenv(true);
+ $dotenv = new Dotenv();
+ $dotenv->usePutenv();
}
}
```
<br>
### NewToConstructorInjectionRector
Change defined new type to constructor injection
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\New_\NewToConstructorInjectionRector`](../rules/Transform/Rector/New_/NewToConstructorInjectionRector.php)
```php
2021-01-30 20:30:37 +00:00
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'],
]]);
};
```
```diff
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);
}
}
```
<br>
### NewToMethodCallRector
Replaces creating object instances with "new" keyword with factory method.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\New_\NewToMethodCallRector`](../rules/Transform/Rector/New_/NewToMethodCallRector.php)
2021-01-30 20:30:37 +00:00
```php
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'),
]),
]]);
};
```
```diff
class SomeClass
{
+ /**
+ * @var \MyClassFactory
+ */
+ private $myClassFactory;
+
public function example() {
- new MyClass($argument);
+ $this->myClassFactory->create($argument);
}
}
```
<br>
### NewToStaticCallRector
Change new Object to static call
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\New_\NewToStaticCallRector`](../rules/Transform/Rector/New_/NewToStaticCallRector.php)
2021-01-30 20:30:37 +00:00
```php
use Rector\Transform\Rector\New_\NewToStaticCallRector;
use Rector\Transform\ValueObject\NewToStaticCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2021-01-30 20:30:37 +00:00
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2021-01-30 20:30:37 +00:00
$services->set(NewToStaticCallRector::class)
->call('configure', [[
2021-01-30 20:30:37 +00:00
NewToStaticCallRector::TYPE_TO_STATIC_CALLS => ValueObjectInliner::inline([
new NewToStaticCall('Cookie', 'Cookie', 'create'),
]),
]]);
};
```
```diff
class SomeClass
{
public function run()
{
2021-01-30 20:30:37 +00:00
- new Cookie($name);
+ Cookie::create($name);
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### ParentClassToTraitsRector
2021-01-30 20:30:37 +00:00
Replaces parent class to specific traits
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Class_\ParentClassToTraitsRector`](../rules/Transform/Rector/Class_/ParentClassToTraitsRector.php)
```php
2021-01-30 20:30:37 +00:00
use Rector\Transform\Rector\Class_\ParentClassToTraitsRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2021-01-30 20:30:37 +00:00
$services->set(ParentClassToTraitsRector::class)
->call('configure', [[
2021-01-30 20:30:37 +00:00
ParentClassToTraitsRector::PARENT_CLASS_TO_TRAITS => [
'Nette\Object' => ['Nette\SmartObject'],
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
2021-01-30 20:30:37 +00:00
-class SomeClass extends Nette\Object
+class SomeClass
{
2021-01-30 20:30:37 +00:00
+ use Nette\SmartObject;
}
```
<br>
### PropertyAssignToMethodCallRector
Turns property assign of specific type and property name to method call
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Assign\PropertyAssignToMethodCallRector`](../rules/Transform/Rector/Assign/PropertyAssignToMethodCallRector.php)
```php
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'),
]),
]]);
};
```
```diff
$someObject = new SomeClass;
-$someObject->oldProperty = false;
+$someObject->newMethodCall(false);
```
<br>
2021-01-30 20:30:37 +00:00
### PropertyFetchToMethodCallRector
Replaces properties assign calls be defined methods.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Assign\PropertyFetchToMethodCallRector`](../rules/Transform/Rector/Assign/PropertyFetchToMethodCallRector.php)
```php
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'),
]),
]]);
};
```
```diff
-$result = $object->property;
-$object->property = $value;
+$result = $object->getProperty();
+$object->setProperty($value);
```
<br>
```php
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', ['someArg'], null),
]),
]]);
};
```
```diff
-$result = $object->property;
+$result = $object->getProperty('someArg');
```
<br>
### ReplaceParentCallByPropertyCallRector
Changes method calls in child of specific types to defined property method call
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\MethodCall\ReplaceParentCallByPropertyCallRector`](../rules/Transform/Rector/MethodCall/ReplaceParentCallByPropertyCallRector.php)
```php
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'),
]),
]]);
};
```
```diff
final class SomeClass
{
public function run(SomeTypeToReplace $someTypeToReplace)
{
- $someTypeToReplace->someMethodCall();
+ $this->someProperty->someMethodCall();
}
}
```
<br>
### ServiceGetterToConstructorInjectionRector
2020-07-24 11:46:57 +00:00
Get service call to constructor injection
2020-07-24 11:46:57 +00:00
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\MethodCall\ServiceGetterToConstructorInjectionRector`](../rules/Transform/Rector/MethodCall/ServiceGetterToConstructorInjectionRector.php)
```php
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'),
]),
]]);
};
```
```diff
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();
}
}
```
<br>
### SingleToManyMethodRector
Change method that returns single value to multiple values
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\ClassMethod\SingleToManyMethodRector`](../rules/Transform/Rector/ClassMethod/SingleToManyMethodRector.php)
```php
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'),
]),
]]);
};
```
```diff
class SomeClass
{
- public function getNode(): string
+ /**
+ * @return string[]
+ */
+ public function getNodes(): array
{
- return 'Echo_';
+ return ['Echo_'];
}
}
```
<br>
### StaticCallToFuncCallRector
Turns static call to function call.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\StaticCall\StaticCallToFuncCallRector`](../rules/Transform/Rector/StaticCall/StaticCallToFuncCallRector.php)
```php
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'),
]),
]]);
};
```
2019-05-29 13:40:20 +00:00
```diff
-OldClass::oldMethod("args");
+new_function("args");
2018-07-31 12:50:39 +00:00
```
<br>
### StaticCallToMethodCallRector
Change static call to service method via constructor injection
2018-05-04 22:30:32 +00:00
:wrench: **configure it!**
2018-08-01 20:09:34 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\StaticCall\StaticCallToMethodCallRector`](../rules/Transform/Rector/StaticCall/StaticCallToMethodCallRector.php)
```php
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'
),
]),
]]);
};
```
2018-05-04 22:30:32 +00:00
```diff
-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');
}
}
2018-08-01 20:09:34 +00:00
```
<br>
### StaticCallToNewRector
Change static call to new instance
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\StaticCall\StaticCallToNewRector`](../rules/Transform/Rector/StaticCall/StaticCallToNewRector.php)
```php
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'),
]),
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $dotenv = JsonResponse::create(true);
+ $dotenv = new JsonResponse();
}
}
```
<br>
2021-01-30 20:30:37 +00:00
### StringToClassConstantRector
Changes strings to specific constants
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\String_\StringToClassConstantRector`](../rules/Transform/Rector/String_/StringToClassConstantRector.php)
2021-01-30 20:30:37 +00:00
```php
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'),
]),
]]);
};
```
```diff
final class SomeSubscriber
{
public static function getSubscribedEvents()
{
- return ['compiler.post_dump' => 'compile'];
+ return [\Yet\AnotherClass::CONSTANT => 'compile'];
}
}
```
<br>
### ToStringToMethodCallRector
Turns defined code uses of `"__toString()"` method to specific method calls.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\String_\ToStringToMethodCallRector`](../rules/Transform/Rector/String_/ToStringToMethodCallRector.php)
```php
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',
2021-03-12 23:52:38 +00:00
], ]]);
};
```
```diff
$someValue = new SomeObject;
-$result = (string) $someValue;
-$result = $someValue->__toString();
+$result = $someValue->getPath();
+$result = $someValue->getPath();
```
<br>
### UnsetAndIssetToMethodCallRector
Turns defined `__isset`/`__unset` calls to specific method calls.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\Isset_\UnsetAndIssetToMethodCallRector`](../rules/Transform/Rector/Isset_/UnsetAndIssetToMethodCallRector.php)
```php
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'),
]),
]]);
};
```
```diff
$container = new SomeContainer;
-isset($container["someKey"]);
-unset($container["someKey"]);
+$container->hasService("someKey");
+$container->removeService("someKey");
```
<br>
### VariableMethodCallToServiceCallRector
Replace variable method call to a service one
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\MethodCall\VariableMethodCallToServiceCallRector`](../rules/Transform/Rector/MethodCall/VariableMethodCallToServiceCallRector.php)
```php
use Rector\Transform\Rector\MethodCall\VariableMethodCallToServiceCallRector;
use Rector\Transform\ValueObject\VariableMethodCallToServiceCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\SymfonyPhpConfig\ValueObjectInliner;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(VariableMethodCallToServiceCallRector::class)
->call('configure', [[
VariableMethodCallToServiceCallRector::VARIABLE_METHOD_CALLS_TO_SERVICE_CALLS => ValueObjectInliner::inline([
new VariableMethodCallToServiceCall(
'PhpParser\Node',
'getAttribute',
'php_doc_info',
'Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory',
'createFromNodeOrEmpty'
),
]),
]]);
};
```
```diff
+use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use PhpParser\Node;
class SomeClass
{
+ public function __construct(PhpDocInfoFactory $phpDocInfoFactory)
+ {
+ $this->phpDocInfoFactory = $phpDocInfoFactory;
+ }
public function run(Node $node)
{
- $phpDocInfo = $node->getAttribute('php_doc_info');
+ $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
}
}
```
<br>
### WrapReturnRector
Wrap return value of specific method
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Transform\Rector\ClassMethod\WrapReturnRector`](../rules/Transform/Rector/ClassMethod/WrapReturnRector.php)
```php
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)]),
]]);
};
```
```diff
final class SomeClass
{
public function getItem()
{
- return 1;
+ return [1];
}
}
```
<br>
## TypeDeclaration
2020-07-24 11:46:57 +00:00
### AddArrayParamDocTypeRector
2019-08-05 21:10:47 +00:00
Adds `@param` annotation to array parameters inferred from the rest of the code
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddArrayParamDocTypeRector`](../rules/TypeDeclaration/Rector/ClassMethod/AddArrayParamDocTypeRector.php)
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
2019-08-05 21:10:47 +00:00
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @param int[] $values
+ */
public function __construct(array $values)
{
$this->values = $values;
}
}
```
2019-08-05 21:10:47 +00:00
<br>
### AddArrayReturnDocTypeRector
Adds `@return` annotation to array parameters inferred from the rest of the code
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddArrayReturnDocTypeRector`](../rules/TypeDeclaration/Rector/ClassMethod/AddArrayReturnDocTypeRector.php)
```diff
class SomeClass
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @return int[]
+ */
public function getValues(): array
2019-08-05 21:10:47 +00:00
{
return $this->values;
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
### AddClosureReturnTypeRector
2018-05-04 22:30:32 +00:00
Add known return type to functions
2020-07-24 11:46:57 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\Closure\AddClosureReturnTypeRector`](../rules/TypeDeclaration/Rector/Closure/AddClosureReturnTypeRector.php)
```diff
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);
});
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2021-02-20 23:02:05 +00:00
### AddMethodCallBasedStrictParamTypeRector
2018-08-01 20:09:34 +00:00
2021-02-20 23:02:05 +00:00
Change param type to strict type of passed expression
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector`](../rules/TypeDeclaration/Rector/ClassMethod/AddMethodCallBasedStrictParamTypeRector.php)
2018-08-01 20:09:34 +00:00
2018-05-04 22:30:32 +00:00
```diff
class SomeClass
{
- public function getById($id)
2021-02-20 23:02:05 +00:00
+ public function getById(int $id)
{
}
}
class CallerClass
{
2021-02-20 23:02:05 +00:00
public function run(SomeClass $someClass)
{
2021-02-20 23:02:05 +00:00
$someClass->getById($this->getId());
}
public function getId(): int
{
return 1000;
}
}
2018-07-31 06:38:48 +00:00
```
<br>
### AddParamTypeDeclarationRector
Add param types where needed
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector`](../rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeDeclarationRector.php)
```php
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()),
]),
]]);
};
```
```diff
class SomeClass
{
- public function process($name)
+ public function process(string $name)
{
}
}
```
<br>
### AddParamTypeFromCallersRector
Add param type based on called types in that particular method
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeFromCallersRector`](../rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeFromCallersRector.php)
```diff
final class SomeClass
{
public function run(Return_ $return)
{
$this->print($return);
}
- public function print($return)
+ public function print(Return_ $return)
{
}
}
```
<br>
### AddReturnTypeDeclarationRector
Changes defined return typehint of method and class.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector`](../rules/TypeDeclaration/Rector/ClassMethod/AddReturnTypeDeclarationRector.php)
```php
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
))),
]),
]]);
};
```
```diff
class SomeClass
{
- public getData()
+ public getData(): array
{
}
}
```
<br>
2021-02-20 23:02:05 +00:00
### AddVoidReturnTypeWhereNoReturnRector
Add return type void to function like without any return
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddVoidReturnTypeWhereNoReturnRector`](../rules/TypeDeclaration/Rector/ClassMethod/AddVoidReturnTypeWhereNoReturnRector.php)
2021-02-20 23:02:05 +00:00
```diff
final class SomeClass
{
- public function getValues()
+ public function getValues(): void
{
$value = 1000;
return;
}
}
```
<br>
### CompleteVarDocTypePropertyRector
2020-07-24 11:46:57 +00:00
Complete property `@var` annotations or correct the old ones
2018-08-01 20:09:34 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\Property\CompleteVarDocTypePropertyRector`](../rules/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector.php)
2018-08-01 20:09:34 +00:00
2018-05-04 22:30:32 +00:00
```diff
final class SomeClass
{
+ /**
+ * @var EventDispatcher
+ */
private $eventDispatcher;
public function __construct(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
}
2018-05-04 22:30:32 +00:00
```
<br>
2021-01-30 20:30:37 +00:00
### FormerNullableArgumentToScalarTypedRector
Change null in argument, that is now not nullable anymore
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\MethodCall\FormerNullableArgumentToScalarTypedRector`](../rules/TypeDeclaration/Rector/MethodCall/FormerNullableArgumentToScalarTypedRector.php)
2021-01-30 20:30:37 +00:00
```diff
final class SomeClass
{
public function run()
{
- $this->setValue(null);
+ $this->setValue('');
}
public function setValue(string $value)
{
}
}
```
<br>
### ParamTypeDeclarationRector
2019-12-18 09:53:46 +00:00
Change `@param` types to type declarations if not a BC-break
2020-07-24 11:46:57 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\FunctionLike\ParamTypeDeclarationRector`](../rules/TypeDeclaration/Rector/FunctionLike/ParamTypeDeclarationRector.php)
2020-07-24 11:46:57 +00:00
```diff
class ParentClass
2019-12-18 09:53:46 +00:00
{
/**
* @param int $number
*/
public function keep($number)
{
}
}
final class ChildClass extends ParentClass
{
/**
* @param int $number
*/
public function keep($number)
{
}
2021-01-30 20:30:37 +00:00
- /**
- * @param int $number
- */
- public function change($number)
+ public function change(int $number)
{
}
2019-12-18 09:53:46 +00:00
}
```
<br>
2019-12-18 09:53:46 +00:00
2021-02-20 23:02:05 +00:00
### ParamTypeFromStrictTypedPropertyRector
Add param type from `$param` set to typed property
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeFromStrictTypedPropertyRector`](../rules/TypeDeclaration/Rector/ClassMethod/ParamTypeFromStrictTypedPropertyRector.php)
2021-02-20 23:02:05 +00:00
```diff
final class SomeClass
{
private int $age;
- public function setAge($age)
+ public function setAge(int $age)
{
$this->age = $age;
}
}
```
<br>
### PropertyTypeDeclarationRector
2019-09-25 08:49:53 +00:00
Add `@var` to properties that are missing it
2019-09-25 08:49:53 +00:00
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\Property\PropertyTypeDeclarationRector`](../rules/TypeDeclaration/Rector/Property/PropertyTypeDeclarationRector.php)
```diff
class SomeClass
{
+ /**
+ * @var int
+ */
private $value;
2019-09-25 08:49:53 +00:00
public function run()
{
$this->value = 123;
}
}
```
2019-09-25 08:49:53 +00:00
<br>
2020-07-24 11:46:57 +00:00
### ReturnTypeDeclarationRector
Change `@return` types and type from static analysis to type declarations if not a BC-break
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\FunctionLike\ReturnTypeDeclarationRector`](../rules/TypeDeclaration/Rector/FunctionLike/ReturnTypeDeclarationRector.php)
```diff
class SomeClass
{
- /**
- * @return int
- */
- public function getCount()
+ public function getCount(): int
{
}
}
```
<br>
2021-01-30 20:30:37 +00:00
2021-02-20 23:02:05 +00:00
### ReturnTypeFromReturnNewRector
Add return type void to function like without any return
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnNewRector`](../rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromReturnNewRector.php)
2021-02-20 23:02:05 +00:00
```diff
final class SomeClass
{
- public function action()
+ public function action(): Respose
{
return new Response();
}
}
```
<br>
### ReturnTypeFromStrictTypedCallRector
Add return type from strict return type of call
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictTypedCallRector`](../rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedCallRector.php)
2021-02-20 23:02:05 +00:00
```diff
final class SomeClass
{
- public function getData()
+ public function getData(): int
{
return $this->getNumber();
}
private function getNumber(): int
{
return 1000;
}
}
```
<br>
### ReturnTypeFromStrictTypedPropertyRector
Add return method return type based on strict typed property
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictTypedPropertyRector`](../rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedPropertyRector.php)
```diff
final class SomeClass
{
private int $age = 100;
- public function getAge()
+ public function getAge(): int
{
return $this->age;
}
}
```
<br>
### TypedPropertyFromStrictConstructorRector
Add typed properties based only on strict constructor types
2021-03-12 23:52:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\Property\TypedPropertyFromStrictConstructorRector`](../rules/TypeDeclaration/Rector/Property/TypedPropertyFromStrictConstructorRector.php)
```diff
class SomeObject
{
- private $name;
+ private string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
```
<br>
2021-01-30 20:30:37 +00:00
## Visibility
### ChangeConstantVisibilityRector
Change visibility of constant from parent class.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Visibility\Rector\ClassConst\ChangeConstantVisibilityRector`](../rules/Visibility/Rector/ClassConst/ChangeConstantVisibilityRector.php)
2021-01-30 20:30:37 +00:00
```php
use Rector\Visibility\Rector\ClassConst\ChangeConstantVisibilityRector;
use Rector\Visibility\ValueObject\ChangeConstantVisibility;
2021-01-30 20:30:37 +00:00
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),
2021-01-30 20:30:37 +00:00
]),
]]);
};
```
```diff
class FrameworkClass
{
protected const SOME_CONSTANT = 1;
}
class MyClass extends FrameworkClass
{
- public const SOME_CONSTANT = 1;
+ protected const SOME_CONSTANT = 1;
}
```
<br>
### ChangeMethodVisibilityRector
Change visibility of method from parent class.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Visibility\Rector\ClassMethod\ChangeMethodVisibilityRector`](../rules/Visibility/Rector/ClassMethod/ChangeMethodVisibilityRector.php)
2021-01-30 20:30:37 +00:00
```php
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),
]),
]]);
};
```
```diff
class FrameworkClass
{
protected someMethod()
{
}
}
class MyClass extends FrameworkClass
{
- public someMethod()
+ protected someMethod()
{
}
}
```
<br>
### ChangePropertyVisibilityRector
Change visibility of property from parent class.
:wrench: **configure it!**
2021-03-12 23:52:38 +00:00
- class: [`Rector\Visibility\Rector\Property\ChangePropertyVisibilityRector`](../rules/Visibility/Rector/Property/ChangePropertyVisibilityRector.php)
2021-01-30 20:30:37 +00:00
```php
use Rector\Visibility\Rector\Property\ChangePropertyVisibilityRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangePropertyVisibilityRector::class)
->call('configure', [[
ChangePropertyVisibilityRector::PROPERTY_TO_VISIBILITY_BY_CLASS => [
'FrameworkClass' => [
'someProperty' => 2,
2021-03-12 23:52:38 +00:00
], ], ]]);
2021-01-30 20:30:37 +00:00
};
```
```diff
class FrameworkClass
{
protected $someProperty;
}
class MyClass extends FrameworkClass
{
- public $someProperty;
+ protected $someProperty;
}
```
<br>