rector/docs/rector_rules_overview.md

13441 lines
366 KiB
Markdown
Raw Normal View History

# All 536 Rectors Overview
2018-04-29 09:03:47 +00:00
2018-08-01 20:09:34 +00:00
- [Projects](#projects)
- [General](#general)
---
2018-08-01 20:09:34 +00:00
## Projects
- [Architecture](#architecture) (4)
- [Autodiscovery](#autodiscovery) (4)
- [CakePHP](#cakephp) (6)
- [Celebrity](#celebrity) (3)
- [CodeQuality](#codequality) (54)
- [CodingStyle](#codingstyle) (36)
- [DeadCode](#deadcode) (40)
- [Decomplex](#decomplex) (1)
- [Decouple](#decouple) (1)
- [Doctrine](#doctrine) (16)
- [DoctrineCodeQuality](#doctrinecodequality) (2)
- [DoctrineGedmoToKnplabs](#doctrinegedmotoknplabs) (7)
- [Downgrade](#downgrade) (1)
- [DynamicTypeAnalysis](#dynamictypeanalysis) (3)
- [FileSystemRector](#filesystemrector) (1)
- [Guzzle](#guzzle) (1)
2020-07-24 11:46:57 +00:00
- [Injection](#injection) (1)
- [JMS](#jms) (2)
- [Laravel](#laravel) (6)
2020-07-14 21:23:06 +00:00
- [Legacy](#legacy) (4)
- [MagicDisclosure](#magicdisclosure) (5)
- [MockeryToProphecy](#mockerytoprophecy) (2)
2020-05-14 10:26:57 +00:00
- [MockistaToMockery](#mockistatomockery) (2)
- [MysqlToMysqli](#mysqltomysqli) (4)
- [Naming](#naming) (3)
- [Nette](#nette) (12)
- [NetteCodeQuality](#nettecodequality) (4)
2020-05-29 10:41:25 +00:00
- [NetteKdyby](#nettekdyby) (4)
- [NetteTesterToPHPUnit](#nettetestertophpunit) (3)
- [NetteToSymfony](#nettetosymfony) (9)
- [NetteUtilsCodeQuality](#netteutilscodequality) (1)
- [Order](#order) (5)
- [PHPOffice](#phpoffice) (14)
- [PHPStan](#phpstan) (3)
- [PHPUnit](#phpunit) (37)
- [PHPUnitSymfony](#phpunitsymfony) (1)
- [PSR4](#psr4) (3)
- [Performance](#performance) (1)
- [Phalcon](#phalcon) (4)
- [Php52](#php52) (2)
2020-05-31 15:45:51 +00:00
- [Php53](#php53) (4)
- [Php54](#php54) (2)
- [Php55](#php55) (2)
- [Php56](#php56) (2)
- [Php70](#php70) (19)
- [Php71](#php71) (9)
- [Php72](#php72) (11)
- [Php73](#php73) (10)
- [Php74](#php74) (15)
- [Php80](#php80) (11)
- [PhpDeglobalize](#phpdeglobalize) (1)
- [PhpSpecToPHPUnit](#phpspectophpunit) (7)
- [Polyfill](#polyfill) (2)
2020-05-29 10:41:25 +00:00
- [Privatization](#privatization) (7)
- [RectorGenerator](#rectorgenerator) (1)
- [RemovingStatic](#removingstatic) (4)
- [Renaming](#renaming) (9)
- [Restoration](#restoration) (7)
- [SOLID](#solid) (12)
- [Sensio](#sensio) (3)
- [StrictCodeQuality](#strictcodequality) (1)
- [Symfony](#symfony) (33)
- [SymfonyCodeQuality](#symfonycodequality) (1)
- [SymfonyPHPUnit](#symfonyphpunit) (1)
- [SymfonyPhpConfig](#symfonyphpconfig) (1)
- [Twig](#twig) (1)
- [TypeDeclaration](#typedeclaration) (9)
2018-09-28 16:33:35 +00:00
2019-08-05 21:10:47 +00:00
## Architecture
### `ConstructorInjectionToActionInjectionRector`
- class: [`Rector\Architecture\Rector\Class_\ConstructorInjectionToActionInjectionRector`](/../master/rules/architecture/src/Rector/Class_/ConstructorInjectionToActionInjectionRector.php)
- [test fixtures](/../master/rules/architecture/tests/Rector/Class_/ConstructorInjectionToActionInjectionRector/Fixture)
2019-08-05 21:10:47 +00:00
Move constructor injection dependency in Controller to action injection
2019-08-05 21:10:47 +00:00
```diff
final class SomeController
{
- /**
- * @var ProductRepository
- */
- private $productRepository;
-
- public function __construct(ProductRepository $productRepository)
+ public function default(ProductRepository $productRepository)
{
- $this->productRepository = $productRepository;
- }
-
- public function default()
- {
- $products = $this->productRepository->fetchAll();
+ $products = $productRepository->fetchAll();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
2020-02-13 13:42:40 +00:00
### `MoveRepositoryFromParentToConstructorRector`
- class: [`Rector\Architecture\Rector\Class_\MoveRepositoryFromParentToConstructorRector`](/../master/rules/architecture/src/Rector/Class_/MoveRepositoryFromParentToConstructorRector.php)
2020-02-13 13:42:40 +00:00
Turns parent EntityRepository class to constructor dependency
```diff
namespace App\Repository;
+use App\Entity\Post;
use Doctrine\ORM\EntityRepository;
-final class PostRepository extends EntityRepository
+final class PostRepository
{
+ /**
+ * @var \Doctrine\ORM\EntityRepository
+ */
+ private $repository;
+ public function __construct(\Doctrine\ORM\EntityManager $entityManager)
+ {
+ $this->repository = $entityManager->getRepository(\App\Entity\Post::class);
+ }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-02-13 13:42:40 +00:00
### `ReplaceParentRepositoryCallsByRepositoryPropertyRector`
- class: [`Rector\Architecture\Rector\MethodCall\ReplaceParentRepositoryCallsByRepositoryPropertyRector`](/../master/rules/architecture/src/Rector/MethodCall/ReplaceParentRepositoryCallsByRepositoryPropertyRector.php)
2020-02-13 13:42:40 +00:00
2020-07-07 10:15:52 +00:00
Handles method calls in child of Doctrine EntityRepository and moves them to `$this->repository` property.
2020-02-13 13:42:40 +00:00
```diff
<?php
use Doctrine\ORM\EntityRepository;
class SomeRepository extends EntityRepository
{
public function someMethod()
{
- return $this->findAll();
+ return $this->repository->findAll();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-02-13 13:42:40 +00:00
### `ServiceLocatorToDIRector`
- class: [`Rector\Architecture\Rector\MethodCall\ServiceLocatorToDIRector`](/../master/rules/architecture/src/Rector/MethodCall/ServiceLocatorToDIRector.php)
2020-02-13 13:42:40 +00:00
2020-07-07 10:15:52 +00:00
Turns `$this->getRepository()` in Symfony Controller to constructor injection and private property access.
2020-02-13 13:42:40 +00:00
```diff
class ProductController extends Controller
{
+ /**
+ * @var ProductRepository
+ */
+ private $productRepository;
+
+ public function __construct(ProductRepository $productRepository)
+ {
+ $this->productRepository = $productRepository;
+ }
+
public function someAction()
{
$entityManager = $this->getDoctrine()->getManager();
- $entityManager->getRepository('SomethingBundle:Product')->findSomething(...);
+ $this->productRepository->findSomething(...);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-02-13 13:42:40 +00:00
2019-09-15 18:28:10 +00:00
## Autodiscovery
### `MoveEntitiesToEntityDirectoryRector`
- class: [`Rector\Autodiscovery\Rector\FileSystem\MoveEntitiesToEntityDirectoryRector`](/../master/rules/autodiscovery/src/Rector/FileSystem/MoveEntitiesToEntityDirectoryRector.php)
2019-09-15 18:28:10 +00:00
Move entities to Entity namespace
```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
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-15 18:28:10 +00:00
### `MoveInterfacesToContractNamespaceDirectoryRector`
- class: [`Rector\Autodiscovery\Rector\FileSystem\MoveInterfacesToContractNamespaceDirectoryRector`](/../master/rules/autodiscovery/src/Rector/FileSystem/MoveInterfacesToContractNamespaceDirectoryRector.php)
2019-09-15 18:28:10 +00:00
Move interface to "Contract" namespace
```diff
-// file: app/Exception/Rule.php
+// file: app/Contract/Rule.php
-namespace App\Exception;
+namespace App\Contract;
interface Rule
{
}
2019-09-15 18:28:10 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-15 18:28:10 +00:00
### `MoveServicesBySuffixToDirectoryRector`
- class: [`Rector\Autodiscovery\Rector\FileSystem\MoveServicesBySuffixToDirectoryRector`](/../master/rules/autodiscovery/src/Rector/FileSystem/MoveServicesBySuffixToDirectoryRector.php)
2019-09-15 18:28:10 +00:00
Move classes by their suffix to their own group/directory
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Autodiscovery\Rector\FileSystem\MoveServicesBySuffixToDirectoryRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(MoveServicesBySuffixToDirectoryRector::class)
->arg('$groupNamesBySuffix', ['Repository']);
};
2019-09-15 18:28:10 +00:00
```
```diff
-// file: app/Entity/ProductRepository.php
+// file: app/Repository/ProductRepository.php
-namespace App/Entity;
+namespace App/Repository;
class ProductRepository
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-15 18:28:10 +00:00
2019-12-26 10:21:09 +00:00
### `MoveValueObjectsToValueObjectDirectoryRector`
- class: [`Rector\Autodiscovery\Rector\FileSystem\MoveValueObjectsToValueObjectDirectoryRector`](/../master/rules/autodiscovery/src/Rector/FileSystem/MoveValueObjectsToValueObjectDirectoryRector.php)
2019-12-26 10:21:09 +00:00
Move value object to ValueObject namespace/directory
```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;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-26 10:21:09 +00:00
## CakePHP
2018-09-28 16:33:35 +00:00
### `AppUsesStaticCallToUseStatementRector`
- class: [`Rector\CakePHP\Rector\StaticCall\AppUsesStaticCallToUseStatementRector`](/../master/rules/cakephp/src/Rector/StaticCall/AppUsesStaticCallToUseStatementRector.php)
- [test fixtures](/../master/rules/cakephp/tests/Rector/StaticCall/AppUsesStaticCallToUseStatementRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `App::uses()` to use imports
```diff
-App::uses('NotificationListener', 'Event');
+use Event\NotificationListener;
CakeEventManager::instance()->attach(new NotificationListener());
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ArrayToFluentCallRector`
- class: [`Rector\CakePHP\Rector\MethodCall\ArrayToFluentCallRector`](/../master/rules/cakephp/src/Rector/MethodCall/ArrayToFluentCallRector.php)
- [test fixtures](/../master/rules/cakephp/tests/Rector/MethodCall/ArrayToFluentCallRector/Fixture)
Moves array options to fluent setter method calls.
```diff
class ArticlesTable extends \Cake\ORM\Table
{
public function initialize(array $config)
{
- $this->belongsTo('Authors', [
- 'foreignKey' => 'author_id',
- 'propertyName' => 'person'
- ]);
+ $this->belongsTo('Authors')
+ ->setForeignKey('author_id')
+ ->setProperty('person');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeSnakedFixtureNameToCamelRector`
- class: [`Rector\CakePHP\Rector\Name\ChangeSnakedFixtureNameToCamelRector`](/../master/rules/cakephp/src/Rector/Name/ChangeSnakedFixtureNameToCamelRector.php)
2020-07-07 10:15:52 +00:00
Changes `$fixtues` style from snake_case to CamelCase.
```diff
class SomeTest
{
protected $fixtures = [
- 'app.posts',
- 'app.users',
- 'some_plugin.posts/special_posts',
+ 'app.Posts',
+ 'app.Users',
+ 'some_plugin.Posts/SpeectialPosts',
];
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ImplicitShortClassNameUseStatementRector`
- class: [`Rector\CakePHP\Rector\Name\ImplicitShortClassNameUseStatementRector`](/../master/rules/cakephp/src/Rector/Name/ImplicitShortClassNameUseStatementRector.php)
- [test fixtures](/../master/rules/cakephp/tests/Rector/Name/ImplicitShortClassNameUseStatementRector/Fixture)
Collect implicit class names and add imports
```diff
use App\Foo\Plugin;
+use Cake\TestSuite\Fixture\TestFixture;
class LocationsFixture extends TestFixture implements Plugin
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-09-28 16:33:35 +00:00
### `ModalToGetSetRector`
- class: [`Rector\CakePHP\Rector\MethodCall\ModalToGetSetRector`](/../master/rules/cakephp/src/Rector/MethodCall/ModalToGetSetRector.php)
- [test fixtures](/../master/rules/cakephp/tests/Rector/MethodCall/ModalToGetSetRector/Fixture)
2018-09-28 16:33:35 +00:00
Changes combined set/get `value()` to specific `getValue()` or `setValue(x)`.
```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']);
```
2018-08-01 20:09:34 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-02 08:04:14 +00:00
### `RenameMethodCallBasedOnParameterRector`
- class: [`Rector\CakePHP\Rector\MethodCall\RenameMethodCallBasedOnParameterRector`](/../master/rules/cakephp/src/Rector/MethodCall/RenameMethodCallBasedOnParameterRector.php)
- [test fixtures](/../master/rules/cakephp/tests/Rector/MethodCall/RenameMethodCallBasedOnParameterRector/Fixture)
2019-10-02 08:04:14 +00:00
Changes method calls based on matching the first parameter value.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\CakePHP\Rector\MethodCall\RenameMethodCallBasedOnParameterRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameMethodCallBasedOnParameterRector::class)
->arg('$methodNamesByTypes', ['getParam' => ['match_parameter' => 'paging', 'replace_with' => 'getAttribute'], 'withParam' => ['match_parameter' => 'paging', 'replace_with' => 'withAttribute']]);
};
2019-10-02 08:04:14 +00:00
```
```diff
$object = new ServerRequest();
-$config = $object->getParam('paging');
-$object = $object->withParam('paging', ['a value']);
+$config = $object->getAttribute('paging');
+$object = $object->withAttribute('paging', ['a value']);
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-02 08:04:14 +00:00
2019-03-09 13:24:30 +00:00
## Celebrity
### `CommonNotEqualRector`
- class: [`Rector\Celebrity\Rector\NotEqual\CommonNotEqualRector`](/../master/rules/celebrity/src/Rector/NotEqual/CommonNotEqualRector.php)
- [test fixtures](/../master/rules/celebrity/tests/Rector/NotEqual/CommonNotEqualRector/Fixture)
2019-03-09 13:24:30 +00:00
Use common != instead of less known <> with same meaning
```diff
final class SomeClass
{
public function run($one, $two)
{
- return $one <> $two;
+ return $one != $two;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
### `LogicalToBooleanRector`
- class: [`Rector\Celebrity\Rector\BooleanOp\LogicalToBooleanRector`](/../master/rules/celebrity/src/Rector/BooleanOp/LogicalToBooleanRector.php)
- [test fixtures](/../master/rules/celebrity/tests/Rector/BooleanOp/LogicalToBooleanRector/Fixture)
2019-03-09 13:24:30 +00:00
Change OR, AND to ||, && with more common understanding
```diff
-if ($f = false or true) {
+if (($f = false) || true) {
return $f;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
2019-05-29 13:40:20 +00:00
### `SetTypeToCastRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\Celebrity\Rector\FuncCall\SetTypeToCastRector`](/../master/rules/celebrity/src/Rector/FuncCall/SetTypeToCastRector.php)
- [test fixtures](/../master/rules/celebrity/tests/Rector/FuncCall/SetTypeToCastRector/Fixture)
2019-02-21 14:36:16 +00:00
2020-06-16 14:39:45 +00:00
Changes `settype()` to (type) where possible
2019-02-21 14:36:16 +00:00
```diff
class SomeClass
{
2019-05-29 13:40:20 +00:00
- public function run($foo)
+ public function run(array $items)
2019-02-21 14:36:16 +00:00
{
2019-05-29 13:40:20 +00:00
- settype($foo, 'string');
+ $foo = (string) $foo;
- return settype($foo, 'integer');
+ return (int) $foo;
2019-02-21 14:36:16 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
2019-05-29 13:40:20 +00:00
## CodeQuality
2019-03-09 13:24:30 +00:00
2020-01-03 18:20:13 +00:00
### `AbsolutizeRequireAndIncludePathRector`
- class: [`Rector\CodeQuality\Rector\Include_\AbsolutizeRequireAndIncludePathRector`](/../master/rules/code-quality/src/Rector/Include_/AbsolutizeRequireAndIncludePathRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Include_/AbsolutizeRequireAndIncludePathRector/Fixture)
2020-01-03 18:20:13 +00:00
include/require to absolute path. This Rector might introduce backwards incompatible code, when the include/require beeing changed depends on the current working directory.
```diff
class SomeClass
{
public function run()
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
require $variable;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-03 18:20:13 +00:00
2019-11-06 23:52:19 +00:00
### `AddPregQuoteDelimiterRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\AddPregQuoteDelimiterRector`](/../master/rules/code-quality/src/Rector/FuncCall/AddPregQuoteDelimiterRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/AddPregQuoteDelimiterRector/Fixture)
2019-11-06 23:52:19 +00:00
2020-06-16 14:39:45 +00:00
Add `preg_quote` delimiter when missing
2019-11-06 23:52:19 +00:00
```diff
-'#' . preg_quote('name') . '#';
+'#' . preg_quote('name', '#') . '#';
2019-11-06 23:52:19 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
### `AndAssignsToSeparateLinesRector`
2019-03-09 13:24:30 +00:00
- class: [`Rector\CodeQuality\Rector\LogicalAnd\AndAssignsToSeparateLinesRector`](/../master/rules/code-quality/src/Rector/LogicalAnd/AndAssignsToSeparateLinesRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/LogicalAnd/AndAssignsToSeparateLinesRector/Fixture)
2019-05-29 13:40:20 +00:00
Split 2 assigns ands to separate line
2019-03-09 13:24:30 +00:00
```diff
class SomeClass
{
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
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
2020-01-03 18:20:13 +00:00
### `ArrayKeyExistsTernaryThenValueToCoalescingRector`
- class: [`Rector\CodeQuality\Rector\Ternary\ArrayKeyExistsTernaryThenValueToCoalescingRector`](/../master/rules/code-quality/src/Rector/Ternary/ArrayKeyExistsTernaryThenValueToCoalescingRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Ternary/ArrayKeyExistsTernaryThenValueToCoalescingRector/Fixture)
2020-01-03 18:20:13 +00:00
2020-06-16 14:39:45 +00:00
Change `array_key_exists()` ternary to coalesing
2020-01-03 18:20:13 +00:00
```diff
class SomeClass
{
public function run($values, $keyToMatch)
{
- $result = array_key_exists($keyToMatch, $values) ? $values[$keyToMatch] : null;
+ $result = $values[$keyToMatch] ?? null;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-03 18:20:13 +00:00
2020-03-28 13:29:19 +00:00
### `ArrayKeysAndInArrayToArrayKeyExistsRector`
2020-03-28 13:29:19 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\ArrayKeysAndInArrayToArrayKeyExistsRector`](/../master/rules/code-quality/src/Rector/FuncCall/ArrayKeysAndInArrayToArrayKeyExistsRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/ArrayKeysAndInArrayToArrayKeyExistsRector/Fixture)
2020-06-16 14:39:45 +00:00
Replace `array_keys()` and `in_array()` to `array_key_exists()`
```diff
class SomeClass
{
public function run($packageName, $values)
{
- $keys = array_keys($values);
- return in_array($packageName, $keys, true);
+ return array_key_exists($packageName, $values);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
### `ArrayMergeOfNonArraysToSimpleArrayRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\ArrayMergeOfNonArraysToSimpleArrayRector`](/../master/rules/code-quality/src/Rector/FuncCall/ArrayMergeOfNonArraysToSimpleArrayRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/ArrayMergeOfNonArraysToSimpleArrayRector/Fixture)
2019-11-06 23:52:19 +00:00
2020-06-16 14:39:45 +00:00
Change `array_merge` of non arrays to array directly
2019-11-06 23:52:19 +00:00
```diff
class SomeClass
{
public function go()
{
$value = 5;
$value2 = 10;
- return array_merge([$value], [$value2]);
+ return [$value, $value2];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
### `ArrayThisCallToThisMethodCallRector`
- class: [`Rector\CodeQuality\Rector\Array_\ArrayThisCallToThisMethodCallRector`](/../master/rules/code-quality/src/Rector/Array_/ArrayThisCallToThisMethodCallRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Array_/ArrayThisCallToThisMethodCallRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `[$this, someMethod]` without any args to `$this->someMethod()`
```diff
class SomeClass
{
public function run()
{
- $values = [$this, 'giveMeMore'];
+ $values = $this->giveMeMore();
}
public function giveMeMore()
{
return 'more';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `BooleanNotIdenticalToNotIdenticalRector`
- class: [`Rector\CodeQuality\Rector\Identical\BooleanNotIdenticalToNotIdenticalRector`](/../master/rules/code-quality/src/Rector/Identical/BooleanNotIdenticalToNotIdenticalRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Identical/BooleanNotIdenticalToNotIdenticalRector/Fixture)
Negated identical boolean compare to not identical compare (does not apply to non-bool values)
```diff
2019-05-29 13:40:20 +00:00
class SomeClass
{
2019-05-29 13:40:20 +00:00
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
2019-05-29 13:40:20 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CallableThisArrayToAnonymousFunctionRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector`](/../master/rules/code-quality/src/Rector/Array_/CallableThisArrayToAnonymousFunctionRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Array_/CallableThisArrayToAnonymousFunctionRector/Fixture)
2018-12-31 11:50:32 +00:00
Convert [$this, "method"] to proper anonymous function
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
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
### `ChangeArrayPushToArrayAssignRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector`](/../master/rules/code-quality/src/Rector/FuncCall/ChangeArrayPushToArrayAssignRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/ChangeArrayPushToArrayAssignRector/Fixture)
2020-06-16 14:39:45 +00:00
Change `array_push()` to direct variable assign
```diff
class SomeClass
{
public function run()
{
$items = [];
- array_push($items, $item);
+ $items[] = $item;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-15 20:40:44 +00:00
### `CombineIfRector`
- class: [`Rector\CodeQuality\Rector\If_\CombineIfRector`](/../master/rules/code-quality/src/Rector/If_/CombineIfRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/CombineIfRector/Fixture)
2020-01-15 20:40:44 +00:00
Merges nested if statements
```diff
class SomeClass {
public function run()
{
- if ($cond1) {
- if ($cond2) {
- return 'foo';
- }
+ if ($cond1 && $cond2) {
+ return 'foo';
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-15 20:40:44 +00:00
### `CombinedAssignRector`
2018-10-21 22:26:45 +00:00
- class: [`Rector\CodeQuality\Rector\Assign\CombinedAssignRector`](/../master/rules/code-quality/src/Rector/Assign/CombinedAssignRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Assign/CombinedAssignRector/Fixture)
2018-10-21 22:26:45 +00:00
2020-07-07 10:15:52 +00:00
Simplify `$value` = `$value` + 5; assignments to shorter ones
2018-10-21 22:26:45 +00:00
```diff
-$value = $value + 5;
+$value += 5;
2018-10-21 22:26:45 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CompactToVariablesRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\CompactToVariablesRector`](/../master/rules/code-quality/src/Rector/FuncCall/CompactToVariablesRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/CompactToVariablesRector/Fixture)
2019-05-01 23:56:58 +00:00
2020-06-16 14:39:45 +00:00
Change `compact()` call to own array
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
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `CompleteDynamicPropertiesRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector`](/../master/rules/code-quality/src/Rector/Class_/CompleteDynamicPropertiesRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Class_/CompleteDynamicPropertiesRector/Fixture)
2019-05-29 13:40:20 +00:00
Add missing dynamic properties
```diff
class SomeClass
{
+ /**
+ * @var int
+ */
+ public $value;
public function set()
{
$this->value = 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ConsecutiveNullCompareReturnsToNullCoalesceQueueRector`
- class: [`Rector\CodeQuality\Rector\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector`](/../master/rules/code-quality/src/Rector/If_/ConsecutiveNullCompareReturnsToNullCoalesceQueueRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/ConsecutiveNullCompareReturnsToNullCoalesceQueueRector/Fixture)
Change multiple null compares to ?? queue
2019-05-01 23:56:58 +00:00
```diff
class SomeClass
{
public function run()
{
- if (null !== $this->orderItem) {
- return $this->orderItem;
2019-05-29 13:40:20 +00:00
- }
-
- if (null !== $this->orderItemUnit) {
- return $this->orderItemUnit;
- }
-
- return null;
+ return $this->orderItem ?? $this->orderItemUnit;
2019-05-01 23:56:58 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
2019-05-29 13:40:20 +00:00
### `ExplicitBoolCompareRector`
2019-05-19 08:27:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector`](/../master/rules/code-quality/src/Rector/If_/ExplicitBoolCompareRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/ExplicitBoolCompareRector/Fixture)
2019-05-19 08:27:38 +00:00
2019-05-29 13:40:20 +00:00
Make if conditions more explicit
2019-05-19 08:27:38 +00:00
```diff
2019-05-29 13:40:20 +00:00
final class SomeController
2019-05-19 08:27:38 +00:00
{
2019-05-29 13:40:20 +00:00
public function run($items)
2019-05-19 08:27:38 +00:00
{
2019-05-29 13:40:20 +00:00
- if (!count($items)) {
+ if (count($items) === 0) {
return 'no items';
2019-05-19 08:27:38 +00:00
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
2020-01-04 17:49:26 +00:00
### `ForRepeatedCountToOwnVariableRector`
- class: [`Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector`](/../master/rules/code-quality/src/Rector/For_/ForRepeatedCountToOwnVariableRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/For_/ForRepeatedCountToOwnVariableRector/Fixture)
2020-01-04 17:49:26 +00:00
2020-06-16 14:39:45 +00:00
Change `count()` in for function to own variable
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-06-16 16:14:51 +00:00
<br><br>
2020-01-04 17:49:26 +00:00
### `ForToForeachRector`
- class: [`Rector\CodeQuality\Rector\For_\ForToForeachRector`](/../master/rules/code-quality/src/Rector/For_/ForToForeachRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/For_/ForToForeachRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `for()` to `foreach()` where useful
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run($tokens)
2019-05-29 13:40:20 +00:00
{
- 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') {
$previousNonSpaceToken = $this->getPreviousNonSpaceToken($tokens, $i);
if ($previousNonSpaceToken !== null && $previousNonSpaceToken[0] === T_OBJECT_OPERATOR) {
continue;
}
$tokens[$i][0] = self::T_FN;
}
}
2019-05-29 13:40:20 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
2020-01-04 17:49:26 +00:00
### `ForeachItemsAssignToEmptyArrayToAssignRector`
- class: [`Rector\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector`](/../master/rules/code-quality/src/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector/Fixture)
2020-01-04 17:49:26 +00:00
2020-06-21 14:49:47 +00:00
Change `foreach()` items assign to empty array to direct assign
2020-01-04 17:49:26 +00:00
```diff
class SomeClass
{
public function run($items)
{
$items2 = [];
- foreach ($items as $item) {
- $items2[] = $item;
- }
+ $items2 = $items;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-04 17:49:26 +00:00
### `ForeachToInArrayRector`
2018-10-21 22:26:45 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\ForeachToInArrayRector`](/../master/rules/code-quality/src/Rector/Foreach_/ForeachToInArrayRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Foreach_/ForeachToInArrayRector/Fixture)
2018-10-21 22:26:45 +00:00
Simplify `foreach` loops into `in_array` when possible
2018-10-21 22:26:45 +00:00
```diff
-foreach ($items as $item) {
- if ($item === "something") {
- return true;
- }
2019-05-29 13:40:20 +00:00
-}
-
-return false;
+in_array("something", $items, true);
2018-10-21 22:26:45 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `GetClassToInstanceOfRector`
- class: [`Rector\CodeQuality\Rector\Identical\GetClassToInstanceOfRector`](/../master/rules/code-quality/src/Rector/Identical/GetClassToInstanceOfRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Identical/GetClassToInstanceOfRector/Fixture)
2020-06-16 14:39:45 +00:00
Changes comparison with `get_class` to instanceof
```diff
-if (EventsListener::class === get_class($event->job)) { }
+if ($event->job instanceof EventsListener) { }
```
2020-06-16 16:14:51 +00:00
<br><br>
### `InArrayAndArrayKeysToArrayKeyExistsRector`
2019-05-19 08:27:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\InArrayAndArrayKeysToArrayKeyExistsRector`](/../master/rules/code-quality/src/Rector/FuncCall/InArrayAndArrayKeysToArrayKeyExistsRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/InArrayAndArrayKeysToArrayKeyExistsRector/Fixture)
2019-05-19 08:27:38 +00:00
Simplify `in_array` and `array_keys` functions combination into `array_key_exists` when `array_keys` has one argument only
2019-05-19 08:27:38 +00:00
```diff
-in_array("key", array_keys($array), true);
+array_key_exists("key", $array);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `InlineIfToExplicitIfRector`
- class: [`Rector\CodeQuality\Rector\BinaryOp\InlineIfToExplicitIfRector`](/../master/rules/code-quality/src/Rector/BinaryOp/InlineIfToExplicitIfRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/BinaryOp/InlineIfToExplicitIfRector/Fixture)
Change inline if to explicit if
```diff
class SomeClass
{
public function run()
{
$userId = null;
- is_null($userId) && $userId = 5;
+ if (is_null($userId)) {
+ $userId = 5;
+ }
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-27 17:50:00 +00:00
### `IntvalToTypeCastRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\IntvalToTypeCastRector`](/../master/rules/code-quality/src/Rector/FuncCall/IntvalToTypeCastRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/IntvalToTypeCastRector/Fixture)
2019-12-27 17:50:00 +00:00
2020-07-07 10:15:52 +00:00
Change `intval()` to faster and readable (int) `$value`
2019-12-27 17:50:00 +00:00
```diff
class SomeClass
{
public function run($value)
{
- return intval($value);
+ return (int) $value;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-27 17:50:00 +00:00
2019-08-05 21:10:47 +00:00
### `IsAWithStringWithThirdArgumentRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\IsAWithStringWithThirdArgumentRector`](/../master/rules/code-quality/src/Rector/FuncCall/IsAWithStringWithThirdArgumentRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/IsAWithStringWithThirdArgumentRector/Fixture)
2019-08-05 21:10:47 +00:00
2020-06-16 14:39:45 +00:00
Complete missing 3rd argument in case `is_a()` function in case of strings
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
public function __construct(string $value)
{
- return is_a($value, 'stdClass');
+ return is_a($value, 'stdClass', true);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `JoinStringConcatRector`
- class: [`Rector\CodeQuality\Rector\Concat\JoinStringConcatRector`](/../master/rules/code-quality/src/Rector/Concat/JoinStringConcatRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Concat/JoinStringConcatRector/Fixture)
Joins concat of 2 strings, unless the lenght is too long
```diff
class SomeClass
{
2019-05-19 08:27:38 +00:00
public function run()
{
- $name = 'Hi' . ' Tom';
+ $name = 'Hi Tom';
2019-05-19 08:27:38 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
2019-08-05 21:10:47 +00:00
### `RemoveAlwaysTrueConditionSetInConstructorRector`
- class: [`Rector\CodeQuality\Rector\If_\RemoveAlwaysTrueConditionSetInConstructorRector`](/../master/rules/code-quality/src/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture)
2019-08-05 21:10:47 +00:00
If conditions is always true, perform the content right away
```diff
final class SomeClass
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function go()
{
- if ($this->value) {
- return 'yes';
- }
+ return 'yes';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `RemoveSoleValueSprintfRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\RemoveSoleValueSprintfRector`](/../master/rules/code-quality/src/Rector/FuncCall/RemoveSoleValueSprintfRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/RemoveSoleValueSprintfRector/Fixture)
2020-06-16 14:39:45 +00:00
Remove `sprintf()` wrapper if not needed
```diff
class SomeClass
{
public function run()
{
- $value = sprintf('%s', 'hi');
+ $value = 'hi';
$welcome = 'hello';
- $value = sprintf('%s', $welcome);
+ $value = $welcome;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ShortenElseIfRector`
- class: [`Rector\CodeQuality\Rector\If_\ShortenElseIfRector`](/../master/rules/code-quality/src/Rector/If_/ShortenElseIfRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/ShortenElseIfRector/Fixture)
Shortens else/if to elseif
```diff
class SomeClass
{
public function run()
{
if ($cond1) {
return $action1;
- } else {
- if ($cond2) {
- return $action2;
- }
+ } elseif ($cond2) {
+ return $action2;
2019-11-06 23:52:19 +00:00
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyArraySearchRector`
- class: [`Rector\CodeQuality\Rector\Identical\SimplifyArraySearchRector`](/../master/rules/code-quality/src/Rector/Identical/SimplifyArraySearchRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Identical/SimplifyArraySearchRector/Fixture)
2020-06-16 14:39:45 +00:00
Simplify `array_search` to `in_array`
```diff
-array_search("searching", $array) !== false;
+in_array("searching", $array);
```
```diff
-array_search("searching", $array, true) !== false;
+in_array("searching", $array, true);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyBoolIdenticalTrueRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector`](/../master/rules/code-quality/src/Rector/Identical/SimplifyBoolIdenticalTrueRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Identical/SimplifyBoolIdenticalTrueRector/Fixture)
2018-12-31 11:50:32 +00:00
Symplify bool value compare to true or false
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
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
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
### `SimplifyConditionsRector`
2018-10-21 22:26:45 +00:00
- class: [`Rector\CodeQuality\Rector\Identical\SimplifyConditionsRector`](/../master/rules/code-quality/src/Rector/Identical/SimplifyConditionsRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Identical/SimplifyConditionsRector/Fixture)
2018-10-21 22:26:45 +00:00
Simplify conditions
2018-10-21 22:26:45 +00:00
```diff
-if (! ($foo !== 'bar')) {...
+if ($foo === 'bar') {...
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyDeMorganBinaryRector`
- class: [`Rector\CodeQuality\Rector\BinaryOp\SimplifyDeMorganBinaryRector`](/../master/rules/code-quality/src/Rector/BinaryOp/SimplifyDeMorganBinaryRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/BinaryOp/SimplifyDeMorganBinaryRector/Fixture)
Simplify negated conditions with de Morgan theorem
```diff
<?php
$a = 5;
$b = 10;
-$result = !($a > 20 || $b <= 50);
+$result = $a <= 20 && $b > 50;
2018-10-21 22:26:45 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
2019-05-29 13:40:20 +00:00
### `SimplifyDuplicatedTernaryRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\CodeQuality\Rector\Ternary\SimplifyDuplicatedTernaryRector`](/../master/rules/code-quality/src/Rector/Ternary/SimplifyDuplicatedTernaryRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Ternary/SimplifyDuplicatedTernaryRector/Fixture)
2019-03-31 12:25:39 +00:00
2019-05-29 13:40:20 +00:00
Remove ternary that duplicated return value of true : false
2019-03-31 12:25:39 +00:00
```diff
class SomeClass
{
2019-05-29 13:40:20 +00:00
public function run(bool $value, string $name)
2019-03-31 12:25:39 +00:00
{
2019-05-29 13:40:20 +00:00
- $isTrue = $value ? true : false;
+ $isTrue = $value;
$isName = $name ? true : false;
2019-03-31 12:25:39 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
### `SimplifyEmptyArrayCheckRector`
- class: [`Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector`](/../master/rules/code-quality/src/Rector/BooleanAnd/SimplifyEmptyArrayCheckRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/BooleanAnd/SimplifyEmptyArrayCheckRector/Fixture)
Simplify `is_array` and `empty` functions combination into a simple identical check for an empty array
2018-10-21 22:26:45 +00:00
```diff
-is_array($values) && empty($values)
+$values === []
2018-10-21 22:26:45 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
### `SimplifyForeachToArrayFilterRector`
2019-02-18 15:51:24 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToArrayFilterRector`](/../master/rules/code-quality/src/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Foreach_/SimplifyForeachToArrayFilterRector/Fixture)
2019-02-18 15:51:24 +00:00
Simplify foreach with function filtering to array filter
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
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `SimplifyForeachToCoalescingRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToCoalescingRector`](/../master/rules/code-quality/src/Rector/Foreach_/SimplifyForeachToCoalescingRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Foreach_/SimplifyForeachToCoalescingRector/Fixture)
2019-05-29 13:40:20 +00:00
Changes foreach that returns set value to ??
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
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-18 15:51:24 +00:00
### `SimplifyFuncGetArgsCountRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyFuncGetArgsCountRector`](/../master/rules/code-quality/src/Rector/FuncCall/SimplifyFuncGetArgsCountRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/SimplifyFuncGetArgsCountRector/Fixture)
2018-12-31 11:50:32 +00:00
2020-06-16 14:39:45 +00:00
Simplify `count` of `func_get_args()` to `func_num_args()`
```diff
-count(func_get_args());
+func_num_args();
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyIfElseToTernaryRector`
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector`](/../master/rules/code-quality/src/Rector/If_/SimplifyIfElseToTernaryRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/SimplifyIfElseToTernaryRector/Fixture)
Changes if/else for same value as assign to ternary
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
public function run()
{
- 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
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
### `SimplifyIfIssetToNullCoalescingRector`
2018-10-21 22:26:45 +00:00
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfIssetToNullCoalescingRector`](/../master/rules/code-quality/src/Rector/If_/SimplifyIfIssetToNullCoalescingRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/SimplifyIfIssetToNullCoalescingRector/Fixture)
Simplify binary if to null coalesce
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
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-23 18:58:57 +00:00
### `SimplifyIfNotNullReturnRector`
2019-02-18 15:51:24 +00:00
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfNotNullReturnRector`](/../master/rules/code-quality/src/Rector/If_/SimplifyIfNotNullReturnRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/SimplifyIfNotNullReturnRector/Fixture)
2019-02-18 15:51:24 +00:00
Changes redundant null check to instant return
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
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-18 15:51:24 +00:00
### `SimplifyIfReturnBoolRector`
2019-01-22 20:34:38 +00:00
- class: [`Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector`](/../master/rules/code-quality/src/Rector/If_/SimplifyIfReturnBoolRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/If_/SimplifyIfReturnBoolRector/Fixture)
2019-01-22 20:34:38 +00:00
Shortens if return false/true to direct return
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
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-01-22 20:34:38 +00:00
### `SimplifyInArrayValuesRector`
2019-05-19 08:27:38 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyInArrayValuesRector`](/../master/rules/code-quality/src/Rector/FuncCall/SimplifyInArrayValuesRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/SimplifyInArrayValuesRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-16 14:39:45 +00:00
Removes unneeded `array_values()` in `in_array()` call
2019-05-29 13:40:20 +00:00
```diff
-in_array("key", array_values($array), true);
+in_array("key", $array, true);
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `SimplifyRegexPatternRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyRegexPatternRector`](/../master/rules/code-quality/src/Rector/FuncCall/SimplifyRegexPatternRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/SimplifyRegexPatternRector/Fixture)
2019-05-29 13:40:20 +00:00
Simplify regex pattern to known ranges
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
{
public function run($value)
2019-05-19 08:27:38 +00:00
{
- preg_match('#[a-zA-Z0-9+]#', $value);
+ preg_match('#[\w\d+]#', $value);
2019-05-19 08:27:38 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
### `SimplifyStrposLowerRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector`](/../master/rules/code-quality/src/Rector/FuncCall/SimplifyStrposLowerRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/SimplifyStrposLowerRector/Fixture)
Simplify strpos(strtolower(), "...") calls
```diff
-strpos(strtolower($var), "...")"
+stripos($var, "...")"
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyTautologyTernaryRector`
- class: [`Rector\CodeQuality\Rector\Ternary\SimplifyTautologyTernaryRector`](/../master/rules/code-quality/src/Rector/Ternary/SimplifyTautologyTernaryRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Ternary/SimplifyTautologyTernaryRector/Fixture)
Simplify tautology ternary to value
```diff
-$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;
+$value = $fullyQualifiedTypeHint;
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyUselessVariableRector`
- class: [`Rector\CodeQuality\Rector\Return_\SimplifyUselessVariableRector`](/../master/rules/code-quality/src/Rector/Return_/SimplifyUselessVariableRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Return_/SimplifyUselessVariableRector/Fixture)
Removes useless variable assigns
2018-10-23 18:58:57 +00:00
```diff
function () {
- $a = true;
- return $a;
+ return true;
};
2018-10-23 18:58:57 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
### `SingleInArrayToCompareRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector`](/../master/rules/code-quality/src/Rector/FuncCall/SingleInArrayToCompareRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/SingleInArrayToCompareRector/Fixture)
2019-05-01 23:56:58 +00:00
2020-06-16 14:39:45 +00:00
Changes `in_array()` with single element to ===
2019-05-01 23:56:58 +00:00
```diff
class SomeClass
{
public function run()
2019-05-01 23:56:58 +00:00
{
- if (in_array(strtolower($type), ['$this'], true)) {
+ if (strtolower($type) === '$this') {
return strtolower($type);
}
2019-05-01 23:56:58 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
### `SplitListAssignToSeparateLineRector`
- class: [`Rector\CodeQuality\Rector\Assign\SplitListAssignToSeparateLineRector`](/../master/rules/code-quality/src/Rector/Assign/SplitListAssignToSeparateLineRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Assign/SplitListAssignToSeparateLineRector/Fixture)
2020-07-07 10:15:52 +00:00
Splits `[$a, $b] = [5, 10]` scalar assign to standalone lines
```diff
final class SomeClass
{
public function run(): void
{
- [$a, $b] = [1, 2];
+ $a = 1;
+ $b = 2;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `StrlenZeroToIdenticalEmptyStringRector`
- class: [`Rector\CodeQuality\Rector\FuncCall\StrlenZeroToIdenticalEmptyStringRector`](/../master/rules/code-quality/src/Rector/FuncCall/StrlenZeroToIdenticalEmptyStringRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/FuncCall/StrlenZeroToIdenticalEmptyStringRector/Fixture)
2019-08-05 21:10:47 +00:00
2020-06-16 14:39:45 +00:00
Changes `strlen` comparison to 0 to direct empty string compare
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
public function run($value)
{
- $empty = strlen($value) === 0;
+ $empty = $value === '';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `ThrowWithPreviousExceptionRector`
- class: [`Rector\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector`](/../master/rules/code-quality/src/Rector/Catch_/ThrowWithPreviousExceptionRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Catch_/ThrowWithPreviousExceptionRector/Fixture)
2019-08-05 21:10:47 +00:00
When throwing into a catch block, checks that the previous exception is passed to the new throw clause
```diff
class SomeClass
{
public function run()
{
try {
$someCode = 1;
} catch (Throwable $throwable) {
- throw new AnotherException('ups');
+ throw new AnotherException('ups', $throwable->getCode(), $throwable);
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `UnnecessaryTernaryExpressionRector`
2018-12-25 19:55:16 +00:00
- class: [`Rector\CodeQuality\Rector\Ternary\UnnecessaryTernaryExpressionRector`](/../master/rules/code-quality/src/Rector/Ternary/UnnecessaryTernaryExpressionRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Ternary/UnnecessaryTernaryExpressionRector/Fixture)
2018-12-25 19:55:16 +00:00
Remove unnecessary ternary expressions.
2018-12-25 19:55:16 +00:00
```diff
-$foo === $bar ? true : false;
+$foo === $bar;
```
2020-06-16 16:14:51 +00:00
<br><br>
### `UnusedForeachValueToArrayKeysRector`
- class: [`Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector`](/../master/rules/code-quality/src/Rector/Foreach_/UnusedForeachValueToArrayKeysRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Foreach_/UnusedForeachValueToArrayKeysRector/Fixture)
2020-07-07 10:15:52 +00:00
Change foreach with unused `$value` but only `$key,` to `array_keys()`
```diff
class SomeClass
{
public function run()
{
$items = [];
- foreach ($values as $key => $value) {
+ foreach (array_keys($values) as $key) {
$items[$key] = null;
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `UseIdenticalOverEqualWithSameTypeRector`
- class: [`Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector`](/../master/rules/code-quality/src/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php)
- [test fixtures](/../master/rules/code-quality/tests/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector/Fixture)
2019-05-29 13:40:20 +00:00
Use ===/!== over ==/!=, it values have the same type
```diff
class SomeClass
{
2019-05-29 13:40:20 +00:00
public function run(int $firstValue, int $secondValue)
{
2019-05-29 13:40:20 +00:00
- $isSame = $firstValue == $secondValue;
- $isDiffernt = $firstValue != $secondValue;
+ $isSame = $firstValue === $secondValue;
+ $isDiffernt = $firstValue !== $secondValue;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## CodingStyle
2019-05-26 19:26:33 +00:00
2019-08-17 13:06:02 +00:00
### `AddArrayDefaultToArrayPropertyRector`
2019-05-26 19:26:33 +00:00
- class: [`Rector\CodingStyle\Rector\Class_\AddArrayDefaultToArrayPropertyRector`](/../master/rules/coding-style/src/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Class_/AddArrayDefaultToArrayPropertyRector/Fixture)
2019-08-17 13:06:02 +00:00
Adds array default value to property to prevent foreach over null error
2019-05-26 19:26:33 +00:00
```diff
class SomeClass
{
/**
* @var int[]
*/
2019-08-17 13:06:02 +00:00
- private $values;
+ private $values = [];
2019-05-29 13:40:20 +00:00
2019-08-17 13:06:02 +00:00
public function isEmpty()
{
2019-08-17 13:06:02 +00:00
- return $this->values === null;
+ return $this->values === [];
}
}
2019-05-26 19:26:33 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-26 19:26:33 +00:00
### `AnnotateThrowablesRector`
- class: [`Rector\CodingStyle\Rector\Throw_\AnnotateThrowablesRector`](/../master/rules/coding-style/src/Rector/Throw_/AnnotateThrowablesRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Throw_/AnnotateThrowablesRector/Fixture)
Adds @throws DocBlock comments to methods that thrwo \Throwables.
```diff
class RootExceptionInMethodWithDocblock
{
/**
* This is a comment.
*
* @param int $code
+ * @throws \RuntimeException
*/
public function throwException(int $code)
{
throw new \RuntimeException('', $code);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `BinarySwitchToIfElseRector`
- class: [`Rector\CodingStyle\Rector\Switch_\BinarySwitchToIfElseRector`](/../master/rules/coding-style/src/Rector/Switch_/BinarySwitchToIfElseRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Switch_/BinarySwitchToIfElseRector/Fixture)
Changes switch with 2 options to if-else
```diff
-switch ($foo) {
- case 'my string':
- $result = 'ok';
- break;
-
- default:
- $result = 'not ok';
+if ($foo == 'my string') {
+ $result = 'ok;
+} else {
+ $result = 'not ok';
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CallUserFuncCallToVariadicRector`
- class: [`Rector\CodingStyle\Rector\FuncCall\CallUserFuncCallToVariadicRector`](/../master/rules/coding-style/src/Rector/FuncCall/CallUserFuncCallToVariadicRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/FuncCall/CallUserFuncCallToVariadicRector/Fixture)
Replace call_user_func_call with variadic
```diff
class SomeClass
{
public function run()
{
- call_user_func_array('some_function', $items);
+ some_function(...$items);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CamelCaseFunctionNamingToUnderscoreRector`
- class: [`Rector\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector`](/../master/rules/coding-style/src/Rector/Function_/CamelCaseFunctionNamingToUnderscoreRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Function_/CamelCaseFunctionNamingToUnderscoreRector/Fixture)
Change CamelCase naming of functions to under_score naming
```diff
-function someCamelCaseFunction()
+function some_camel_case_function()
{
}
-someCamelCaseFunction();
+some_camel_case_function();
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CatchExceptionNameMatchingTypeRector`
- class: [`Rector\CodingStyle\Rector\Catch_\CatchExceptionNameMatchingTypeRector`](/../master/rules/coding-style/src/Rector/Catch_/CatchExceptionNameMatchingTypeRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Catch_/CatchExceptionNameMatchingTypeRector/Fixture)
Type and name of catch exception should match
```diff
2019-05-29 13:40:20 +00:00
class SomeClass
{
public function run()
{
try {
// ...
- } catch (SomeException $typoException) {
- $typoException->getMessage();
+ } catch (SomeException $someException) {
+ $someException->getMessage();
2019-05-29 13:40:20 +00:00
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ConsistentImplodeRector`
- class: [`Rector\CodingStyle\Rector\FuncCall\ConsistentImplodeRector`](/../master/rules/coding-style/src/Rector/FuncCall/ConsistentImplodeRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/FuncCall/ConsistentImplodeRector/Fixture)
2020-06-16 14:39:45 +00:00
Changes various `implode` forms to consistent one
```diff
class SomeClass
{
public function run(array $items)
{
- $itemsAsStrings = implode($items);
- $itemsAsStrings = implode($items, '|');
+ $itemsAsStrings = implode('', $items);
+ $itemsAsStrings = implode('|', $items);
$itemsAsStrings = implode('|', $items);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ConsistentPregDelimiterRector`
- class: [`Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector`](/../master/rules/coding-style/src/Rector/FuncCall/ConsistentPregDelimiterRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/FuncCall/ConsistentPregDelimiterRector/Fixture)
Replace PREG delimiter with configured one
```diff
2019-03-09 13:24:30 +00:00
class SomeClass
{
2019-03-09 13:24:30 +00:00
public function run()
{
- preg_match('~value~', $value);
- preg_match_all('~value~im', $value);
+ preg_match('#value#', $value);
+ preg_match_all('#value#im', $value);
2019-03-09 13:24:30 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `EncapsedStringsToSprintfRector`
- class: [`Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector`](/../master/rules/coding-style/src/Rector/Encapsed/EncapsedStringsToSprintfRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Encapsed/EncapsedStringsToSprintfRector/Fixture)
2019-08-05 21:10:47 +00:00
2020-06-16 14:39:45 +00:00
Convert enscaped {$string} to more readable `sprintf`
2019-08-05 21:10:47 +00:00
```diff
final class SomeClass
{
public function run(string $format)
{
- return "Unsupported format {$format}";
+ return sprintf('Unsupported format %s', $format);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `FollowRequireByDirRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\CodingStyle\Rector\Include_\FollowRequireByDirRector`](/../master/rules/coding-style/src/Rector/Include_/FollowRequireByDirRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Include_/FollowRequireByDirRector/Fixture)
2019-05-01 23:56:58 +00:00
include/require should be followed by absolute path
2019-05-01 23:56:58 +00:00
```diff
class SomeClass
{
public function run()
2019-05-01 23:56:58 +00:00
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
2019-05-01 23:56:58 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
2019-10-15 14:46:31 +00:00
### `FunctionCallToConstantRector`
- class: [`Rector\CodingStyle\Rector\FuncCall\FunctionCallToConstantRector`](/../master/rules/coding-style/src/Rector/FuncCall/FunctionCallToConstantRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/FuncCall/FunctionCallToConstantRector/Fixture)
2019-10-15 14:46:31 +00:00
Changes use of function calls to use constants
```diff
class SomeClass
{
public function run()
{
- $value = php_sapi_name();
+ $value = PHP_SAPI;
}
}
```
```diff
class SomeClass
{
public function run()
{
- $value = pi();
+ $value = M_PI;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `IdenticalFalseToBooleanNotRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\CodingStyle\Rector\Identical\IdenticalFalseToBooleanNotRector`](/../master/rules/coding-style/src/Rector/Identical/IdenticalFalseToBooleanNotRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Identical/IdenticalFalseToBooleanNotRector/Fixture)
2019-05-01 23:56:58 +00:00
Changes === false to negate !
```diff
2019-05-29 13:40:20 +00:00
-if ($something === false) {}
+if (! $something) {}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `MakeInheritedMethodVisibilitySameAsParentRector`
- class: [`Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector`](/../master/rules/coding-style/src/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector/Fixture)
Make method visibility same as parent one
```diff
class ChildClass extends ParentClass
{
- public function run()
+ protected function run()
{
}
}
class ParentClass
{
protected function run()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `ManualJsonStringToJsonEncodeArrayRector`
- class: [`Rector\CodingStyle\Rector\String_\ManualJsonStringToJsonEncodeArrayRector`](/../master/rules/coding-style/src/Rector/String_/ManualJsonStringToJsonEncodeArrayRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/String_/ManualJsonStringToJsonEncodeArrayRector/Fixture)
2019-08-05 21:10:47 +00:00
Add extra space before new assign set
```diff
final class SomeClass
{
public function run()
{
- $someJsonAsString = '{"role_name":"admin","numberz":{"id":"10"}}';
+ $data = [
+ 'role_name' => 'admin',
+ 'numberz' => ['id' => 10]
+ ];
+
2019-08-17 13:06:02 +00:00
+ $someJsonAsString = Nette\Utils\Json::encode($data);
2019-08-05 21:10:47 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `NewlineBeforeNewAssignSetRector`
- class: [`Rector\CodingStyle\Rector\ClassMethod\NewlineBeforeNewAssignSetRector`](/../master/rules/coding-style/src/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/ClassMethod/NewlineBeforeNewAssignSetRector/Fixture)
2019-08-05 21:10:47 +00:00
Add extra space before new assign set
```diff
final class SomeClass
{
public function run()
{
$value = new Value;
$value->setValue(5);
+
$value2 = new Value;
$value2->setValue(1);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `NullableCompareToNullRector`
- class: [`Rector\CodingStyle\Rector\If_\NullableCompareToNullRector`](/../master/rules/coding-style/src/Rector/If_/NullableCompareToNullRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/If_/NullableCompareToNullRector/Fixture)
Changes negate of empty comparison of nullable value to explicit === or !== compare
```diff
/** @var stdClass|null $value */
-if ($value) {
+if ($value !== null) {
}
-if (!$value) {
+if ($value === null) {
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `PreferThisOrSelfMethodCallRector`
- class: [`Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector`](/../master/rules/coding-style/src/Rector/MethodCall/PreferThisOrSelfMethodCallRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/MethodCall/PreferThisOrSelfMethodCallRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-07-07 10:15:52 +00:00
Changes `$this->...` to self:: or vise versa for specific types
2019-09-25 08:49:53 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(PreferThisOrSelfMethodCallRector::class)
->arg('PHPUnit\TestCase', 'self');
};
2019-09-25 08:49:53 +00:00
```
```diff
class SomeClass extends PHPUnit\TestCase
{
public function run()
{
- $this->assertThis();
+ self::assertThis();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RemoveDoubleUnderscoreInMethodNameRector`
- class: [`Rector\CodingStyle\Rector\ClassMethod\RemoveDoubleUnderscoreInMethodNameRector`](/../master/rules/coding-style/src/Rector/ClassMethod/RemoveDoubleUnderscoreInMethodNameRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/ClassMethod/RemoveDoubleUnderscoreInMethodNameRector/Fixture)
Non-magic PHP object methods cannot start with "__"
```diff
class SomeClass
{
- public function __getName($anotherObject)
+ public function getName($anotherObject)
{
- $anotherObject->__getSurname();
+ $anotherObject->getSurname();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveUnusedAliasRector`
- class: [`Rector\CodingStyle\Rector\Use_\RemoveUnusedAliasRector`](/../master/rules/coding-style/src/Rector/Use_/RemoveUnusedAliasRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Use_/RemoveUnusedAliasRector/Fixture)
Removes unused use aliases. Keep annotation aliases like "Doctrine\ORM\Mapping as ORM" to keep convention format
```diff
-use Symfony\Kernel as BaseKernel;
+use Symfony\Kernel;
-class SomeClass extends BaseKernel
+class SomeClass extends Kernel
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ReturnArrayClassMethodToYieldRector`
- class: [`Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector`](/../master/rules/coding-style/src/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector/Fixture)
2019-09-21 22:14:49 +00:00
Turns array return to yield return in specific type and method
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ReturnArrayClassMethodToYieldRector::class)
->arg('EventSubscriberInterface', ['getSubscribedEvents']);
};
```
```diff
class SomeEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
2019-09-21 22:14:49 +00:00
- return ['event' => 'callback'];
+ yield 'event' => 'callback';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimpleArrayCallableToStringRector`
- class: [`Rector\CodingStyle\Rector\FuncCall\SimpleArrayCallableToStringRector`](/../master/rules/coding-style/src/Rector/FuncCall/SimpleArrayCallableToStringRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/FuncCall/SimpleArrayCallableToStringRector/Fixture)
Changes redundant anonymous bool functions to simple calls
```diff
-$paths = array_filter($paths, function ($path): bool {
- return is_dir($path);
-});
+array_filter($paths, "is_dir");
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `SplitDoubleAssignRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\CodingStyle\Rector\Assign\SplitDoubleAssignRector`](/../master/rules/coding-style/src/Rector/Assign/SplitDoubleAssignRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Assign/SplitDoubleAssignRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-16 14:39:45 +00:00
Split multiple inline assigns to `each` own lines default value, to prevent undefined array issues
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
- $one = $two = 1;
+ $one = 1;
+ $two = 1;
2019-05-29 13:40:20 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-05-01 23:56:58 +00:00
### `SplitGroupedConstantsAndPropertiesRector`
- class: [`Rector\CodingStyle\Rector\ClassConst\SplitGroupedConstantsAndPropertiesRector`](/../master/rules/coding-style/src/Rector/ClassConst/SplitGroupedConstantsAndPropertiesRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/ClassConst/SplitGroupedConstantsAndPropertiesRector/Fixture)
2019-05-01 23:56:58 +00:00
Separate constant and properties to own lines
```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;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
### `SplitGroupedUseImportsRector`
- class: [`Rector\CodingStyle\Rector\Use_\SplitGroupedUseImportsRector`](/../master/rules/coding-style/src/Rector/Use_/SplitGroupedUseImportsRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Use_/SplitGroupedUseImportsRector/Fixture)
Split grouped use imports and trait statements to standalone lines
```diff
-use A, B;
+use A;
+use B;
class SomeClass
{
- use SomeTrait, AnotherTrait;
+ use SomeTrait;
+ use AnotherTrait;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SplitStringClassConstantToClassConstFetchRector`
- class: [`Rector\CodingStyle\Rector\String_\SplitStringClassConstantToClassConstFetchRector`](/../master/rules/coding-style/src/Rector/String_/SplitStringClassConstantToClassConstFetchRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/String_/SplitStringClassConstantToClassConstFetchRector/Fixture)
Separate class constant in a string to class constant fetch and string
```diff
class SomeClass
{
const HI = true;
}
class AnotherClass
{
public function get()
{
- return 'SomeClass::HI';
+ return SomeClass::class . '::HI';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `StrictArraySearchRector`
- class: [`Rector\CodingStyle\Rector\FuncCall\StrictArraySearchRector`](/../master/rules/coding-style/src/Rector/FuncCall/StrictArraySearchRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/FuncCall/StrictArraySearchRector/Fixture)
2020-06-16 14:39:45 +00:00
Makes `array_search` search for identical elements
```diff
-array_search($value, $items);
+array_search($value, $items, true);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SymplifyQuoteEscapeRector`
- class: [`Rector\CodingStyle\Rector\String_\SymplifyQuoteEscapeRector`](/../master/rules/coding-style/src/Rector/String_/SymplifyQuoteEscapeRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/String_/SymplifyQuoteEscapeRector/Fixture)
2018-10-21 22:26:45 +00:00
2020-01-03 18:20:13 +00:00
Prefer quote that are not inside the string
2018-10-21 22:26:45 +00:00
```diff
class SomeClass
{
public function run()
{
- $name = "\" Tom";
- $name = '\' Sara';
+ $name = '" Tom';
+ $name = "' Sara";
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `TernaryConditionVariableAssignmentRector`
- class: [`Rector\CodingStyle\Rector\Ternary\TernaryConditionVariableAssignmentRector`](/../master/rules/coding-style/src/Rector/Ternary/TernaryConditionVariableAssignmentRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Ternary/TernaryConditionVariableAssignmentRector/Fixture)
Assign outcome of ternary condition to variable, where applicable
```diff
function ternary($value)
{
- $value ? $a = 1 : $a = 0;
+ $a = $value ? 1 : 0;
}
```
<br><br>
### `UnderscoreToPascalCasePropertyNameRector`
2020-05-29 10:41:25 +00:00
- class: [`Rector\CodingStyle\Rector\Property\UnderscoreToPascalCasePropertyNameRector`](/../master/rules/coding-style/src/Rector/Property/UnderscoreToPascalCasePropertyNameRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Property/UnderscoreToPascalCasePropertyNameRector/Fixture)
Change under_score names to pascalCase
```diff
final class SomeClass
{
- public $property_name;
+ public $propertyName;
public function run($a)
{
- $this->property_name = 5;
+ $this->propertyName = 5;
}
}
```
<br><br>
### `UnderscoreToPascalCaseVariableNameRector`
- class: [`Rector\CodingStyle\Rector\Variable\UnderscoreToPascalCaseVariableNameRector`](/../master/rules/coding-style/src/Rector/Variable/UnderscoreToPascalCaseVariableNameRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Variable/UnderscoreToPascalCaseVariableNameRector/Fixture)
2020-05-29 10:41:25 +00:00
Change under_score names to pascalCase
```diff
final class SomeClass
{
- public function run($a_b)
+ public function run($aB)
{
- $some_value = $a_b;
+ $someValue = $aB;
2020-05-29 10:41:25 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-29 10:41:25 +00:00
### `UseClassKeywordForClassNameResolutionRector`
- class: [`Rector\CodingStyle\Rector\String_\UseClassKeywordForClassNameResolutionRector`](/../master/rules/coding-style/src/Rector/String_/UseClassKeywordForClassNameResolutionRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/String_/UseClassKeywordForClassNameResolutionRector/Fixture)
Use `class` keyword for class name resolution in string instead of hardcoded string reference
```diff
-$value = 'App\SomeClass::someMethod()';
+$value = \App\SomeClass . '::someMethod()';
```
<br><br>
### `UseIncrementAssignRector`
- class: [`Rector\CodingStyle\Rector\Assign\UseIncrementAssignRector`](/../master/rules/coding-style/src/Rector/Assign/UseIncrementAssignRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Assign/UseIncrementAssignRector/Fixture)
Use ++ increment instead of `$var += 1`
```diff
class SomeClass
{
public function run()
{
- $style += 1;
+ ++$style
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `VarConstantCommentRector`
- class: [`Rector\CodingStyle\Rector\ClassConst\VarConstantCommentRector`](/../master/rules/coding-style/src/Rector/ClassConst/VarConstantCommentRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/ClassConst/VarConstantCommentRector/Fixture)
2020-06-16 14:39:45 +00:00
`Constant` should have a @var comment with type
```diff
class SomeClass
{
+ /**
+ * @var string
+ */
const HI = 'hi';
}
2018-10-21 22:26:45 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
2019-10-15 14:46:31 +00:00
### `VersionCompareFuncCallToConstantRector`
- class: [`Rector\CodingStyle\Rector\FuncCall\VersionCompareFuncCallToConstantRector`](/../master/rules/coding-style/src/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/FuncCall/VersionCompareFuncCallToConstantRector/Fixture)
2019-10-15 14:46:31 +00:00
Changes use of call to version compare function to use of PHP version constant
```diff
class SomeClass
{
public function run()
{
- version_compare(PHP_VERSION, '5.3.0', '<');
+ PHP_VERSION_ID < 50300;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `WrapEncapsedVariableInCurlyBracesRector`
- class: [`Rector\CodingStyle\Rector\Encapsed\WrapEncapsedVariableInCurlyBracesRector`](/../master/rules/coding-style/src/Rector/Encapsed/WrapEncapsedVariableInCurlyBracesRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/Encapsed/WrapEncapsedVariableInCurlyBracesRector/Fixture)
Wrap encapsed variables in curly braces
```diff
function run($world)
{
- echo "Hello $world!"
+ echo "Hello {$world}!"
}
```
<br><br>
2019-05-29 13:40:20 +00:00
### `YieldClassMethodToArrayClassMethodRector`
- class: [`Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector`](/../master/rules/coding-style/src/Rector/ClassMethod/YieldClassMethodToArrayClassMethodRector.php)
- [test fixtures](/../master/rules/coding-style/tests/Rector/ClassMethod/YieldClassMethodToArrayClassMethodRector/Fixture)
2019-05-29 13:40:20 +00:00
Turns yield return to array return in specific type and method
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(YieldClassMethodToArrayClassMethodRector::class)
->arg('EventSubscriberInterface', ['getSubscribedEvents']);
};
2019-05-29 13:40:20 +00:00
```
```diff
2019-05-29 13:40:20 +00:00
class SomeEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- yield 'event' => 'callback';
+ return ['event' => 'callback'];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## DeadCode
### `RemoveAlwaysTrueIfConditionRector`
- class: [`Rector\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector`](/../master/rules/dead-code/src/Rector/If_/RemoveAlwaysTrueIfConditionRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/If_/RemoveAlwaysTrueIfConditionRector/Fixture)
Remove if condition that is always true
```diff
final class SomeClass
{
public function go()
{
- if (1 === 1) {
- return 'yes';
- }
+ return 'yes';
return 'no';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveAndTrueRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\DeadCode\Rector\BooleanAnd\RemoveAndTrueRector`](/../master/rules/dead-code/src/Rector/BooleanAnd/RemoveAndTrueRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/BooleanAnd/RemoveAndTrueRector/Fixture)
2019-05-29 13:40:20 +00:00
Remove and true that has no added value
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run()
2019-05-29 13:40:20 +00:00
{
- return true && 5 === 1;
+ return 5 === 1;
2019-05-29 13:40:20 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveAssignOfVoidReturnFunctionRector`
- class: [`Rector\DeadCode\Rector\Assign\RemoveAssignOfVoidReturnFunctionRector`](/../master/rules/dead-code/src/Rector/Assign/RemoveAssignOfVoidReturnFunctionRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Assign/RemoveAssignOfVoidReturnFunctionRector/Fixture)
Remove assign of void function/method to variable
```diff
class SomeClass
{
public function run()
{
- $value = $this->getOne();
+ $this->getOne();
}
private function getOne(): void
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveCodeAfterReturnRector`
- class: [`Rector\DeadCode\Rector\FunctionLike\RemoveCodeAfterReturnRector`](/../master/rules/dead-code/src/Rector/FunctionLike/RemoveCodeAfterReturnRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/FunctionLike/RemoveCodeAfterReturnRector/Fixture)
Remove dead code after return statement
```diff
class SomeClass
{
public function run(int $a)
{
return $a;
- $a++;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-06-06 13:01:53 +00:00
### `RemoveConcatAutocastRector`
- class: [`Rector\DeadCode\Rector\Concat\RemoveConcatAutocastRector`](/../master/rules/dead-code/src/Rector/Concat/RemoveConcatAutocastRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Concat/RemoveConcatAutocastRector/Fixture)
2019-06-06 13:01:53 +00:00
Remove (string) casting when it comes to concat, that does this by default
```diff
class SomeConcatingClass
{
public function run($value)
{
- return 'hi ' . (string) $value;
+ return 'hi ' . $value;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-06-06 13:01:53 +00:00
### `RemoveDeadConstructorRector`
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveDeadConstructorRector`](/../master/rules/dead-code/src/Rector/ClassMethod/RemoveDeadConstructorRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassMethod/RemoveDeadConstructorRector/Fixture)
Remove empty constructor
```diff
class SomeClass
{
- public function __construct()
- {
- }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-25 19:55:16 +00:00
### `RemoveDeadIfForeachForRector`
2018-12-25 19:55:16 +00:00
- class: [`Rector\DeadCode\Rector\For_\RemoveDeadIfForeachForRector`](/../master/rules/dead-code/src/Rector/For_/RemoveDeadIfForeachForRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/For_/RemoveDeadIfForeachForRector/Fixture)
2018-12-25 19:55:16 +00:00
Remove if, foreach and for that does not do anything
2018-12-25 19:55:16 +00:00
```diff
2019-05-29 13:40:20 +00:00
class SomeClass
{
public function run($someObject)
{
$value = 5;
- if ($value) {
- }
-
if ($someObject->run()) {
- }
-
- foreach ($values as $value) {
}
return $value;
}
}
2018-12-25 19:55:16 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-25 19:55:16 +00:00
### `RemoveDeadRecursiveClassMethodRector`
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveDeadRecursiveClassMethodRector`](/../master/rules/dead-code/src/Rector/ClassMethod/RemoveDeadRecursiveClassMethodRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassMethod/RemoveDeadRecursiveClassMethodRector/Fixture)
Remove unused public method that only calls itself recursively
```diff
class SomeClass
{
- public function run()
- {
- return $this->run();
- }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `RemoveDeadReturnRector`
2018-12-25 19:55:16 +00:00
- class: [`Rector\DeadCode\Rector\FunctionLike\RemoveDeadReturnRector`](/../master/rules/dead-code/src/Rector/FunctionLike/RemoveDeadReturnRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/FunctionLike/RemoveDeadReturnRector/Fixture)
2018-12-25 19:55:16 +00:00
2019-05-29 13:40:20 +00:00
Remove last return in the functions, since does not do anything
2018-12-25 19:55:16 +00:00
```diff
2019-05-29 13:40:20 +00:00
class SomeClass
2018-12-25 19:55:16 +00:00
{
2019-05-29 13:40:20 +00:00
public function run()
{
$shallWeDoThis = true;
if ($shallWeDoThis) {
return;
}
-
- return;
}
2018-12-25 19:55:16 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-25 19:55:16 +00:00
### `RemoveDeadStmtRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\DeadCode\Rector\Stmt\RemoveDeadStmtRector`](/../master/rules/dead-code/src/Rector/Stmt/RemoveDeadStmtRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Stmt/RemoveDeadStmtRector/Fixture)
2018-12-31 11:50:32 +00:00
Removes dead code statements
2018-12-31 11:50:32 +00:00
```diff
-$value = 5;
-$value;
+$value = 5;
2018-12-31 11:50:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
### `RemoveDeadTryCatchRector`
- class: [`Rector\DeadCode\Rector\TryCatch\RemoveDeadTryCatchRector`](/../master/rules/dead-code/src/Rector/TryCatch/RemoveDeadTryCatchRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/TryCatch/RemoveDeadTryCatchRector/Fixture)
Remove dead try/catch
```diff
class SomeClass
{
public function run()
{
- try {
- // some code
- }
- catch (Throwable $throwable) {
- throw $throwable;
- }
+ // some code
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveDeadZeroAndOneOperationRector`
- class: [`Rector\DeadCode\Rector\Plus\RemoveDeadZeroAndOneOperationRector`](/../master/rules/dead-code/src/Rector/Plus/RemoveDeadZeroAndOneOperationRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Plus/RemoveDeadZeroAndOneOperationRector/Fixture)
Remove operation with 1 and 0, that have no effect on the value
```diff
class SomeClass
{
public function run()
{
- $value = 5 * 1;
- $value = 5 + 0;
+ $value = 5;
+ $value = 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveDefaultArgumentValueRector`
2019-03-09 13:24:30 +00:00
- class: [`Rector\DeadCode\Rector\MethodCall\RemoveDefaultArgumentValueRector`](/../master/rules/dead-code/src/Rector/MethodCall/RemoveDefaultArgumentValueRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/MethodCall/RemoveDefaultArgumentValueRector/Fixture)
2019-03-09 13:24:30 +00:00
Remove argument value, if it is the same as default value
2019-03-09 13:24:30 +00:00
```diff
class SomeClass
{
2019-05-29 13:40:20 +00:00
public function run()
{
- $this->runWithDefault([]);
- $card = self::runWithStaticDefault([]);
+ $this->runWithDefault();
+ $card = self::runWithStaticDefault();
2019-05-29 13:40:20 +00:00
}
2019-02-21 14:36:16 +00:00
public function runWithDefault($items = [])
{
return $items;
}
2019-02-21 14:36:16 +00:00
public function runStaticWithDefault($cards = [])
2019-02-21 14:36:16 +00:00
{
return $cards;
2019-02-21 14:36:16 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
### `RemoveDelegatingParentCallRector`
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveDelegatingParentCallRector`](/../master/rules/dead-code/src/Rector/ClassMethod/RemoveDelegatingParentCallRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassMethod/RemoveDelegatingParentCallRector/Fixture)
Removed dead parent call, that does not change anything
```diff
class SomeClass
{
- public function prettyPrint(array $stmts): string
- {
- return parent::prettyPrint($stmts);
- }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveDoubleAssignRector`
2019-02-18 15:51:24 +00:00
- class: [`Rector\DeadCode\Rector\Assign\RemoveDoubleAssignRector`](/../master/rules/dead-code/src/Rector/Assign/RemoveDoubleAssignRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Assign/RemoveDoubleAssignRector/Fixture)
2019-02-18 15:51:24 +00:00
Simplify useless double assigns
2019-02-18 15:51:24 +00:00
```diff
-$value = 1;
$value = 1;
2019-02-18 15:51:24 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-18 15:51:24 +00:00
### `RemoveDuplicatedArrayKeyRector`
2019-05-19 08:27:38 +00:00
- class: [`Rector\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector`](/../master/rules/dead-code/src/Rector/Array_/RemoveDuplicatedArrayKeyRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Array_/RemoveDuplicatedArrayKeyRector/Fixture)
2019-05-19 08:27:38 +00:00
2020-06-16 16:13:37 +00:00
Remove duplicated `key` in defined arrays.
2019-05-19 08:27:38 +00:00
```diff
$item = [
- 1 => 'A',
1 => 'B'
];
2019-05-19 08:27:38 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
2019-08-05 21:10:47 +00:00
### `RemoveDuplicatedCaseInSwitchRector`
- class: [`Rector\DeadCode\Rector\Switch_\RemoveDuplicatedCaseInSwitchRector`](/../master/rules/dead-code/src/Rector/Switch_/RemoveDuplicatedCaseInSwitchRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Switch_/RemoveDuplicatedCaseInSwitchRector/Fixture)
2019-08-05 21:10:47 +00:00
2 following switch keys with identical will be reduced to one result
```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;
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `RemoveDuplicatedIfReturnRector`
- class: [`Rector\DeadCode\Rector\FunctionLike\RemoveDuplicatedIfReturnRector`](/../master/rules/dead-code/src/Rector/FunctionLike/RemoveDuplicatedIfReturnRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/FunctionLike/RemoveDuplicatedIfReturnRector/Fixture)
Remove duplicated if stmt with return in function/method body
```diff
class SomeClass
{
public function run($value)
{
if ($value) {
return true;
}
$value2 = 100;
-
- if ($value) {
- return true;
- }
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveDuplicatedInstanceOfRector`
- class: [`Rector\DeadCode\Rector\Instanceof_\RemoveDuplicatedInstanceOfRector`](/../master/rules/dead-code/src/Rector/Instanceof_/RemoveDuplicatedInstanceOfRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Instanceof_/RemoveDuplicatedInstanceOfRector/Fixture)
Remove duplicated instanceof in one call
```diff
class SomeClass
{
public function run($value)
{
- $isIt = $value instanceof A || $value instanceof A;
- $isIt = $value instanceof A && $value instanceof A;
+ $isIt = $value instanceof A;
+ $isIt = $value instanceof A;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveEmptyClassMethodRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector`](/../master/rules/dead-code/src/Rector/ClassMethod/RemoveEmptyClassMethodRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassMethod/RemoveEmptyClassMethodRector/Fixture)
2019-03-31 12:25:39 +00:00
Remove empty method calls not required by parents
2019-03-31 12:25:39 +00:00
```diff
class OrphanClass
{
- public function __construct()
- {
- }
}
2019-03-31 12:25:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
2019-08-24 11:08:59 +00:00
### `RemoveNullPropertyInitializationRector`
- class: [`Rector\DeadCode\Rector\Property\RemoveNullPropertyInitializationRector`](/../master/rules/dead-code/src/Rector/Property/RemoveNullPropertyInitializationRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Property/RemoveNullPropertyInitializationRector/Fixture)
2019-08-24 11:08:59 +00:00
Remove initialization with null value from property declarations
```diff
class SunshineCommand extends ParentClassWithNewConstructor
{
- private $myVar = null;
+ private $myVar;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-24 11:08:59 +00:00
### `RemoveOverriddenValuesRector`
2018-12-25 19:55:16 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveOverriddenValuesRector`](/../master/rules/dead-code/src/Rector/ClassMethod/RemoveOverriddenValuesRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassMethod/RemoveOverriddenValuesRector/Fixture)
2018-12-25 19:55:16 +00:00
Remove initial assigns of overridden values
2018-12-25 19:55:16 +00:00
```diff
2019-05-29 13:40:20 +00:00
final class SomeController
2018-12-25 19:55:16 +00:00
{
2019-05-29 13:40:20 +00:00
public function run()
{
- $directories = [];
$possibleDirectories = [];
$directories = array_filter($possibleDirectories, 'file_exists');
2019-05-29 13:40:20 +00:00
}
2018-12-25 19:55:16 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-25 19:55:16 +00:00
### `RemoveParentCallWithoutParentRector`
2018-12-25 19:55:16 +00:00
- class: [`Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector`](/../master/rules/dead-code/src/Rector/StaticCall/RemoveParentCallWithoutParentRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/StaticCall/RemoveParentCallWithoutParentRector/Fixture)
2018-12-25 19:55:16 +00:00
Remove unused parent call with no parent class
2018-12-25 19:55:16 +00:00
```diff
class OrphanClass
2019-05-29 13:40:20 +00:00
{
public function __construct()
{
- parent::__construct();
}
2019-05-29 13:40:20 +00:00
}
2018-12-25 19:55:16 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-25 19:55:16 +00:00
2019-08-17 13:06:02 +00:00
### `RemoveSetterOnlyPropertyAndMethodCallRector`
- class: [`Rector\DeadCode\Rector\Class_\RemoveSetterOnlyPropertyAndMethodCallRector`](/../master/rules/dead-code/src/Rector/Class_/RemoveSetterOnlyPropertyAndMethodCallRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Class_/RemoveSetterOnlyPropertyAndMethodCallRector/Fixture)
2019-08-17 13:06:02 +00:00
Removes method that set values that are never used
```diff
class SomeClass
{
- private $name;
-
- public function setName($name)
- {
- $this->name = $name;
- }
}
class ActiveOnlySetter
{
public function run()
{
$someClass = new SomeClass();
- $someClass->setName('Tom');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-17 13:06:02 +00:00
### `RemoveUnreachableStatementRector`
- class: [`Rector\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector`](/../master/rules/dead-code/src/Rector/Stmt/RemoveUnreachableStatementRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Stmt/RemoveUnreachableStatementRector/Fixture)
Remove unreachable statements
```diff
class SomeClass
{
public function run()
{
return 5;
-
- $removeMe = 10;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveUnusedAssignVariableRector`
- class: [`Rector\DeadCode\Rector\Assign\RemoveUnusedAssignVariableRector`](/../master/rules/dead-code/src/Rector/Assign/RemoveUnusedAssignVariableRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Assign/RemoveUnusedAssignVariableRector/Fixture)
Remove assigned unused variable
```diff
class SomeClass
{
public function run()
{
- $value = $this->process();
+ $this->process();
}
public function process()
{
// something going on
return 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveUnusedClassConstantRector`
- class: [`Rector\DeadCode\Rector\ClassConst\RemoveUnusedClassConstantRector`](/../master/rules/dead-code/src/Rector/ClassConst/RemoveUnusedClassConstantRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassConst/RemoveUnusedClassConstantRector/Fixture)
Remove unused class constants
```diff
class SomeClass
{
- private const SOME_CONST = 'dead';
-
public function run()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-04 23:18:57 +00:00
### `RemoveUnusedClassesRector`
- class: [`Rector\DeadCode\Rector\Class_\RemoveUnusedClassesRector`](/../master/rules/dead-code/src/Rector/Class_/RemoveUnusedClassesRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Class_/RemoveUnusedClassesRector/Fixture)
2020-01-04 23:18:57 +00:00
Remove unused classes without interface
```diff
interface SomeInterface
{
}
class SomeClass implements SomeInterface
{
public function run($items)
{
return null;
}
-}
-
-class NowhereUsedClass
-{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-04 23:18:57 +00:00
2019-08-05 21:10:47 +00:00
### `RemoveUnusedDoctrineEntityMethodAndPropertyRector`
- class: [`Rector\DeadCode\Rector\Class_\RemoveUnusedDoctrineEntityMethodAndPropertyRector`](/../master/rules/dead-code/src/Rector/Class_/RemoveUnusedDoctrineEntityMethodAndPropertyRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Class_/RemoveUnusedDoctrineEntityMethodAndPropertyRector/Fixture)
2019-08-05 21:10:47 +00:00
Removes unused methods and properties from Doctrine entity classes
```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;
- }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `RemoveUnusedForeachKeyRector`
2019-05-19 08:27:38 +00:00
- class: [`Rector\DeadCode\Rector\Foreach_\RemoveUnusedForeachKeyRector`](/../master/rules/dead-code/src/Rector/Foreach_/RemoveUnusedForeachKeyRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Foreach_/RemoveUnusedForeachKeyRector/Fixture)
2019-05-19 08:27:38 +00:00
2020-06-16 14:39:45 +00:00
Remove unused `key` in foreach
2019-05-19 08:27:38 +00:00
```diff
$items = [];
-foreach ($items as $key => $value) {
+foreach ($items as $value) {
$result = $value;
2019-05-19 08:27:38 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
### `RemoveUnusedFunctionRector`
- class: [`Rector\DeadCode\Rector\Function_\RemoveUnusedFunctionRector`](/../master/rules/dead-code/src/Rector/Function_/RemoveUnusedFunctionRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Function_/RemoveUnusedFunctionRector/Fixture)
Remove unused function
```diff
-function removeMe()
-{
-}
-
function useMe()
{
}
useMe();
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveUnusedNonEmptyArrayBeforeForeachRector`
- class: [`Rector\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector`](/../master/rules/dead-code/src/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector/Fixture)
Remove unused if check to non-empty array before foreach of the array
```diff
class SomeClass
{
public function run()
{
$values = [];
- if ($values !== []) {
- foreach ($values as $value) {
- echo $value;
- }
+ foreach ($values as $value) {
+ echo $value;
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `RemoveUnusedParameterRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveUnusedParameterRector`](/../master/rules/dead-code/src/Rector/ClassMethod/RemoveUnusedParameterRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassMethod/RemoveUnusedParameterRector/Fixture)
2019-02-21 14:36:16 +00:00
2019-05-29 13:40:20 +00:00
Remove unused parameter, if not required by interface or parent class
2019-02-21 14:36:16 +00:00
```diff
2019-05-29 13:40:20 +00:00
class SomeClass
2019-02-21 14:36:16 +00:00
{
2019-05-29 13:40:20 +00:00
- public function __construct($value, $value2)
+ public function __construct($value)
2019-02-21 14:36:16 +00:00
{
2019-05-29 13:40:20 +00:00
$this->value = $value;
2019-02-21 14:36:16 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
### `RemoveUnusedPrivateConstantRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\DeadCode\Rector\ClassConst\RemoveUnusedPrivateConstantRector`](/../master/rules/dead-code/src/Rector/ClassConst/RemoveUnusedPrivateConstantRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassConst/RemoveUnusedPrivateConstantRector/Fixture)
2019-02-21 14:36:16 +00:00
Remove unused private constant
2019-02-21 14:36:16 +00:00
```diff
2019-05-29 13:40:20 +00:00
final class SomeController
2019-02-21 14:36:16 +00:00
{
- private const SOME_CONSTANT = 5;
2019-05-29 13:40:20 +00:00
public function run()
2019-02-21 14:36:16 +00:00
{
return 5;
2019-02-21 14:36:16 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
### `RemoveUnusedPrivateMethodRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector`](/../master/rules/dead-code/src/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/ClassMethod/RemoveUnusedPrivateMethodRector/Fixture)
2019-03-31 12:25:39 +00:00
Remove unused private method
2019-03-31 12:25:39 +00:00
```diff
final class SomeController
2019-03-31 12:25:39 +00:00
{
public function run()
{
return 5;
}
-
- private function skip()
2019-05-29 13:40:20 +00:00
- {
- return 10;
2019-05-29 13:40:20 +00:00
- }
2019-03-31 12:25:39 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
### `RemoveUnusedPrivatePropertyRector`
2018-12-25 19:55:16 +00:00
- class: [`Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector`](/../master/rules/dead-code/src/Rector/Property/RemoveUnusedPrivatePropertyRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Property/RemoveUnusedPrivatePropertyRector/Fixture)
2018-12-25 19:55:16 +00:00
Remove unused private properties
2018-12-25 19:55:16 +00:00
```diff
2019-05-29 13:40:20 +00:00
class SomeClass
{
- private $property;
2019-05-29 13:40:20 +00:00
}
2018-12-25 19:55:16 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-25 19:55:16 +00:00
### `RemoveUnusedVariableAssignRector`
- class: [`Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector`](/../master/rules/dead-code/src/Rector/Assign/RemoveUnusedVariableAssignRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Assign/RemoveUnusedVariableAssignRector/Fixture)
Remove unused assigns to variables
```diff
class SomeClass
{
public function run()
{
- $value = 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `SimplifyIfElseWithSameContentRector`
- class: [`Rector\DeadCode\Rector\If_\SimplifyIfElseWithSameContentRector`](/../master/rules/dead-code/src/Rector/If_/SimplifyIfElseWithSameContentRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/If_/SimplifyIfElseWithSameContentRector/Fixture)
2019-10-15 14:46:31 +00:00
Remove if/else if they have same content
```diff
class SomeClass
{
public function run()
{
- if (true) {
- return 1;
- } else {
- return 1;
- }
+ return 1;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `SimplifyMirrorAssignRector`
- class: [`Rector\DeadCode\Rector\Expression\SimplifyMirrorAssignRector`](/../master/rules/dead-code/src/Rector/Expression/SimplifyMirrorAssignRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Expression/SimplifyMirrorAssignRector/Fixture)
Removes unneeded $a = $a assigns
```diff
-$a = $a;
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-27 17:50:00 +00:00
### `TernaryToBooleanOrFalseToBooleanAndRector`
- class: [`Rector\DeadCode\Rector\Ternary\TernaryToBooleanOrFalseToBooleanAndRector`](/../master/rules/dead-code/src/Rector/Ternary/TernaryToBooleanOrFalseToBooleanAndRector.php)
- [test fixtures](/../master/rules/dead-code/tests/Rector/Ternary/TernaryToBooleanOrFalseToBooleanAndRector/Fixture)
2019-12-27 17:50:00 +00:00
Change ternary of bool : false to && bool
```diff
class SomeClass
{
public function go()
{
- return $value ? $this->getBool() : false;
+ return $value && $this->getBool();
}
private function getBool(): bool
{
return (bool) 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-27 17:50:00 +00:00
## Decomplex
### `UseMessageVariableForSprintfInSymfonyStyleRector`
- class: [`Rector\Decomplex\Rector\MethodCall\UseMessageVariableForSprintfInSymfonyStyleRector`](/../master/rules/decomplex/src/Rector/MethodCall/UseMessageVariableForSprintfInSymfonyStyleRector.php)
- [test fixtures](/../master/rules/decomplex/tests/Rector/MethodCall/UseMessageVariableForSprintfInSymfonyStyleRector/Fixture)
2020-07-07 10:15:52 +00:00
Decouple `$message` property from `sprintf()` calls in `$this->smyfonyStyle->method()`
```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);
}
}
```
<br><br>
## Decouple
### `DecoupleClassMethodToOwnClassRector`
- class: [`Rector\Decouple\Rector\DecoupleClassMethodToOwnClassRector`](/../master/rules/decouple/src/Rector/DecoupleClassMethodToOwnClassRector.php)
- [test fixtures](/../master/rules/decouple/tests/Rector/DecoupleClassMethodToOwnClassRector/Fixture)
Move class method with its all dependencies to own class by method name
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Decouple\Rector\DecoupleClassMethodToOwnClassRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(DecoupleClassMethodToOwnClassRector::class)
->arg('$methodNamesByClass', ['SomeClass' => ['someMethod' => ['class' => 'NewDecoupledClass', 'method' => 'someRenamedMethod', 'parent_class' => 'AddedParentClass']]]);
};
```
```diff
class SomeClass
{
- public function someMethod()
- {
- $this->alsoCallThis();
- }
-
- private function alsoCallThis()
- {
- }
}
```
**New file**
```php
<?php
class NewDecoupledClass extends AddedParentClass
{
public function someRenamedMethod()
{
$this->alsoCallThis();
}
private function alsoCallThis()
{
}
}
```
<br><br>
2018-08-01 20:09:34 +00:00
## Doctrine
2019-12-22 18:38:09 +00:00
### `AddEntityIdByConditionRector`
- class: [`Rector\Doctrine\Rector\Class_\AddEntityIdByConditionRector`](/../master/rules/doctrine/src/Rector/Class_/AddEntityIdByConditionRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Class_/AddEntityIdByConditionRector/Fixture)
2019-12-22 18:38:09 +00:00
Add entity id with annotations when meets condition
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Doctrine\Rector\Class_\AddEntityIdByConditionRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(AddEntityIdByConditionRector::class);
};
2019-12-22 18:38:09 +00:00
```
```diff
class SomeClass
{
use SomeTrait;
+
+ /**
+ * @ORM\Id
+ * @ORM\Column(type="integer")
+ * @ORM\GeneratedValue(strategy="AUTO")
+ */
+ private $id;
+
+ public function getId(): int
+ {
+ return $this->id;
+ }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-22 18:38:09 +00:00
2019-09-21 22:14:49 +00:00
### `AddUuidAnnotationsToIdPropertyRector`
- class: [`Rector\Doctrine\Rector\Property\AddUuidAnnotationsToIdPropertyRector`](/../master/rules/doctrine/src/Rector/Property/AddUuidAnnotationsToIdPropertyRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Property/AddUuidAnnotationsToIdPropertyRector/Fixture)
2019-09-21 22:14:49 +00:00
2020-07-07 10:15:52 +00:00
Add uuid annotations to `$id` property
2019-09-21 22:14:49 +00:00
```diff
use Doctrine\ORM\Attributes as ORM;
/**
* @ORM\Entity
*/
class SomeClass
{
/**
- * @var int
+ * @var \Ramsey\Uuid\UuidInterface
* @ORM\Id
- * @ORM\Column(type="integer")
- * @ORM\GeneratedValue(strategy="AUTO")
- * @Serializer\Type("int")
+ * @ORM\Column(type="uuid_binary")
+ * @Serializer\Type("string")
*/
public $id;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `AddUuidMirrorForRelationPropertyRector`
- class: [`Rector\Doctrine\Rector\Class_\AddUuidMirrorForRelationPropertyRector`](/../master/rules/doctrine/src/Rector/Class_/AddUuidMirrorForRelationPropertyRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Class_/AddUuidMirrorForRelationPropertyRector/Fixture)
2020-07-07 10:15:52 +00:00
Adds `$uuid` property to entities, that already have `$id` with integer type.Require for step-by-step migration from int to uuid.
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeEntity
{
/**
* @ORM\ManyToOne(targetEntity="AnotherEntity", cascade={"persist", "merge"})
* @ORM\JoinColumn(nullable=false)
*/
private $amenity;
+
+ /**
+ * @ORM\ManyToOne(targetEntity="AnotherEntity", cascade={"persist", "merge"})
+ * @ORM\JoinColumn(nullable=true, referencedColumnName="uuid")
+ */
+ private $amenityUuid;
}
/**
* @ORM\Entity
*/
class AnotherEntity
{
/**
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
private $uuid;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `AddUuidToEntityWhereMissingRector`
- class: [`Rector\Doctrine\Rector\Class_\AddUuidToEntityWhereMissingRector`](/../master/rules/doctrine/src/Rector/Class_/AddUuidToEntityWhereMissingRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Class_/AddUuidToEntityWhereMissingRector/Fixture)
2018-08-01 20:09:34 +00:00
2020-07-07 10:15:52 +00:00
Adds `$uuid` property to entities, that already have `$id` with integer type.Require for step-by-step migration from int to uuid. In following step it should be renamed to `$id` and replace it
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeEntityWithIntegerId
{
/**
+ * @var \Ramsey\Uuid\UuidInterface
+ * @ORM\Column(type="uuid_binary", unique=true, nullable=true)
+ */
+ private $uuid;
+ /**
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-19 09:27:29 +00:00
### `AlwaysInitializeUuidInEntityRector`
- class: [`Rector\Doctrine\Rector\Class_\AlwaysInitializeUuidInEntityRector`](/../master/rules/doctrine/src/Rector/Class_/AlwaysInitializeUuidInEntityRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Class_/AlwaysInitializeUuidInEntityRector/Fixture)
2019-09-19 09:27:29 +00:00
Add uuid initializion to all entities that misses it
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class AddUuidInit
{
/**
* @ORM\Id
* @var UuidInterface
*/
private $superUuid;
+ public function __construct()
+ {
+ $this->superUuid = \Ramsey\Uuid\Uuid::uuid4();
+ }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-19 09:27:29 +00:00
2019-09-21 22:14:49 +00:00
### `ChangeGetIdTypeToUuidRector`
- class: [`Rector\Doctrine\Rector\ClassMethod\ChangeGetIdTypeToUuidRector`](/../master/rules/doctrine/src/Rector/ClassMethod/ChangeGetIdTypeToUuidRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/ClassMethod/ChangeGetIdTypeToUuidRector/Fixture)
2019-09-21 22:14:49 +00:00
2020-06-21 14:49:47 +00:00
Change return type of `getId()` to uuid interface
2019-09-21 22:14:49 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class GetId
{
- public function getId(): int
+ public function getId(): \Ramsey\Uuid\UuidInterface
{
return $this->id;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `ChangeGetUuidMethodCallToGetIdRector`
- class: [`Rector\Doctrine\Rector\MethodCall\ChangeGetUuidMethodCallToGetIdRector`](/../master/rules/doctrine/src/Rector/MethodCall/ChangeGetUuidMethodCallToGetIdRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/MethodCall/ChangeGetUuidMethodCallToGetIdRector/Fixture)
2019-09-21 22:14:49 +00:00
2020-06-21 14:49:47 +00:00
Change `getUuid()` method call to `getId()`
2019-09-21 22:14:49 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
class SomeClass
{
public function run()
{
$buildingFirst = new Building();
- return $buildingFirst->getUuid()->toString();
+ return $buildingFirst->getId()->toString();
}
}
/**
* @ORM\Entity
*/
class UuidEntity
{
private $uuid;
public function getUuid(): UuidInterface
{
return $this->uuid;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `ChangeIdenticalUuidToEqualsMethodCallRector`
- class: [`Rector\Doctrine\Rector\Identical\ChangeIdenticalUuidToEqualsMethodCallRector`](/../master/rules/doctrine/src/Rector/Identical/ChangeIdenticalUuidToEqualsMethodCallRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Identical/ChangeIdenticalUuidToEqualsMethodCallRector/Fixture)
2019-09-21 22:14:49 +00:00
2020-07-07 10:15:52 +00:00
Change `$uuid` === 1 to `$uuid->equals(\Ramsey\Uuid\Uuid::fromString(1))`
2019-09-21 22:14:49 +00:00
```diff
class SomeClass
{
public function match($checkedId): int
{
$building = new Building();
- return $building->getId() === $checkedId;
+ return $building->getId()->equals(\Ramsey\Uuid\Uuid::fromString($checkedId));
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `ChangeReturnTypeOfClassMethodWithGetIdRector`
- class: [`Rector\Doctrine\Rector\ClassMethod\ChangeReturnTypeOfClassMethodWithGetIdRector`](/../master/rules/doctrine/src/Rector/ClassMethod/ChangeReturnTypeOfClassMethodWithGetIdRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/ClassMethod/ChangeReturnTypeOfClassMethodWithGetIdRector/Fixture)
2019-09-21 22:14:49 +00:00
2020-06-21 14:49:47 +00:00
Change `getUuid()` method call to `getId()`
2019-09-21 22:14:49 +00:00
```diff
class SomeClass
{
- public function getBuildingId(): int
+ public function getBuildingId(): \Ramsey\Uuid\UuidInterface
{
$building = new Building();
return $building->getId();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `ChangeSetIdToUuidValueRector`
- class: [`Rector\Doctrine\Rector\MethodCall\ChangeSetIdToUuidValueRector`](/../master/rules/doctrine/src/Rector/MethodCall/ChangeSetIdToUuidValueRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/MethodCall/ChangeSetIdToUuidValueRector/Fixture)
2019-09-21 22:14:49 +00:00
Change set id to uuid values
```diff
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
class SomeClass
{
public function run()
{
$buildingFirst = new Building();
- $buildingFirst->setId(1);
- $buildingFirst->setUuid(Uuid::fromString('a3bfab84-e207-4ddd-b96d-488151de9e96'));
+ $buildingFirst->setId(Uuid::fromString('a3bfab84-e207-4ddd-b96d-488151de9e96'));
}
}
/**
* @ORM\Entity
*/
class Building
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `ChangeSetIdTypeToUuidRector`
- class: [`Rector\Doctrine\Rector\ClassMethod\ChangeSetIdTypeToUuidRector`](/../master/rules/doctrine/src/Rector/ClassMethod/ChangeSetIdTypeToUuidRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/ClassMethod/ChangeSetIdTypeToUuidRector/Fixture)
2019-09-21 22:14:49 +00:00
2020-06-21 14:49:47 +00:00
Change param type of `setId()` to uuid interface
2019-09-21 22:14:49 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SetId
{
private $id;
- public function setId(int $uuid): int
+ public function setId(\Ramsey\Uuid\UuidInterface $uuid): int
{
return $this->id = $uuid;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `EntityAliasToClassConstantReferenceRector`
- class: [`Rector\Doctrine\Rector\MethodCall\EntityAliasToClassConstantReferenceRector`](/../master/rules/doctrine/src/Rector/MethodCall/EntityAliasToClassConstantReferenceRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/MethodCall/EntityAliasToClassConstantReferenceRector/Fixture)
2018-08-01 20:09:34 +00:00
Replaces doctrine alias with class.
```diff
2018-08-10 19:07:08 +00:00
$entityManager = new Doctrine\ORM\EntityManager();
-$entityManager->getRepository("AppBundle:Post");
+$entityManager->getRepository(\App\Entity\Post::class);
2018-08-01 20:09:34 +00:00
```
2018-07-31 21:47:59 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
### `ManagerRegistryGetManagerToEntityManagerRector`
- class: [`Rector\Doctrine\Rector\Class_\ManagerRegistryGetManagerToEntityManagerRector`](/../master/rules/doctrine/src/Rector/Class_/ManagerRegistryGetManagerToEntityManagerRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Class_/ManagerRegistryGetManagerToEntityManagerRector/Fixture)
Changes ManagerRegistry intermediate calls directly to EntityManager calls
```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');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-02 08:04:14 +00:00
### `RemoveRepositoryFromEntityAnnotationRector`
- class: [`Rector\Doctrine\Rector\Class_\RemoveRepositoryFromEntityAnnotationRector`](/../master/rules/doctrine/src/Rector/Class_/RemoveRepositoryFromEntityAnnotationRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Class_/RemoveRepositoryFromEntityAnnotationRector/Fixture)
2019-10-02 08:04:14 +00:00
Removes repository class from @Entity annotation
```diff
use Doctrine\ORM\Mapping as ORM;
/**
- * @ORM\Entity(repositoryClass="ProductRepository")
+ * @ORM\Entity
*/
class Product
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-02 08:04:14 +00:00
2019-09-21 22:14:49 +00:00
### `RemoveTemporaryUuidColumnPropertyRector`
- class: [`Rector\Doctrine\Rector\Property\RemoveTemporaryUuidColumnPropertyRector`](/../master/rules/doctrine/src/Rector/Property/RemoveTemporaryUuidColumnPropertyRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Property/RemoveTemporaryUuidColumnPropertyRector/Fixture)
2019-09-21 22:14:49 +00:00
2020-07-07 10:15:52 +00:00
Remove temporary `$uuid` property
2019-09-21 22:14:49 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Column
{
/**
* @ORM\Column
*/
public $id;
-
- /**
- * @ORM\Column
- */
- public $uuid;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
### `RemoveTemporaryUuidRelationPropertyRector`
- class: [`Rector\Doctrine\Rector\Property\RemoveTemporaryUuidRelationPropertyRector`](/../master/rules/doctrine/src/Rector/Property/RemoveTemporaryUuidRelationPropertyRector.php)
- [test fixtures](/../master/rules/doctrine/tests/Rector/Property/RemoveTemporaryUuidRelationPropertyRector/Fixture)
2019-09-21 22:14:49 +00:00
Remove temporary *Uuid relation properties
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Column
{
/**
* @ORM\ManyToMany(targetEntity="Phonenumber")
*/
private $apple;
-
- /**
- * @ORM\ManyToMany(targetEntity="Phonenumber")
- */
- private $appleUuid;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-21 22:14:49 +00:00
2019-10-02 08:04:14 +00:00
## DoctrineCodeQuality
### `ChangeQuerySetParametersMethodParameterFromArrayToArrayCollectionRector`
- class: [`Rector\DoctrineCodeQuality\Rector\Class_\ChangeQuerySetParametersMethodParameterFromArrayToArrayCollectionRector`](/../master/rules/doctrine-code-quality/src/Rector/Class_/ChangeQuerySetParametersMethodParameterFromArrayToArrayCollectionRector.php)
- [test fixtures](/../master/rules/doctrine-code-quality/tests/Rector/Class_/ChangeQuerySetParametersMethodParameterFromArrayToArrayCollection/Fixture)
Change array to ArrayCollection in setParameters method of query builder
```diff
2020-04-01 00:05:51 +00:00
-
+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()
;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-02 08:04:14 +00:00
### `InitializeDefaultEntityCollectionRector`
- class: [`Rector\DoctrineCodeQuality\Rector\Class_\InitializeDefaultEntityCollectionRector`](/../master/rules/doctrine-code-quality/src/Rector/Class_/InitializeDefaultEntityCollectionRector.php)
- [test fixtures](/../master/rules/doctrine-code-quality/tests/Rector/Class_/InitializeDefaultEntityCollectionRector/Fixture)
2019-10-02 08:04:14 +00:00
Initialize collection property in Entity constructor
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeClass
{
/**
* @ORM\OneToMany(targetEntity="MarketingEvent")
*/
private $marketingEvents = [];
+
+ public function __construct()
+ {
+ $this->marketingEvents = new ArrayCollection();
+ }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-02 08:04:14 +00:00
2019-12-26 10:21:09 +00:00
## DoctrineGedmoToKnplabs
2020-01-08 00:05:45 +00:00
### `BlameableBehaviorRector`
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\BlameableBehaviorRector`](/../master/rules/doctrine-gedmo-to-knplabs/src/Rector/Class_/BlameableBehaviorRector.php)
- [test fixtures](/../master/rules/doctrine-gedmo-to-knplabs/tests/Rector/Class_/BlameableBehaviorRector/Fixture)
2020-01-08 00:05:45 +00:00
Change Blameable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
```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
{
- /**
- * @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;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-08 00:05:45 +00:00
### `LoggableBehaviorRector`
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\LoggableBehaviorRector`](/../master/rules/doctrine-gedmo-to-knplabs/src/Rector/Class_/LoggableBehaviorRector.php)
- [test fixtures](/../master/rules/doctrine-gedmo-to-knplabs/tests/Rector/Class_/LoggableBehaviorRector/Fixture)
2020-01-08 00:05:45 +00:00
Change Loggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
```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;
/**
* @ORM\Entity
- * @Gedmo\Loggable
*/
-class SomeClass
+class SomeClass implements LoggableInterface
{
+ use LoggableTrait;
+
/**
- * @Gedmo\Versioned
* @ORM\Column(name="title", type="string", length=8)
*/
private $title;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-08 00:05:45 +00:00
2019-12-26 10:21:09 +00:00
### `SluggableBehaviorRector`
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\SluggableBehaviorRector`](/../master/rules/doctrine-gedmo-to-knplabs/src/Rector/Class_/SluggableBehaviorRector.php)
- [test fixtures](/../master/rules/doctrine-gedmo-to-knplabs/tests/Rector/Class_/SluggableBehaviorRector/Fixture)
2019-12-26 10:21:09 +00:00
Change Sluggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
```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'];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-26 10:21:09 +00:00
2020-01-08 00:05:45 +00:00
### `SoftDeletableBehaviorRector`
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\SoftDeletableBehaviorRector`](/../master/rules/doctrine-gedmo-to-knplabs/src/Rector/Class_/SoftDeletableBehaviorRector.php)
- [test fixtures](/../master/rules/doctrine-gedmo-to-knplabs/tests/Rector/Class_/SoftDeletableBehaviorRector/Fixture)
2020-01-08 00:05:45 +00:00
Change SoftDeletable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
```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;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-08 00:05:45 +00:00
2019-12-26 10:21:09 +00:00
### `TimestampableBehaviorRector`
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\TimestampableBehaviorRector`](/../master/rules/doctrine-gedmo-to-knplabs/src/Rector/Class_/TimestampableBehaviorRector.php)
- [test fixtures](/../master/rules/doctrine-gedmo-to-knplabs/tests/Rector/Class_/TimestampableBehaviorRector/Fixture)
2019-12-26 10:21:09 +00:00
Change Timestampable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
```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;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-26 10:21:09 +00:00
2019-12-27 17:50:00 +00:00
### `TranslationBehaviorRector`
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\TranslationBehaviorRector`](/../master/rules/doctrine-gedmo-to-knplabs/src/Rector/Class_/TranslationBehaviorRector.php)
- [test fixtures](/../master/rules/doctrine-gedmo-to-knplabs/tests/Rector/Class_/TranslationBehaviorRector/Fixture)
2019-12-27 17:50:00 +00:00
Change Translation from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
```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;
- }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-27 17:50:00 +00:00
2019-12-26 10:21:09 +00:00
### `TreeBehaviorRector`
- class: [`Rector\DoctrineGedmoToKnplabs\Rector\Class_\TreeBehaviorRector`](/../master/rules/doctrine-gedmo-to-knplabs/src/Rector/Class_/TreeBehaviorRector.php)
- [test fixtures](/../master/rules/doctrine-gedmo-to-knplabs/tests/Rector/Class_/TreeBehaviorRector/Fixture)
2019-12-26 10:21:09 +00:00
Change Tree from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
```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;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-26 10:21:09 +00:00
## Downgrade
### `DowngradeTypedPropertyRector`
- class: [`Rector\Downgrade\Rector\Property\DowngradeTypedPropertyRector`](/../master/rules/downgrade/src/Rector/Property/DowngradeTypedPropertyRector.php)
- [test fixtures](/../master/rules/downgrade/tests/Rector/Property/DowngradeTypedPropertyRector/Fixture)
Changes property type definition from type definitions to `@var` annotations.
```diff
class SomeClass {
- private string $property;
+ /**
+ * @var string
+ */
+ private $property;
}
```
<br><br>
2019-11-12 07:01:15 +00:00
## DynamicTypeAnalysis
### `AddArgumentTypeWithProbeDataRector`
- class: [`Rector\DynamicTypeAnalysis\Rector\ClassMethod\AddArgumentTypeWithProbeDataRector`](/../master/packages/dynamic-type-analysis/src/Rector/ClassMethod/AddArgumentTypeWithProbeDataRector.php)
- [test fixtures](/../master/packages/dynamic-type-analysis/tests/Rector/ClassMethod/AddArgumentTypeWithProbeDataRector/Fixture)
2019-11-12 07:01:15 +00:00
Add argument type based on probed data
```diff
class SomeClass
{
- public function run($arg)
+ public function run(string $arg)
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-12 07:01:15 +00:00
### `DecorateMethodWithArgumentTypeProbeRector`
- class: [`Rector\DynamicTypeAnalysis\Rector\ClassMethod\DecorateMethodWithArgumentTypeProbeRector`](/../master/packages/dynamic-type-analysis/src/Rector/ClassMethod/DecorateMethodWithArgumentTypeProbeRector.php)
- [test fixtures](/../master/packages/dynamic-type-analysis/tests/Rector/ClassMethod/DecorateMethodWithArgumentTypeProbeRector/Fixture)
2019-11-12 07:01:15 +00:00
2020-06-16 14:39:45 +00:00
Add probe that records argument types to `each` method
2019-11-12 07:01:15 +00:00
```diff
class SomeClass
{
public function run($arg)
{
+ \Rector\DynamicTypeAnalysis\Probe\TypeStaticProbe::recordArgumentType($arg, __METHOD__, 0);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-12 07:01:15 +00:00
### `RemoveArgumentTypeProbeRector`
- class: [`Rector\DynamicTypeAnalysis\Rector\StaticCall\RemoveArgumentTypeProbeRector`](/../master/packages/dynamic-type-analysis/src/Rector/StaticCall/RemoveArgumentTypeProbeRector.php)
- [test fixtures](/../master/packages/dynamic-type-analysis/tests/Rector/StaticCall/RemoveArgumentTypeProbeRector/Fixture)
2019-11-12 07:01:15 +00:00
Clean up probe that records argument types
```diff
-use Rector\DynamicTypeAnalysis\Probe\TypeStaticProbe;
-
class SomeClass
{
public function run($arg)
{
- TypeStaticProbe::recordArgumentType($arg, __METHOD__, 0);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-12 07:01:15 +00:00
## FileSystemRector
### `RemoveProjectFileRector`
- class: [`Rector\FileSystemRector\Rector\Removing\RemoveProjectFileRector`](/../master/packages/file-system-rector/src/Rector/Removing/RemoveProjectFileRector.php)
Remove file relative to project directory
```diff
-// someFile/ToBeRemoved.txt
```
2020-06-16 16:14:51 +00:00
<br><br>
## Guzzle
### `MessageAsArrayRector`
- class: [`Rector\Guzzle\Rector\MethodCall\MessageAsArrayRector`](/../master/rules/guzzle/src/Rector/MethodCall/MessageAsArrayRector.php)
- [test fixtures](/../master/rules/guzzle/tests/Rector/MethodCall/MessageAsArrayRector/Fixture)
2020-06-21 14:49:47 +00:00
Changes getMessage(..., true) to `getMessageAsArray()`
```diff
/** @var GuzzleHttp\Message\MessageInterface */
-$value = $message->getMessage('key', true);
+$value = $message->getMessageAsArray('key');
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-07-24 11:46:57 +00:00
## Injection
### `StaticCallToAnotherServiceConstructorInjectionRector`
- class: [`Rector\Injection\Rector\StaticCall\StaticCallToAnotherServiceConstructorInjectionRector`](/../master/rules/injection/src/Rector/StaticCall/StaticCallToAnotherServiceConstructorInjectionRector.php)
- [test fixtures](/../master/rules/injection/tests/Rector/StaticCall/StaticCallToAnotherServiceConstructorInjectionRector/Fixture)
Change static call to service method via constructor injection
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Injection\Rector\StaticCall\StaticCallToAnotherServiceConstructorInjectionRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(StaticCallToAnotherServiceConstructorInjectionRector::class);
};
```
```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');
}
}
```
<br><br>
## JMS
### `RemoveJmsInjectParamsAnnotationRector`
- class: [`Rector\JMS\Rector\ClassMethod\RemoveJmsInjectParamsAnnotationRector`](/../master/rules/jms/src/Rector/ClassMethod/RemoveJmsInjectParamsAnnotationRector.php)
- [test fixtures](/../master/rules/jms/tests/Rector/ClassMethod/RemoveJmsInjectParamsAnnotationRector/Fixture)
Removes JMS\DiExtraBundle\Annotation\InjectParams annotation
```diff
use JMS\DiExtraBundle\Annotation as DI;
class SomeClass
{
- /**
- * @DI\InjectParams({
- * "subscribeService" = @DI\Inject("app.email.service.subscribe"),
- * "ipService" = @DI\Inject("app.util.service.ip")
- * })
- */
public function __construct()
{
}
-}
+}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveJmsInjectServiceAnnotationRector`
- class: [`Rector\JMS\Rector\Class_\RemoveJmsInjectServiceAnnotationRector`](/../master/rules/jms/src/Rector/Class_/RemoveJmsInjectServiceAnnotationRector.php)
- [test fixtures](/../master/rules/jms/tests/Rector/Class_/RemoveJmsInjectServiceAnnotationRector/Fixture)
Removes JMS\DiExtraBundle\Annotation\Services annotation
```diff
use JMS\DiExtraBundle\Annotation as DI;
-/**
- * @DI\Service("email.web.services.subscribe_token", public=true)
- */
class SomeClass
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
## Laravel
### `FacadeStaticCallToConstructorInjectionRector`
2019-03-09 13:24:30 +00:00
- class: [`Rector\Laravel\Rector\StaticCall\FacadeStaticCallToConstructorInjectionRector`](/../master/rules/laravel/src/Rector/StaticCall/FacadeStaticCallToConstructorInjectionRector.php)
- [test fixtures](/../master/rules/laravel/tests/Rector/StaticCall/FacadeStaticCallToConstructorInjectionRector/Fixture)
2019-03-09 13:24:30 +00:00
Move Illuminate\Support\Facades\* static calls to constructor injection
2019-03-09 13:24:30 +00:00
```diff
use Illuminate\Support\Facades\Response;
class ExampleController extends Controller
2019-03-09 13:24:30 +00:00
{
+ /**
+ * @var \Illuminate\Contracts\Routing\ResponseFactory
+ */
+ private $responseFactory;
+
+ public function __construct(\Illuminate\Contracts\Routing\ResponseFactory $responseFactory)
+ {
+ $this->responseFactory = $responseFactory;
+ }
+
public function store()
2019-03-09 13:24:30 +00:00
{
- return Response::view('example', ['new_example' => 123]);
+ return $this->responseFactory->view('example', ['new_example' => 123]);
2019-03-09 13:24:30 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
### `HelperFunctionToConstructorInjectionRector`
2019-03-09 13:24:30 +00:00
- class: [`Rector\Laravel\Rector\FuncCall\HelperFunctionToConstructorInjectionRector`](/../master/rules/laravel/src/Rector/FuncCall/HelperFunctionToConstructorInjectionRector.php)
- [test fixtures](/../master/rules/laravel/tests/Rector/FuncCall/HelperFunctionToConstructorInjectionRector/Fixture)
2019-03-09 13:24:30 +00:00
Move help facade-like function calls to constructor injection
2019-03-09 13:24:30 +00:00
```diff
class SomeController
2019-03-09 13:24:30 +00:00
{
+ /**
+ * @var \Illuminate\Contracts\View\Factory
2019-03-09 13:24:30 +00:00
+ */
+ private $viewFactory;
2019-03-09 13:24:30 +00:00
+
+ public function __construct(\Illuminate\Contracts\View\Factory $viewFactory)
2019-03-09 13:24:30 +00:00
+ {
+ $this->viewFactory = $viewFactory;
2019-03-09 13:24:30 +00:00
+ }
+
public function action()
2019-03-09 13:24:30 +00:00
{
- $template = view('template.blade');
- $viewFactory = view();
+ $template = $this->viewFactory->make('template.blade');
+ $viewFactory = $this->viewFactory;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-19 09:27:29 +00:00
### `InlineValidationRulesToArrayDefinitionRector`
- class: [`Rector\Laravel\Rector\Class_\InlineValidationRulesToArrayDefinitionRector`](/../master/rules/laravel/src/Rector/Class_/InlineValidationRulesToArrayDefinitionRector.php)
- [test fixtures](/../master/rules/laravel/tests/Rector/Class_/InlineValidationRulesToArrayDefinitionRector/Fixture)
2019-09-19 09:27:29 +00:00
Transforms inline validation rules to array definition
```diff
use Illuminate\Foundation\Http\FormRequest;
class SomeClass extends FormRequest
{
public function rules(): array
{
return [
- 'someAttribute' => 'required|string|exists:' . SomeModel::class . 'id',
+ 'someAttribute' => ['required', 'string', \Illuminate\Validation\Rule::exists(SomeModel::class, 'id')],
];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-19 09:27:29 +00:00
### `MinutesToSecondsInCacheRector`
- class: [`Rector\Laravel\Rector\StaticCall\MinutesToSecondsInCacheRector`](/../master/rules/laravel/src/Rector/StaticCall/MinutesToSecondsInCacheRector.php)
- [test fixtures](/../master/rules/laravel/tests/Rector/StaticCall/MinutesToSecondsInCacheRector/Fixture)
Change minutes argument to seconds in Illuminate\Contracts\Cache\Store and Illuminate\Support\Facades\Cache
```diff
class SomeClass
{
public function run()
{
- Illuminate\Support\Facades\Cache::put('key', 'value', 60);
+ Illuminate\Support\Facades\Cache::put('key', 'value', 60 * 60);
2019-03-09 13:24:30 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
### `Redirect301ToPermanentRedirectRector`
- class: [`Rector\Laravel\Rector\StaticCall\Redirect301ToPermanentRedirectRector`](/../master/rules/laravel/src/Rector/StaticCall/Redirect301ToPermanentRedirectRector.php)
- [test fixtures](/../master/rules/laravel/tests/Rector/StaticCall/Redirect301ToPermanentRedirectRector/Fixture)
2019-03-09 13:24:30 +00:00
Change "redirect" call with 301 to "permanentRedirect"
```diff
class SomeClass
{
public function run()
{
- Illuminate\Routing\Route::redirect('/foo', '/bar', 301);
+ Illuminate\Routing\Route::permanentRedirect('/foo', '/bar');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
### `RequestStaticValidateToInjectRector`
- class: [`Rector\Laravel\Rector\StaticCall\RequestStaticValidateToInjectRector`](/../master/rules/laravel/src/Rector/StaticCall/RequestStaticValidateToInjectRector.php)
- [test fixtures](/../master/rules/laravel/tests/Rector/StaticCall/RequestStaticValidateToInjectRector/Fixture)
2019-03-09 13:24:30 +00:00
2020-06-21 14:49:47 +00:00
Change static `validate()` method to `$request->validate()`
2019-03-09 13:24:30 +00:00
```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']);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
## Legacy
2020-07-14 21:23:06 +00:00
### `AddTopIncludeRector`
- class: [`Rector\Legacy\Rector\Include_\AddTopIncludeRector`](/../master/rules/legacy/src/Rector/Include_/AddTopIncludeRector.php)
- [test fixtures](/../master/rules/legacy/tests/Rector/Include_/AddTopIncludeRector/Fixture)
Adds an include file at the top of matching files, except class definitions
```diff
+require_once __DIR__ . '/../autoloader.php';
+
if (isset($_POST['csrf'])) {
processPost($_POST);
}
```
<br><br>
### `ChangeSingletonToServiceRector`
2020-03-28 23:39:16 +00:00
- class: [`Rector\Legacy\Rector\ClassMethod\ChangeSingletonToServiceRector`](/../master/rules/legacy/src/Rector/ClassMethod/ChangeSingletonToServiceRector.php)
- [test fixtures](/../master/rules/legacy/tests/Rector/ClassMethod/ChangeSingletonToServiceRector/Fixture)
Change singleton class to normal class that can be registered as a service
```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;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `FunctionToStaticMethodRector`
- class: [`Rector\Legacy\Rector\FileSystem\FunctionToStaticMethodRector`](/../master/rules/legacy/src/Rector/FileSystem/FunctionToStaticMethodRector.php)
Change functions to static calls, so composer can autoload them
```diff
-function some_function()
+class SomeUtilsClass
{
+ public static function someFunction()
+ {
+ }
}
-some_function('lol');
+SomeUtilsClass::someFunction('lol');
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveIncludeRector`
- class: [`Rector\Legacy\Rector\Include_\RemoveIncludeRector`](/../master/rules/legacy/src/Rector/Include_/RemoveIncludeRector.php)
- [test fixtures](/../master/rules/legacy/tests/Rector/Include_/RemoveIncludeRector/Fixture)
Remove includes (include, include_once, require, require_once) from source
```diff
// Comment before require
-include 'somefile.php';
+
// Comment after require
```
<br><br>
## MagicDisclosure
### `DefluentMethodCallRector`
- class: [`Rector\MagicDisclosure\Rector\MethodCall\DefluentMethodCallRector`](/../master/rules/magic-disclosure/src/Rector/MethodCall/DefluentMethodCallRector.php)
- [test fixtures](/../master/rules/magic-disclosure/tests/Rector/MethodCall/DefluentMethodCallRector/Fixture)
Turns fluent interface calls to classic ones.
```diff
$someClass = new SomeClass();
-$someClass->someFunction()
- ->otherFunction();
+$someClass->someFunction();
+$someClass->otherFunction();
```
<br><br>
### `GetAndSetToMethodCallRector`
- class: [`Rector\MagicDisclosure\Rector\Assign\GetAndSetToMethodCallRector`](/../master/rules/magic-disclosure/src/Rector/Assign/GetAndSetToMethodCallRector.php)
- [test fixtures](/../master/rules/magic-disclosure/tests/Rector/Assign/GetAndSetToMethodCallRector/Fixture)
Turns defined `__get`/`__set` to specific method calls.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\MagicDisclosure\Rector\Assign\GetAndSetToMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(GetAndSetToMethodCallRector::class)
->arg('SomeContainer', ['set' => 'addService']);
};
```
```diff
$container = new SomeContainer;
-$container->someService = $someService;
+$container->setService("someService", $someService);
```
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\MagicDisclosure\Rector\Assign\GetAndSetToMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(GetAndSetToMethodCallRector::class)
->arg('$typeToMethodCalls', ['SomeContainer' => ['get' => 'getService']]);
};
```
```diff
$container = new SomeContainer;
-$someService = $container->someService;
+$someService = $container->getService("someService");
```
<br><br>
### `ReturnThisRemoveRector`
2020-07-01 20:28:39 +00:00
- class: [`Rector\MagicDisclosure\Rector\ClassMethod\ReturnThisRemoveRector`](/../master/rules/magic-disclosure/src/Rector/ClassMethod/ReturnThisRemoveRector.php)
- [test fixtures](/../master/rules/magic-disclosure/tests/Rector/ClassMethod/ReturnThisRemoveRector/Fixture)
2020-07-07 10:15:52 +00:00
Removes "return `$this;"` from *fluent interfaces* for specified classes.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\MagicDisclosure\Rector\ClassMethod\ReturnThisRemoveRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ReturnThisRemoveRector::class)
->arg('$classesToDefluent', ['SomeExampleClass']);
2020-07-24 11:46:57 +00:00
};
```
```diff
class SomeExampleClass
{
public function someFunction()
{
- return $this;
}
public function otherFunction()
{
- return $this;
}
}
```
<br><br>
### `ToStringToMethodCallRector`
- class: [`Rector\MagicDisclosure\Rector\String_\ToStringToMethodCallRector`](/../master/rules/magic-disclosure/src/Rector/String_/ToStringToMethodCallRector.php)
- [test fixtures](/../master/rules/magic-disclosure/tests/Rector/String_/ToStringToMethodCallRector/Fixture)
Turns defined code uses of "__toString()" method to specific method calls.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\MagicDisclosure\Rector\String_\ToStringToMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ToStringToMethodCallRector::class)
->arg('$methodNamesByType', ['SomeObject' => 'getPath']);
2020-07-24 11:46:57 +00:00
};
```
```diff
$someValue = new SomeObject;
-$result = (string) $someValue;
-$result = $someValue->__toString();
+$result = $someValue->getPath();
+$result = $someValue->getPath();
```
<br><br>
### `UnsetAndIssetToMethodCallRector`
- class: [`Rector\MagicDisclosure\Rector\Isset_\UnsetAndIssetToMethodCallRector`](/../master/rules/magic-disclosure/src/Rector/Isset_/UnsetAndIssetToMethodCallRector.php)
- [test fixtures](/../master/rules/magic-disclosure/tests/Rector/Isset_/UnsetAndIssetToMethodCallRector/Fixture)
Turns defined `__isset`/`__unset` calls to specific method calls.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\MagicDisclosure\Rector\Isset_\UnsetAndIssetToMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(UnsetAndIssetToMethodCallRector::class)
->arg('SomeContainer', ['isset' => 'hasService']);
};
```
```diff
$container = new SomeContainer;
-isset($container["someKey"]);
+$container->hasService("someKey");
```
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\MagicDisclosure\Rector\Isset_\UnsetAndIssetToMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(UnsetAndIssetToMethodCallRector::class)
->arg('SomeContainer', ['unset' => 'removeService']);
};
```
```diff
$container = new SomeContainer;
-unset($container["someKey"]);
+$container->removeService("someKey");
```
<br><br>
## MockeryToProphecy
### `MockeryCloseRemoveRector`
- class: [`Rector\MockeryToProphecy\Rector\StaticCall\MockeryCloseRemoveRector`](/../master/rules/mockery-to-prophecy/src/Rector/StaticCall/MockeryCloseRemoveRector.php)
Removes mockery close from test classes
```diff
public function tearDown() : void
{
- \Mockery::close();
}
```
<br><br>
### `MockeryCreateMockToProphizeRector`
- class: [`Rector\MockeryToProphecy\Rector\MethodCall\MockeryCreateMockToProphizeRector`](/../master/rules/mockery-to-prophecy/src/Rector/MethodCall/MockeryCreateMockToProphizeRector.php)
Changes mockery mock creation to Prophesize
```diff
-$mock = \Mockery::mock(\'MyClass\');
+ $mock = $this->prophesize(\'MyClass\');
+
$service = new Service();
-$service->injectDependency($mock);
+$service->injectDependency($mock->reveal());
```
<br><br>
2020-05-14 10:26:57 +00:00
## MockistaToMockery
### `MockeryTearDownRector`
- class: [`Rector\MockistaToMockery\Rector\Class_\MockeryTearDownRector`](/../master/rules/mockista-to-mockery/src/Rector/Class_/MockeryTearDownRector.php)
- [test fixtures](/../master/rules/mockista-to-mockery/tests/Rector/Class_/MockeryTearDownRector/Fixture)
2020-06-21 14:49:47 +00:00
Add `Mockery::close()` in `tearDown()` method if not yet
2020-05-14 10:26:57 +00:00
```diff
use PHPUnit\Framework\TestCase;
class SomeTest extends TestCase
{
+ protected function tearDown(): void
+ {
+ Mockery::close();
+ }
public function test()
{
$mockUser = mock(User::class);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-14 10:26:57 +00:00
### `MockistaMockToMockeryMockRector`
- class: [`Rector\MockistaToMockery\Rector\ClassMethod\MockistaMockToMockeryMockRector`](/../master/rules/mockista-to-mockery/src/Rector/ClassMethod/MockistaMockToMockeryMockRector.php)
- [test fixtures](/../master/rules/mockista-to-mockery/tests/Rector/ClassMethod/MockistaMockToMockeryMockRector/Fixture)
Change functions to static calls, so composer can autoload them
```diff
class SomeTest
{
public function run()
{
- $mockUser = mock(User::class);
- $mockUser->getId()->once->andReturn(1);
- $mockUser->freeze();
+ $mockUser = Mockery::mock(User::class);
+ $mockUser->expects()->getId()->once()->andReturn(1);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-14 10:26:57 +00:00
2019-02-21 14:36:16 +00:00
## MysqlToMysqli
### `MysqlAssignToMysqliRector`
- class: [`Rector\MysqlToMysqli\Rector\Assign\MysqlAssignToMysqliRector`](/../master/rules/mysql-to-mysqli/src/Rector/Assign/MysqlAssignToMysqliRector.php)
- [test fixtures](/../master/rules/mysql-to-mysqli/tests/Rector/Assign/MysqlAssignToMysqliRector/Fixture)
2019-02-21 14:36:16 +00:00
Converts more complex mysql functions to mysqli
```diff
-$data = mysql_db_name($result, $row);
+mysqli_data_seek($result, $row);
+$fetch = mysql_fetch_row($result);
+$data = $fetch[0];
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
### `MysqlFuncCallToMysqliRector`
- class: [`Rector\MysqlToMysqli\Rector\FuncCall\MysqlFuncCallToMysqliRector`](/../master/rules/mysql-to-mysqli/src/Rector/FuncCall/MysqlFuncCallToMysqliRector.php)
- [test fixtures](/../master/rules/mysql-to-mysqli/tests/Rector/FuncCall/MysqlFuncCallToMysqliRector/Fixture)
2019-02-21 14:36:16 +00:00
Converts more complex mysql functions to mysqli
```diff
-mysql_drop_db($database);
+mysqli_query('DROP DATABASE ' . $database);
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
### `MysqlPConnectToMysqliConnectRector`
- class: [`Rector\MysqlToMysqli\Rector\FuncCall\MysqlPConnectToMysqliConnectRector`](/../master/rules/mysql-to-mysqli/src/Rector/FuncCall/MysqlPConnectToMysqliConnectRector.php)
- [test fixtures](/../master/rules/mysql-to-mysqli/tests/Rector/FuncCall/MysqlPConnectToMysqliConnectRector/Fixture)
2019-02-21 14:36:16 +00:00
2020-06-21 14:49:47 +00:00
Replace `mysql_pconnect()` with `mysqli_connect()` with host p: prefix
2019-02-21 14:36:16 +00:00
```diff
final class SomeClass
{
public function run($host, $username, $password)
{
- return mysql_pconnect($host, $username, $password);
+ return mysqli_connect('p:' . $host, $username, $password);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
### `MysqlQueryMysqlErrorWithLinkRector`
- class: [`Rector\MysqlToMysqli\Rector\FuncCall\MysqlQueryMysqlErrorWithLinkRector`](/../master/rules/mysql-to-mysqli/src/Rector/FuncCall/MysqlQueryMysqlErrorWithLinkRector.php)
- [test fixtures](/../master/rules/mysql-to-mysqli/tests/Rector/FuncCall/MysqlQueryMysqlErrorWithLinkRector/Fixture)
Add mysql_query and mysql_error with connection
```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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## Naming
### `RenamePropertyToMatchTypeRector`
- class: [`Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector`](/../master/rules/naming/src/Rector/Class_/RenamePropertyToMatchTypeRector.php)
- [test fixtures](/../master/rules/naming/tests/Rector/Class_/RenamePropertyToMatchTypeRector/Fixture)
Rename property and method param to match its type
```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;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RenameVariableToMatchGetMethodNameRector`
- class: [`Rector\Naming\Rector\Assign\RenameVariableToMatchGetMethodNameRector`](/../master/rules/naming/src/Rector/Assign/RenameVariableToMatchGetMethodNameRector.php)
- [test fixtures](/../master/rules/naming/tests/Rector/Assign/RenameVariableToMatchGetMethodNameRector/Fixture)
Rename variable to match get method name
```diff
class SomeClass
{
public function run()
{
- $a = $this->getRunner();
+ $runner = $this->getRunner();
}
}
```
<br><br>
2020-06-30 08:46:05 +00:00
### `RenameVariableToMatchNewTypeRector`
- class: [`Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector`](/../master/rules/naming/src/Rector/ClassMethod/RenameVariableToMatchNewTypeRector.php)
- [test fixtures](/../master/rules/naming/tests/Rector/ClassMethod/RenameVariableToMatchNewTypeRector/Fixture)
Rename variable to match new ClassType
```diff
final class SomeClass
{
public function run()
{
- $search = new DreamSearch();
- $search->advance();
+ $dreamSearch = new DreamSearch();
+ $dreamSearch->advance();
}
}
```
<br><br>
2019-04-02 13:35:35 +00:00
## Nette
### `AddDatePickerToDateControlRector`
- class: [`Rector\Nette\Rector\MethodCall\AddDatePickerToDateControlRector`](/../master/rules/nette/src/Rector/MethodCall/AddDatePickerToDateControlRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/MethodCall/AddDatePickerToDateControlRector/Fixture)
Nextras/Form upgrade of addDatePicker method call to DateControl assign
```diff
use Nette\Application\UI\Form;
class SomeClass
{
public function run()
{
$form = new Form();
- $form->addDatePicker('key', 'Label');
+ $keyDateControl = $form['key'] = new \Nextras\FormComponents\Controls\DateControl('Label');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ContextGetByTypeToConstructorInjectionRector`
- class: [`Rector\Nette\Rector\MethodCall\ContextGetByTypeToConstructorInjectionRector`](/../master/rules/nette/src/Rector/MethodCall/ContextGetByTypeToConstructorInjectionRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/MethodCall/ContextGetByTypeToConstructorInjectionRector/Fixture)
Move dependency get via `$context->getByType()` to constructor injection
```diff
class SomeClass
{
/**
* @var \Nette\DI\Container
*/
private $context;
+ /**
+ * @var SomeTypeToInject
+ */
+ private $someTypeToInject;
+
+ public function __construct(SomeTypeToInject $someTypeToInject)
+ {
+ $this->someTypeToInject = $someTypeToInject;
+ }
+
public function run()
{
- $someTypeToInject = $this->context->getByType(SomeTypeToInject::class);
+ $someTypeToInject = $this->someTypeToInject;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `EndsWithFunctionToNetteUtilsStringsRector`
2019-04-02 13:35:35 +00:00
- class: [`Rector\Nette\Rector\Identical\EndsWithFunctionToNetteUtilsStringsRector`](/../master/rules/nette/src/Rector/Identical/EndsWithFunctionToNetteUtilsStringsRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/Identical/EndsWithFunctionToNetteUtilsStringsRector/Fixture)
2019-04-02 13:35:35 +00:00
2020-06-21 14:49:47 +00:00
Use `Nette\Utils\Strings::endWith()` over bare string-functions
2019-04-02 13:35:35 +00:00
```diff
class SomeClass
{
public function end($needle)
2019-04-02 13:35:35 +00:00
{
2019-05-29 13:40:20 +00:00
$content = 'Hi, my name is Tom';
- $yes = substr($content, -strlen($needle)) === $needle;
+ $yes = \Nette\Utils\Strings::endsWith($content, $needle);
2019-04-02 13:35:35 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-04-02 13:35:35 +00:00
2019-11-12 07:01:15 +00:00
### `FilePutContentsToFileSystemWriteRector`
- class: [`Rector\Nette\Rector\FuncCall\FilePutContentsToFileSystemWriteRector`](/../master/rules/nette/src/Rector/FuncCall/FilePutContentsToFileSystemWriteRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/FuncCall/FilePutContentsToFileSystemWriteRector/Fixture)
2019-11-12 07:01:15 +00:00
2020-06-21 14:49:47 +00:00
Change `file_put_contents()` to `FileSystem::write()`
2019-11-12 07:01:15 +00:00
```diff
class SomeClass
{
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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-12 07:01:15 +00:00
2019-08-17 13:06:02 +00:00
### `JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector`
- class: [`Rector\Nette\Rector\FuncCall\JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector`](/../master/rules/nette/src/Rector/FuncCall/JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/FuncCall/JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector/Fixture)
2019-08-17 13:06:02 +00:00
2020-06-21 14:49:47 +00:00
Changes `json_encode()/json_decode()` to safer and more verbose `Nette\Utils\Json::encode()/decode()` calls
2019-08-17 13:06:02 +00:00
```diff
class SomeClass
{
public function decodeJson(string $jsonString)
{
- $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-06-16 16:14:51 +00:00
<br><br>
2019-08-17 13:06:02 +00:00
### `PregFunctionToNetteUtilsStringsRector`
2019-04-02 13:35:35 +00:00
- class: [`Rector\Nette\Rector\FuncCall\PregFunctionToNetteUtilsStringsRector`](/../master/rules/nette/src/Rector/FuncCall/PregFunctionToNetteUtilsStringsRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/FuncCall/PregFunctionToNetteUtilsStringsRector/Fixture)
2019-04-02 13:35:35 +00:00
2020-06-16 14:39:45 +00:00
Use `Nette\Utils\Strings` over bare `preg_split()` and `preg_replace()` functions
```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#');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `PregMatchFunctionToNetteUtilsStringsRector`
- class: [`Rector\Nette\Rector\FuncCall\PregMatchFunctionToNetteUtilsStringsRector`](/../master/rules/nette/src/Rector/FuncCall/PregMatchFunctionToNetteUtilsStringsRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/FuncCall/PregMatchFunctionToNetteUtilsStringsRector/Fixture)
2020-06-16 14:39:45 +00:00
Use `Nette\Utils\Strings` over bare `preg_match()` and `preg_match_all()` functions
2019-04-02 13:35:35 +00:00
```diff
+use Nette\Utils\Strings;
+
2019-04-02 13:35:35 +00:00
class SomeClass
{
public function run()
2019-04-02 13:35:35 +00:00
{
$content = 'Hi my name is Tom';
2019-11-06 23:52:19 +00:00
- preg_match('#Hi#', $content, $matches);
+ $matches = Strings::match($content, '#Hi#');
2019-04-02 13:35:35 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-04-02 13:35:35 +00:00
### `SetClassWithArgumentToSetFactoryRector`
- class: [`Rector\Nette\Rector\MethodCall\SetClassWithArgumentToSetFactoryRector`](/../master/rules/nette/src/Rector/MethodCall/SetClassWithArgumentToSetFactoryRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/MethodCall/SetClassWithArgumentToSetFactoryRector/Fixture)
Change setClass with class and arguments to separated methods
```diff
use Nette\DI\ContainerBuilder;
class SomeClass
{
public function run(ContainerBuilder $containerBuilder)
{
$containerBuilder->addDefinition('...')
- ->setClass('SomeClass', [1, 2]);
+ ->setFactory('SomeClass', [1, 2]);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `StartsWithFunctionToNetteUtilsStringsRector`
2019-04-02 13:35:35 +00:00
- class: [`Rector\Nette\Rector\Identical\StartsWithFunctionToNetteUtilsStringsRector`](/../master/rules/nette/src/Rector/Identical/StartsWithFunctionToNetteUtilsStringsRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/Identical/StartsWithFunctionToNetteUtilsStringsRector/Fixture)
2019-04-02 13:35:35 +00:00
2020-06-21 14:49:47 +00:00
Use `Nette\Utils\Strings::startsWith()` over bare string-functions
2019-04-02 13:35:35 +00:00
```diff
class SomeClass
{
public function start($needle)
2019-04-02 13:35:35 +00:00
{
$content = 'Hi, my name is Tom';
- $yes = substr($content, 0, strlen($needle)) === $needle;
+ $yes = \Nette\Utils\Strings::startsWith($content, $needle);
2019-04-02 13:35:35 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-04-02 13:35:35 +00:00
### `StrposToStringsContainsRector`
2019-04-02 13:35:35 +00:00
- class: [`Rector\Nette\Rector\NotIdentical\StrposToStringsContainsRector`](/../master/rules/nette/src/Rector/NotIdentical/StrposToStringsContainsRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/NotIdentical/StrposToStringsContainsRector/Fixture)
2019-04-02 13:35:35 +00:00
2020-06-16 14:39:45 +00:00
Use `Nette\Utils\Strings` over bare string-functions
2019-04-02 13:35:35 +00:00
```diff
class SomeClass
{
2019-05-29 13:40:20 +00:00
public function run()
2019-04-02 13:35:35 +00:00
{
$name = 'Hi, my name is Tom';
- return strpos($name, 'Hi') !== false;
+ return \Nette\Utils\Strings::contains($name, 'Hi');
2019-04-02 13:35:35 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-04-02 13:35:35 +00:00
### `SubstrStrlenFunctionToNetteUtilsStringsRector`
2019-04-02 13:35:35 +00:00
- class: [`Rector\Nette\Rector\FuncCall\SubstrStrlenFunctionToNetteUtilsStringsRector`](/../master/rules/nette/src/Rector/FuncCall/SubstrStrlenFunctionToNetteUtilsStringsRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/FuncCall/SubstrStrlenFunctionToNetteUtilsStringsRector/Fixture)
2019-04-02 13:35:35 +00:00
2020-06-16 14:39:45 +00:00
Use `Nette\Utils\Strings` over bare string-functions
2019-04-02 13:35:35 +00:00
```diff
class SomeClass
{
2019-05-29 13:40:20 +00:00
public function run()
2019-04-02 13:35:35 +00:00
{
- return substr($value, 0, 3);
+ return \Nette\Utils\Strings::substring($value, 0, 3);
2019-04-02 13:35:35 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-04-02 13:35:35 +00:00
2019-12-26 18:35:02 +00:00
### `TemplateMagicAssignToExplicitVariableArrayRector`
- class: [`Rector\Nette\Rector\ClassMethod\TemplateMagicAssignToExplicitVariableArrayRector`](/../master/rules/nette/src/Rector/ClassMethod/TemplateMagicAssignToExplicitVariableArrayRector.php)
- [test fixtures](/../master/rules/nette/tests/Rector/ClassMethod/TemplateMagicAssignToExplicitVariableArrayRector/Fixture)
2019-12-26 18:35:02 +00:00
2020-06-21 14:32:27 +00:00
Change `$this->templates->{magic}` to `$this->template->render(..., $values)`
2019-12-26 18:35:02 +00:00
```diff
use Nette\Application\UI\Control;
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']);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-26 18:35:02 +00:00
## NetteCodeQuality
### `ChangeControlArrayAccessToAnnotatedControlVariableRector`
- class: [`Rector\NetteCodeQuality\Rector\ArrayDimFetch\ChangeControlArrayAccessToAnnotatedControlVariableRector`](/../master/rules/nette-code-quality/src/Rector/ArrayDimFetch/ChangeControlArrayAccessToAnnotatedControlVariableRector.php)
- [test fixtures](/../master/rules/nette-code-quality/tests/Rector/ArrayDimFetch/ChangeControlArrayAccessToAnnotatedControlVariableRector/Fixture)
Change magic `$this["some_component"]` to variable assign with @var annotation
```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><br>
### `ChangeFormArrayAccessToAnnotatedControlVariableRector`
- class: [`Rector\NetteCodeQuality\Rector\ArrayDimFetch\ChangeFormArrayAccessToAnnotatedControlVariableRector`](/../master/rules/nette-code-quality/src/Rector/ArrayDimFetch/ChangeFormArrayAccessToAnnotatedControlVariableRector.php)
- [test fixtures](/../master/rules/nette-code-quality/tests/Rector/ArrayDimFetch/ChangeFormArrayAccessToAnnotatedControlVariableRector/Fixture)
Change array access magic on `$form` to explicit standalone typed variable
```diff
use Nette\Application\UI\Form;
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';
}
}
```
<br><br>
### `MakeGetComponentAssignAnnotatedRector`
- class: [`Rector\NetteCodeQuality\Rector\Assign\MakeGetComponentAssignAnnotatedRector`](/../master/rules/nette-code-quality/src/Rector/Assign/MakeGetComponentAssignAnnotatedRector.php)
- [test fixtures](/../master/rules/nette-code-quality/tests/Rector/Assign/MakeGetComponentAssignAnnotatedRector/Fixture)
Add doc type for magic `$control->getComponent(...)` assign
```diff
use Nette\Application\UI\Control;
final class SomeClass
{
public function run()
{
$externalControl = new ExternalControl();
+ /** @var AnotherControl $anotherControl */
$anotherControl = $externalControl->getComponent('another');
}
}
final class ExternalControl extends Control
{
public function createComponentAnother(): AnotherControl
{
return new AnotherControl();
}
}
final class AnotherControl extends Control
{
}
```
<br><br>
### `MoveInjectToExistingConstructorRector`
- class: [`Rector\NetteCodeQuality\Rector\Class_\MoveInjectToExistingConstructorRector`](/../master/rules/nette-code-quality/src/Rector/Class_/MoveInjectToExistingConstructorRector.php)
- [test fixtures](/../master/rules/nette-code-quality/tests/Rector/Class_/MoveInjectToExistingConstructorRector/Fixture)
Move @inject properties to constructor, if there already is one
```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><br>
## NetteKdyby
2020-05-30 23:34:04 +00:00
### `ChangeNetteEventNamesInGetSubscribedEventsRector`
2020-05-30 23:34:04 +00:00
- class: [`Rector\NetteKdyby\Rector\ClassMethod\ChangeNetteEventNamesInGetSubscribedEventsRector`](/../master/rules/nette-kdyby/src/Rector/ClassMethod/ChangeNetteEventNamesInGetSubscribedEventsRector.php)
- [test fixtures](/../master/rules/nette-kdyby/tests/Rector/ClassMethod/ChangeNetteEventNamesInGetSubscribedEventsRector/Fixture)
Change EventSubscriber from Kdyby to Contributte
```diff
+use Contributte\Events\Extra\Event\Application\ShutdownEvent;
2020-05-30 23:34:04 +00:00
use Kdyby\Events\Subscriber;
use Nette\Application\Application;
-use Nette\Application\UI\Presenter;
2020-05-30 23:34:04 +00:00
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();
// ...
}
2020-05-29 10:41:25 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-29 10:41:25 +00:00
### `ReplaceEventManagerWithEventSubscriberRector`
- class: [`Rector\NetteKdyby\Rector\MethodCall\ReplaceEventManagerWithEventSubscriberRector`](/../master/rules/nette-kdyby/src/Rector/MethodCall/ReplaceEventManagerWithEventSubscriberRector.php)
- [test fixtures](/../master/rules/nette-kdyby/tests/Rector/MethodCall/ReplaceEventManagerWithEventSubscriberRector/Fixture)
Change Kdyby EventManager to EventDispatcher
```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));
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-29 10:41:25 +00:00
### `ReplaceMagicEventPropertySubscriberWithEventClassSubscriberRector`
- class: [`Rector\NetteKdyby\Rector\ClassMethod\ReplaceMagicEventPropertySubscriberWithEventClassSubscriberRector`](/../master/rules/nette-kdyby/src/Rector/ClassMethod/ReplaceMagicEventPropertySubscriberWithEventClassSubscriberRector.php)
- [test fixtures](/../master/rules/nette-kdyby/tests/Rector/ClassMethod/ReplaceMagicEventPropertySubscriberWithEventClassSubscriberRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `getSubscribedEvents()` from on magic property, to Event class
2020-05-29 10:41:25 +00:00
```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
{
2020-05-29 10:41:25 +00:00
+ $album = $albumServiceApproveEventAlbum->getAlbum();
$album->play();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ReplaceMagicPropertyEventWithEventClassRector`
- class: [`Rector\NetteKdyby\Rector\MethodCall\ReplaceMagicPropertyEventWithEventClassRector`](/../master/rules/nette-kdyby/src/Rector/MethodCall/ReplaceMagicPropertyEventWithEventClassRector.php)
- [test fixtures](/../master/rules/nette-kdyby/tests/Rector/MethodCall/ReplaceMagicPropertyEventWithEventClassRector/Fixture)
2020-07-07 10:15:52 +00:00
Change `$onProperty` magic call with event disptacher and class dispatch
```diff
final class FileManager
{
- public $onUpload;
2020-05-29 10:41:25 +00:00
+ 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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-16 20:31:46 +00:00
## NetteTesterToPHPUnit
### `NetteAssertToPHPUnitAssertRector`
- class: [`Rector\NetteTesterToPHPUnit\Rector\StaticCall\NetteAssertToPHPUnitAssertRector`](/../master/rules/nette-tester-to-phpunit/src/Rector/StaticCall/NetteAssertToPHPUnitAssertRector.php)
Migrate Nette/Assert calls to PHPUnit
```diff
use Tester\Assert;
function someStaticFunctions()
{
- Assert::true(10 == 5);
+ \PHPUnit\Framework\Assert::assertTrue(10 == 5);
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-16 20:31:46 +00:00
### `NetteTesterClassToPHPUnitClassRector`
- class: [`Rector\NetteTesterToPHPUnit\Rector\Class_\NetteTesterClassToPHPUnitClassRector`](/../master/rules/nette-tester-to-phpunit/src/Rector/Class_/NetteTesterClassToPHPUnitClassRector.php)
2019-03-16 20:31:46 +00:00
Migrate Nette Tester test case to PHPUnit
```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);
2019-03-31 12:25:39 +00:00
+ $this->assertInstanceOf(\Kdyby\Doctrine\EntityManager::cllass, $default);
+ $this->assertTrue(5);
+ $this->same($container->getService('kdyby.doctrine.default.entityManager'), $default);
2019-03-16 20:31:46 +00:00
}
-}
-
-(new \ExtensionTest())->run();
+}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-16 20:31:46 +00:00
### `RenameTesterTestToPHPUnitToTestFileRector`
2019-02-02 16:22:15 +00:00
- class: [`Rector\NetteTesterToPHPUnit\Rector\RenameTesterTestToPHPUnitToTestFileRector`](/../master/rules/nette-tester-to-phpunit/src/Rector/RenameTesterTestToPHPUnitToTestFileRector.php)
2019-02-02 16:22:15 +00:00
Rename "*.phpt" file to "*Test.php" file
2019-02-02 16:22:15 +00:00
```diff
-// tests/SomeTestCase.phpt
+// tests/SomeTestCase.php
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-02 16:22:15 +00:00
## NetteToSymfony
2019-02-02 16:22:15 +00:00
### `DeleteFactoryInterfaceRector`
- class: [`Rector\NetteToSymfony\Rector\FileSystem\DeleteFactoryInterfaceRector`](/../master/rules/nette-to-symfony/src/Rector/FileSystem/DeleteFactoryInterfaceRector.php)
Interface factories are not needed in Symfony. Clear constructor injection is used instead
```diff
-interface SomeControlFactoryInterface
-{
- public function create();
-}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-22 18:38:09 +00:00
### `FormControlToControllerAndFormTypeRector`
- class: [`Rector\NetteToSymfony\Rector\Assign\FormControlToControllerAndFormTypeRector`](/../master/rules/nette-to-symfony/src/Rector/Assign/FormControlToControllerAndFormTypeRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/Assign/FormControlToControllerAndFormTypeRector/Fixture)
2019-12-22 18:38:09 +00:00
Change Form that extends Control to Controller and decoupled FormType
```diff
-use Nette\Application\UI\Form;
-use Nette\Application\UI\Control;
-
-class SomeForm extends Control
+class SomeFormController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
2020-03-28 23:06:05 +00:00
- 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'];
- }
-
2020-03-28 23:06:05 +00:00
- public function processForm(Form $form)
- {
- // process me
2020-03-28 23:06:05 +00:00
+ if ($form->isSuccess() && $form->isValid()) {
+ // process me
+ }
}
2019-12-22 18:38:09 +00:00
}
```
2020-03-28 23:06:05 +00:00
**New file**
```php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class SomeFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $formBuilder, array $options)
{
$formBuilder->add('name', TextType::class, [
'label' => 'Your name'
]);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-22 18:38:09 +00:00
### `FromHttpRequestGetHeaderToHeadersGetRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\NetteToSymfony\Rector\MethodCall\FromHttpRequestGetHeaderToHeadersGetRector`](/../master/rules/nette-to-symfony/src/Rector/MethodCall/FromHttpRequestGetHeaderToHeadersGetRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/MethodCall/FromHttpRequestGetHeaderToHeadersGetRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-21 14:49:47 +00:00
Changes `getHeader()` to `$request->headers->get()`
2019-05-29 13:40:20 +00:00
```diff
use Nette\Request;
2019-05-29 13:40:20 +00:00
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
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `FromRequestGetParameterToAttributesGetRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\NetteToSymfony\Rector\MethodCall\FromRequestGetParameterToAttributesGetRector`](/../master/rules/nette-to-symfony/src/Rector/MethodCall/FromRequestGetParameterToAttributesGetRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/MethodCall/FromRequestGetParameterToAttributesGetRector/Fixture)
2019-05-29 13:40:20 +00:00
Changes "getParameter()" to "attributes->get()" from Nette to Symfony
2019-05-29 13:40:20 +00:00
```diff
use Nette\Request;
2019-05-29 13:40:20 +00:00
final class SomeController
2019-02-02 16:22:15 +00:00
{
public static function someAction(Request $request)
2019-02-02 16:22:15 +00:00
{
- $value = $request->getParameter('abz');
+ $value = $request->attribute->get('abz');
2019-02-02 16:22:15 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-02 16:22:15 +00:00
2019-05-29 13:40:20 +00:00
### `NetteControlToSymfonyControllerRector`
2019-02-18 15:51:24 +00:00
- class: [`Rector\NetteToSymfony\Rector\Class_\NetteControlToSymfonyControllerRector`](/../master/rules/nette-to-symfony/src/Rector/Class_/NetteControlToSymfonyControllerRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/Class_/NetteControlToSymfonyControllerRector/Fixture)
2019-02-18 15:51:24 +00:00
2019-05-29 13:40:20 +00:00
Migrate Nette Component to Symfony Controller
2019-02-18 15:51:24 +00:00
```diff
2019-12-26 18:35:02 +00:00
-use Nette\Application\UI\Control;
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+use Symfony\Component\HttpFoundation\Response;
2019-02-18 15:51:24 +00:00
2019-05-29 13:40:20 +00:00
-class SomeControl extends Control
+class SomeController extends AbstractController
2019-02-18 15:51:24 +00:00
{
2019-05-29 13:40:20 +00:00
- public function render()
- {
- $this->template->param = 'some value';
- $this->template->render(__DIR__ . '/poll.latte');
- }
+ public function some(): Response
2019-05-29 13:40:20 +00:00
+ {
+ return $this->render(__DIR__ . '/poll.latte', ['param' => 'some value']);
2019-05-29 13:40:20 +00:00
+ }
2019-02-18 15:51:24 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-18 15:51:24 +00:00
### `NetteFormToSymfonyFormRector`
2019-02-18 15:51:24 +00:00
- class: [`Rector\NetteToSymfony\Rector\Class_\NetteFormToSymfonyFormRector`](/../master/rules/nette-to-symfony/src/Rector/Class_/NetteFormToSymfonyFormRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/Class_/NetteFormToSymfonyFormRector/Fixture)
2019-02-18 15:51:24 +00:00
Migrate Nette\Forms in Presenter to Symfony
2019-02-18 15:51:24 +00:00
```diff
use Nette\Application\UI;
2019-02-18 15:51:24 +00:00
class SomePresenter extends UI\Presenter
2019-02-18 15:51:24 +00:00
{
public function someAction()
2019-02-18 15:51:24 +00:00
{
- $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'
+ ]);
2019-02-18 15:51:24 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-18 15:51:24 +00:00
2019-05-29 13:40:20 +00:00
### `RenameEventNamesInEventSubscriberRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\NetteToSymfony\Rector\ClassMethod\RenameEventNamesInEventSubscriberRector`](/../master/rules/nette-to-symfony/src/Rector/ClassMethod/RenameEventNamesInEventSubscriberRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/ClassMethod/RenameEventNamesInEventSubscriberRector/Fixture)
2019-03-31 12:25:39 +00:00
2019-05-29 13:40:20 +00:00
Changes event names from Nette ones to Symfony ones
2019-03-31 12:25:39 +00:00
```diff
2019-05-29 13:40:20 +00:00
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
2019-03-31 12:25:39 +00:00
2019-05-29 13:40:20 +00:00
final class SomeClass implements EventSubscriberInterface
2019-03-31 12:25:39 +00:00
{
2019-05-29 13:40:20 +00:00
public static function getSubscribedEvents()
{
- return ['nette.application' => 'someMethod'];
+ return [\SymfonyEvents::KERNEL => 'someMethod'];
}
2019-03-31 12:25:39 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
2019-05-29 13:40:20 +00:00
### `RouterListToControllerAnnotationsRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\NetteToSymfony\Rector\ClassMethod\RouterListToControllerAnnotationsRector`](/../master/rules/nette-to-symfony/src/Rector/ClassMethod/RouterListToControllerAnnotationsRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/ClassMethod/RouterListToControllerAnnotationsRetor/Fixture)
2019-03-31 12:25:39 +00:00
2020-06-21 14:49:47 +00:00
Change new `Route()` from RouteFactory to @Route annotation above controller method
2019-03-31 12:25:39 +00:00
```diff
2019-05-29 13:40:20 +00:00
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);
2019-03-31 12:25:39 +00:00
2019-05-29 13:40:20 +00:00
return $routeList;
}
}
2019-09-19 09:27:29 +00:00
+use Symfony\Component\Routing\Annotation\Route;
+
2019-05-29 13:40:20 +00:00
final class SomePresenter
2019-03-31 12:25:39 +00:00
{
2019-05-29 13:40:20 +00:00
+ /**
2019-09-19 09:27:29 +00:00
+ * @Route(path="some-path")
2019-05-29 13:40:20 +00:00
+ */
public function run()
2019-03-31 12:25:39 +00:00
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
### `WrapTransParameterNameRector`
- class: [`Rector\NetteToSymfony\Rector\MethodCall\WrapTransParameterNameRector`](/../master/rules/nette-to-symfony/src/Rector/MethodCall/WrapTransParameterNameRector.php)
- [test fixtures](/../master/rules/nette-to-symfony/tests/Rector/MethodCall/WrapTransParameterNameRector/Fixture)
2020-06-21 14:49:47 +00:00
Adds %% to placeholder name of `trans()` method if missing
```diff
use Symfony\Component\Translation\Translator;
final class SomeController
{
public function run()
{
$translator = new Translator('');
$translated = $translator->trans(
'Hello %name%',
- ['name' => $name]
+ ['%name%' => $name]
);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## NetteUtilsCodeQuality
### `ReplaceTimeNumberWithDateTimeConstantRector`
- class: [`Rector\NetteUtilsCodeQuality\Rector\LNumber\ReplaceTimeNumberWithDateTimeConstantRector`](/../master/rules/nette-utils-code-quality/src/Rector/LNumber/ReplaceTimeNumberWithDateTimeConstantRector.php)
- [test fixtures](/../master/rules/nette-utils-code-quality/tests/Rector/LNumber/ReplaceTimeNumberWithDateTimeConstantRector/Fixture)
2020-06-16 14:39:45 +00:00
Replace `time` numbers with `Nette\Utils\DateTime` constants
```diff
final class SomeClass
{
public function run()
{
- return 86400;
+ return \Nette\Utils\DateTime::DAY;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## Order
### `OrderClassConstantsByIntegerValueRector`
- class: [`Rector\Order\Rector\Class_\OrderClassConstantsByIntegerValueRector`](/../master/rules/order/src/Rector/Class_/OrderClassConstantsByIntegerValueRector.php)
- [test fixtures](/../master/rules/order/tests/Rector/Class_/OrderClassConstantsByIntegerValueRector/Fixture)
Order class constant order by their integer value
```diff
class SomeClass
{
const MODE_ON = 0;
+ const MODE_MAYBE = 1;
+
const MODE_OFF = 2;
-
- const MODE_MAYBE = 1;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `OrderConstructorDependenciesByTypeAlphabeticallyRector`
- class: [`Rector\Order\Rector\ClassMethod\OrderConstructorDependenciesByTypeAlphabeticallyRector`](/../master/rules/order/src/Rector/ClassMethod/OrderConstructorDependenciesByTypeAlphabeticallyRector.php)
- [test fixtures](/../master/rules/order/tests/Rector/ClassMethod/OrderConstructorDependenciesByTypeAlphabeticallyRector/Fixture)
Order __constructor dependencies by type A-Z
```diff
class SomeClass
{
public function __construct(
+ LatteAndTwigFinder $latteAndTwigFinder,
LatteToTwigConverter $latteToTwigConverter,
+ SmartFileSystem $smartFileSystem,
SymfonyStyle $symfonyStyle,
- LatteAndTwigFinder $latteAndTwigFinder,
- SmartFileSystem $smartFileSystem,
) {
}
}
```
<br><br>
### `OrderPrivateMethodsByUseRector`
- class: [`Rector\Order\Rector\Class_\OrderPrivateMethodsByUseRector`](/../master/rules/order/src/Rector/Class_/OrderPrivateMethodsByUseRector.php)
- [test fixtures](/../master/rules/order/tests/Rector/Class_/OrderPrivateMethodsByUseRector/Fixture)
Order private methods in order of their use
```diff
class SomeClass
{
public function run()
{
$this->call1();
$this->call2();
}
- private function call2()
+ private function call1()
{
}
- private function call1()
+ private function call2()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `OrderPropertyByComplexityRector`
- class: [`Rector\Order\Rector\Class_\OrderPropertyByComplexityRector`](/../master/rules/order/src/Rector/Class_/OrderPropertyByComplexityRector.php)
- [test fixtures](/../master/rules/order/tests/Rector/Class_/OrderPropertyByComplexityRector/Fixture)
Order properties by complexity, from the simplest like scalars to the most complex, like union or collections
```diff
-class SomeClass
+class SomeClass implements FoodRecipeInterface
{
/**
* @var string
*/
private $name;
/**
- * @var Type
+ * @var int
*/
- private $service;
+ private $price;
/**
- * @var int
+ * @var Type
*/
- private $price;
+ private $service;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `OrderPublicInterfaceMethodRector`
- class: [`Rector\Order\Rector\Class_\OrderPublicInterfaceMethodRector`](/../master/rules/order/src/Rector/Class_/OrderPublicInterfaceMethodRector.php)
- [test fixtures](/../master/rules/order/tests/Rector/Class_/OrderPublicInterfaceMethodRector/Fixture)
Order public methods required by interface in custom orderer
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Order\Rector\Class_\OrderPublicInterfaceMethodRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(OrderPublicInterfaceMethodRector::class)
->arg('$methodOrderByInterfaces', ['FoodRecipeInterface' => ['getDescription', 'process']]);
};
```
```diff
class SomeClass implements FoodRecipeInterface
{
- public function process()
+ public function getDescription()
{
}
-
- public function getDescription()
+ public function process()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## PHPOffice
### `AddRemovedDefaultValuesRector`
- class: [`Rector\PHPOffice\Rector\StaticCall\AddRemovedDefaultValuesRector`](/../master/rules/php-office/src/Rector/StaticCall/AddRemovedDefaultValuesRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/StaticCall/AddRemovedDefaultValuesRector/Fixture)
Complete removed default values explicitly
```diff
final class SomeClass
{
public function run(): void
{
$logger = new \PHPExcel_CalcEngine_Logger;
- $logger->setWriteDebugLog();
+ $logger->setWriteDebugLog(false);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CellStaticToCoordinateRector`
- class: [`Rector\PHPOffice\Rector\StaticCall\CellStaticToCoordinateRector`](/../master/rules/php-office/src/Rector/StaticCall/CellStaticToCoordinateRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/StaticCall/CellStaticToCoordinateRector/Fixture)
Methods to manipulate coordinates that used to exists in PHPExcel_Cell to PhpOffice\PhpSpreadsheet\Cell\Coordinate
```diff
class SomeClass
{
public function run()
{
- \PHPExcel_Cell::stringFromColumnIndex();
+ \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeChartRendererRector`
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeChartRendererRector`](/../master/rules/php-office/src/Rector/StaticCall/ChangeChartRendererRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/StaticCall/ChangeChartRendererRector/Fixture)
Change chart renderer
```diff
final class SomeClass
{
public function run(): void
{
- \PHPExcel_Settings::setChartRenderer($rendererName, $rendererLibraryPath);
+ \PHPExcel_Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeConditionalGetConditionRector`
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeConditionalGetConditionRector`](/../master/rules/php-office/src/Rector/MethodCall/ChangeConditionalGetConditionRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/MethodCall/ChangeConditionalGetConditionRector/Fixture)
2020-06-21 14:49:47 +00:00
Change argument `PHPExcel_Style_Conditional->getCondition()` to `getConditions()`
```diff
final class SomeClass
{
public function run(): void
{
$conditional = new \PHPExcel_Style_Conditional;
- $someCondition = $conditional->getCondition();
+ $someCondition = $conditional->getConditions()[0] ?? '';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeConditionalReturnedCellRector`
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeConditionalReturnedCellRector`](/../master/rules/php-office/src/Rector/MethodCall/ChangeConditionalReturnedCellRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/MethodCall/ChangeConditionalReturnedCellRector/Fixture)
2020-06-21 14:49:47 +00:00
Change conditional call to `getCell()`
```diff
final class SomeClass
{
public function run(): void
{
$worksheet = new \PHPExcel_Worksheet();
- $cell = $worksheet->setCellValue('A1', 'value', true);
+ $cell = $worksheet->getCell('A1')->setValue('value');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeConditionalSetConditionRector`
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeConditionalSetConditionRector`](/../master/rules/php-office/src/Rector/MethodCall/ChangeConditionalSetConditionRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/MethodCall/ChangeConditionalSetConditionRector/Fixture)
2020-06-21 14:49:47 +00:00
Change argument `PHPExcel_Style_Conditional->setCondition()` to `setConditions()`
```diff
final class SomeClass
{
public function run(): void
{
$conditional = new \PHPExcel_Style_Conditional;
- $someCondition = $conditional->setCondition(1);
+ $someCondition = $conditional->setConditions((array) 1);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeDataTypeForValueRector`
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeDataTypeForValueRector`](/../master/rules/php-office/src/Rector/StaticCall/ChangeDataTypeForValueRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/StaticCall/ChangeDataTypeForValueRector/Fixture)
2020-06-21 14:49:47 +00:00
Change argument `DataType::dataTypeForValue()` to DefaultValueBinder
```diff
final class SomeClass
{
public function run(): void
{
- $type = \PHPExcel_Cell_DataType::dataTypeForValue('value');
+ $type = \PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder::dataTypeForValue('value');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeDuplicateStyleArrayToApplyFromArrayRector`
- class: [`Rector\PHPOffice\Rector\MethodCall\ChangeDuplicateStyleArrayToApplyFromArrayRector`](/../master/rules/php-office/src/Rector/MethodCall/ChangeDuplicateStyleArrayToApplyFromArrayRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/MethodCall/ChangeDuplicateStyleArrayToApplyFromArrayRector/Fixture)
2020-06-21 14:49:47 +00:00
Change method call `duplicateStyleArray()` to `getStyle()` + `applyFromArray()`
```diff
final class SomeClass
{
public function run(): void
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->duplicateStyleArray($styles, $range, $advanced);
+ $worksheet->getStyle($range)->applyFromArray($styles, $advanced);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeIOFactoryArgumentRector`
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeIOFactoryArgumentRector`](/../master/rules/php-office/src/Rector/StaticCall/ChangeIOFactoryArgumentRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/StaticCall/ChangeIOFactoryArgumentRector/Fixture)
2020-06-21 14:49:47 +00:00
Change argument of PHPExcel_IOFactory::createReader(), `PHPExcel_IOFactory::createWriter()` and `PHPExcel_IOFactory::identify()`
```diff
final class SomeClass
{
public function run(): void
{
- $writer = \PHPExcel_IOFactory::createWriter('CSV');
+ $writer = \PHPExcel_IOFactory::createWriter('Csv');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangePdfWriterRector`
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangePdfWriterRector`](/../master/rules/php-office/src/Rector/StaticCall/ChangePdfWriterRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/StaticCall/ChangePdfWriterRector/Fixture)
Change init of PDF writer
```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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeSearchLocationToRegisterReaderRector`
- class: [`Rector\PHPOffice\Rector\StaticCall\ChangeSearchLocationToRegisterReaderRector`](/../master/rules/php-office/src/Rector/StaticCall/ChangeSearchLocationToRegisterReaderRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/StaticCall/ChangeSearchLocationToRegisterReaderRector/Fixture)
2020-06-21 14:49:47 +00:00
Change argument `addSearchLocation()` to `registerReader()`
```diff
final class SomeClass
{
public function run(): void
{
- \PHPExcel_IOFactory::addSearchLocation($type, $location, $classname);
+ \PhpOffice\PhpSpreadsheet\IOFactory::registerReader($type, $classname);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `GetDefaultStyleToGetParentRector`
- class: [`Rector\PHPOffice\Rector\MethodCall\GetDefaultStyleToGetParentRector`](/../master/rules/php-office/src/Rector/MethodCall/GetDefaultStyleToGetParentRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/MethodCall/GetDefaultStyleToGetParentRector/Fixture)
2020-06-21 14:49:47 +00:00
Methods to (new `Worksheet())->getDefaultStyle()` to `getParent()->getDefaultStyle()`
```diff
class SomeClass
{
public function run()
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->getDefaultStyle();
+ $worksheet->getParent()->getDefaultStyle();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `IncreaseColumnIndexRector`
- class: [`Rector\PHPOffice\Rector\MethodCall\IncreaseColumnIndexRector`](/../master/rules/php-office/src/Rector/MethodCall/IncreaseColumnIndexRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/MethodCall/IncreaseColumnIndexRector/Fixture)
Column index changed from 0 to 1 - run only ONCE! changes current value without memory
```diff
final class SomeClass
{
public function run(): void
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->setCellValueByColumnAndRow(0, 3, '1150');
+ $worksheet->setCellValueByColumnAndRow(1, 3, '1150');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveSetTempDirOnExcelWriterRector`
- class: [`Rector\PHPOffice\Rector\MethodCall\RemoveSetTempDirOnExcelWriterRector`](/../master/rules/php-office/src/Rector/MethodCall/RemoveSetTempDirOnExcelWriterRector.php)
- [test fixtures](/../master/rules/php-office/tests/Rector/MethodCall/RemoveSetTempDirOnExcelWriterRector/Fixture)
2020-06-21 14:49:47 +00:00
Remove `setTempDir()` on PHPExcel_Writer_Excel5
```diff
final class SomeClass
{
public function run(): void
{
$writer = new \PHPExcel_Writer_Excel5;
- $writer->setTempDir();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## PHPStan
### `PHPStormVarAnnotationRector`
- class: [`Rector\PHPStan\Rector\Assign\PHPStormVarAnnotationRector`](/../master/rules/phpstan/src/Rector/Assign/PHPStormVarAnnotationRector.php)
- [test fixtures](/../master/rules/phpstan/tests/Rector/Assign/PHPStormVarAnnotationRector/Fixture)
Change various @var annotation formats to one PHPStorm understands
```diff
-$config = 5;
-/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+$config = 5;
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RecastingRemovalRector`
- class: [`Rector\PHPStan\Rector\Cast\RecastingRemovalRector`](/../master/rules/phpstan/src/Rector/Cast/RecastingRemovalRector.php)
- [test fixtures](/../master/rules/phpstan/tests/Rector/Cast/RecastingRemovalRector/Fixture)
Removes recasting of the same type
```diff
$string = '';
-$string = (string) $string;
+$string = $string;
$array = [];
-$array = (array) $array;
+$array = $array;
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `RemoveNonExistingVarAnnotationRector`
- class: [`Rector\PHPStan\Rector\Node\RemoveNonExistingVarAnnotationRector`](/../master/rules/phpstan/src/Rector/Node/RemoveNonExistingVarAnnotationRector.php)
- [test fixtures](/../master/rules/phpstan/tests/Rector/Node/RemoveNonExistingVarAnnotationRector/Fixture)
2019-08-05 21:10:47 +00:00
Removes non-existing @var annotations above the code
```diff
class SomeClass
{
public function get()
{
- /** @var Training[] $trainings */
return $this->getData();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
2018-10-21 22:26:45 +00:00
## PHPUnit
2019-10-15 14:46:31 +00:00
### `AddDoesNotPerformAssertionToNonAssertingTestRector`
- class: [`Rector\PHPUnit\Rector\ClassMethod\AddDoesNotPerformAssertionToNonAssertingTestRector`](/../master/rules/phpunit/src/Rector/ClassMethod/AddDoesNotPerformAssertionToNonAssertingTestRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/ClassMethod/AddDoesNotPerformAssertionToNonAssertingTestRector/Fixture)
2019-10-15 14:46:31 +00:00
2019-11-16 08:45:14 +00:00
Tests without assertion will have @doesNotPerformAssertion
2019-10-15 14:46:31 +00:00
```diff
class SomeClass extends PHPUnit\Framework\TestCase
{
+ /**
2020-02-29 20:50:29 +00:00
+ * @doesNotPerformAssertions
2019-10-15 14:46:31 +00:00
+ */
public function test()
{
$nothing = 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
2020-04-01 00:05:51 +00:00
### `AddProphecyTraitRector`
- class: [`Rector\PHPUnit\Rector\Class_\AddProphecyTraitRector`](/../master/rules/phpunit/src/Rector/Class_/AddProphecyTraitRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/Class_/AddProphecyTraitRector/Fixture)
2020-06-21 14:49:47 +00:00
Add Prophecy trait for method using `$this->prophesize()`
2020-04-01 00:05:51 +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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-04-01 00:05:51 +00:00
### `AddSeeTestAnnotationRector`
- class: [`Rector\PHPUnit\Rector\Class_\AddSeeTestAnnotationRector`](/../master/rules/phpunit/src/Rector/Class_/AddSeeTestAnnotationRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/Class_/AddSeeTestAnnotationRector/Fixture)
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.
```diff
+/**
+ * @see \SomeServiceTest
+ */
class SomeService
{
}
2020-02-11 13:49:32 +00:00
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ArrayArgumentInTestToDataProviderRector`
- class: [`Rector\PHPUnit\Rector\Class_\ArrayArgumentInTestToDataProviderRector`](/../master/rules/phpunit/src/Rector/Class_/ArrayArgumentInTestToDataProviderRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/Class_/ArrayArgumentInTestToDataProviderRector/Fixture)
Move array argument from tests into data provider [configurable]
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\PHPUnit\Rector\Class_\ArrayArgumentInTestToDataProviderRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ArrayArgumentInTestToDataProviderRector::class)
->arg('$configuration', [['class' => 'PHPUnit\Framework\TestCase', 'old_method' => 'doTestMultiple', 'new_method' => 'doTestSingle', 'variable_name' => 'number']]);
};
```
```diff
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
{
- public function test()
+ /**
2020-02-02 17:32:08 +00:00
+ * @dataProvider provideData()
+ */
2019-09-15 18:28:10 +00:00
+ public function test(int $number)
{
- $this->doTestMultiple([1, 2, 3]);
2019-09-15 18:28:10 +00:00
+ $this->doTestSingle($number);
+ }
+
2020-02-02 17:32:08 +00:00
+ public function provideData(): \Iterator
+ {
2019-09-15 18:28:10 +00:00
+ yield [1];
+ yield [2];
+ yield [3];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `AssertCompareToSpecificMethodRector`
2018-10-21 22:26:45 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertCompareToSpecificMethodRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertCompareToSpecificMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertCompareToSpecificMethodRector/Fixture)
2018-10-21 22:26:45 +00:00
Turns vague php-only method in PHPUnit TestCase to more specific
2018-10-21 22:26:45 +00:00
2018-10-12 23:15:00 +00:00
```diff
-$this->assertSame(10, count($anything), "message");
+$this->assertCount(10, $anything, "message");
2018-10-12 23:15:00 +00:00
```
```diff
2019-12-18 09:53:46 +00:00
-$this->assertNotEquals(get_class($value), stdClass::class);
+$this->assertNotInstanceOf(stdClass::class, $value);
2018-12-14 19:35:35 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-14 19:35:35 +00:00
### `AssertComparisonToSpecificMethodRector`
2018-12-14 19:35:35 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertComparisonToSpecificMethodRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertComparisonToSpecificMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertComparisonToSpecificMethodRector/Fixture)
2019-05-29 13:40:20 +00:00
Turns comparison operations to their method name alternatives in PHPUnit TestCase
2019-05-29 13:40:20 +00:00
```diff
-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
2019-05-29 13:40:20 +00:00
```
```diff
-$this->assertFalse($foo >= $bar, "message");
+$this->assertLessThanOrEqual($bar, $foo, "message");
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `AssertEqualsParameterToSpecificMethodsTypeRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\AssertEqualsParameterToSpecificMethodsTypeRector`](/../master/rules/phpunit/src/Rector/MethodCall/AssertEqualsParameterToSpecificMethodsTypeRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/AssertEqualsParameterToSpecificMethodsTypeRector/Fixture)
2018-12-14 19:35:35 +00:00
2020-06-21 14:49:47 +00:00
Change `assertEquals()/assertNotEquals()` method parameters to new specific alternatives
2018-12-14 19:35:35 +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');
2019-03-16 20:31:46 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-16 20:31:46 +00:00
### `AssertFalseStrposToContainsRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertFalseStrposToContainsRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertFalseStrposToContainsRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertFalseStrposToContainsRector/Fixture)
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
```diff
-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
```
2019-05-29 13:40:20 +00:00
```diff
-$this->assertNotFalse(stripos($anything, "foo"), "message");
+$this->assertContains("foo", $anything, "message");
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `AssertInstanceOfComparisonRector`
2019-03-16 20:31:46 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertInstanceOfComparisonRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertInstanceOfComparisonRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertInstanceOfComparisonRector/Fixture)
2019-03-16 20:31:46 +00:00
Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase
2019-03-16 20:31:46 +00:00
```diff
-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertInstanceOf("Foo", $foo, "message");
```
2018-08-01 20:09:34 +00:00
```diff
-$this->assertFalse($foo instanceof Foo, "message");
+$this->assertNotInstanceOf("Foo", $foo, "message");
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `AssertIssetToSpecificMethodRector`
2018-07-31 12:50:39 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertIssetToSpecificMethodRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertIssetToSpecificMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertIssetToSpecificMethodRector/Fixture)
2018-07-31 12:50:39 +00:00
2019-05-29 13:40:20 +00:00
Turns isset comparisons to their method name alternatives in PHPUnit TestCase
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
2019-05-29 13:40:20 +00:00
-$this->assertTrue(isset($anything->foo));
2019-09-21 22:14:49 +00:00
+$this->assertObjectHasAttribute("foo", $anything);
2018-10-12 23:15:00 +00:00
```
```diff
2019-09-21 22:14:49 +00:00
-$this->assertFalse(isset($anything["foo"]), "message");
2019-05-29 13:40:20 +00:00
+$this->assertArrayNotHasKey("foo", $anything, "message");
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-07-31 12:50:39 +00:00
### `AssertNotOperatorRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertNotOperatorRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertNotOperatorRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertNotOperatorRector/Fixture)
Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase
2018-10-12 23:15:00 +00:00
2018-10-21 22:26:45 +00:00
```diff
-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
2018-10-21 22:26:45 +00:00
```
2018-10-12 23:15:00 +00:00
```diff
-$this->assertFalse(!$foo, "message");
+$this->assertTrue($foo, "message");
```
2018-10-12 23:15:00 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
### `AssertPropertyExistsRector`
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertPropertyExistsRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertPropertyExistsRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertPropertyExistsRector/Fixture)
Turns `property_exists` comparisons to their method name alternatives in PHPUnit TestCase
2018-10-12 23:15:00 +00:00
```diff
-$this->assertTrue(property_exists(new Class, "property"), "message");
+$this->assertClassHasAttribute("property", "Class", "message");
2018-10-12 23:15:00 +00:00
```
```diff
-$this->assertFalse(property_exists(new Class, "property"), "message");
+$this->assertClassNotHasAttribute("property", "Class", "message");
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `AssertRegExpRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertRegExpRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertRegExpRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertRegExpRector/Fixture)
2018-10-12 23:15:00 +00:00
2019-05-29 13:40:20 +00:00
Turns `preg_match` comparisons to their method name alternatives in PHPUnit TestCase
2018-10-12 23:15:00 +00:00
```diff
2019-05-29 13:40:20 +00:00
-$this->assertSame(1, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertRegExp("/^Message for ".*"\.$/", $string, $message);
2018-10-12 23:15:00 +00:00
```
```diff
2019-05-29 13:40:20 +00:00
-$this->assertEquals(false, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertNotRegExp("/^Message for ".*"\.$/", $string, $message);
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `AssertSameBoolNullToSpecificMethodRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertSameBoolNullToSpecificMethodRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertSameBoolNullToSpecificMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertSameBoolNullToSpecificMethodRector/Fixture)
2018-10-12 23:15:00 +00:00
Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase
2018-10-12 23:15:00 +00:00
```diff
-$this->assertSame(null, $anything);
+$this->assertNull($anything);
2018-10-12 23:15:00 +00:00
```
```diff
-$this->assertNotSame(false, $anything);
+$this->assertNotFalse($anything);
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-12 23:15:00 +00:00
### `AssertTrueFalseInternalTypeToSpecificMethodRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertTrueFalseInternalTypeToSpecificMethodRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertTrueFalseInternalTypeToSpecificMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertTrueFalseInternalTypeToSpecificMethodRector/Fixture)
Turns true/false with internal type comparisons to their method name alternatives in PHPUnit TestCase
2018-10-12 23:15:00 +00:00
```diff
-$this->assertTrue(is_{internal_type}($anything), "message");
+$this->assertInternalType({internal_type}, $anything, "message");
2018-10-12 23:15:00 +00:00
```
```diff
-$this->assertFalse(is_{internal_type}($anything), "message");
+$this->assertNotInternalType({internal_type}, $anything, "message");
```
2020-06-16 16:14:51 +00:00
<br><br>
### `AssertTrueFalseToSpecificMethodRector`
- class: [`Rector\PHPUnit\Rector\SpecificMethod\AssertTrueFalseToSpecificMethodRector`](/../master/rules/phpunit/src/Rector/SpecificMethod/AssertTrueFalseToSpecificMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/SpecificMethod/AssertTrueFalseToSpecificMethodRector/Fixture)
Turns true/false comparisons to their method name alternatives in PHPUnit TestCase when possible
```diff
-$this->assertTrue(is_readable($readmeFile), "message");
+$this->assertIsReadable($readmeFile, "message");
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-03-23 16:13:04 +00:00
### `CreateMockToCreateStubRector`
- class: [`Rector\PHPUnit\Rector\MethodCall\CreateMockToCreateStubRector`](/../master/rules/phpunit/src/Rector/MethodCall/CreateMockToCreateStubRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/CreateMockToCreateStubRector/Fixture)
2020-06-21 14:49:47 +00:00
Replaces `createMock()` with `createStub()` when relevant
2020-03-23 16:13:04 +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());
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-03-23 16:13:04 +00:00
### `DelegateExceptionArgumentsRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\DelegateExceptionArgumentsRector`](/../master/rules/phpunit/src/Rector/DelegateExceptionArgumentsRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/DelegateExceptionArgumentsRector/Fixture)
2018-10-12 23:15:00 +00:00
Takes `setExpectedException()` 2nd and next arguments to own methods in PHPUnit.
2019-05-29 13:40:20 +00:00
```diff
-$this->setExpectedException(Exception::class, "Message", "CODE");
+$this->setExpectedException(Exception::class);
+$this->expectExceptionMessage("Message");
+$this->expectExceptionCode("CODE");
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `EnsureDataProviderInDocBlockRector`
- class: [`Rector\PHPUnit\Rector\ClassMethod\EnsureDataProviderInDocBlockRector`](/../master/rules/phpunit/src/Rector/ClassMethod/EnsureDataProviderInDocBlockRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/ClassMethod/EnsureDataProviderInDocBlockRector/Fixture)
2019-10-15 14:46:31 +00:00
Data provider annotation must be in doc block
```diff
class SomeClass extends PHPUnit\Framework\TestCase
{
- /*
+ /**
* @dataProvider testProvideData()
*/
public function test()
{
$nothing = 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `ExceptionAnnotationRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\ExceptionAnnotationRector`](/../master/rules/phpunit/src/Rector/ExceptionAnnotationRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/ExceptionAnnotationRector/Fixture)
2018-10-12 23:15:00 +00:00
2020-07-07 10:15:52 +00:00
Changes `@expectedException annotations to expectException*() methods
2019-05-29 13:40:20 +00:00
```diff
-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
public function test()
{
+ $this->expectException('Exception');
+ $this->expectExceptionMessage('Message');
// tested code
}
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ExplicitPhpErrorApiRector`
- class: [`Rector\PHPUnit\Rector\MethodCall\ExplicitPhpErrorApiRector`](/../master/rules/phpunit/src/Rector/MethodCall/ExplicitPhpErrorApiRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/ExplicitPhpErrorApiRector/Fixture)
Use explicit API for expecting PHP errors, warnings, and notices
```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();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `GetMockBuilderGetMockToCreateMockRector`
- class: [`Rector\PHPUnit\Rector\MethodCall\GetMockBuilderGetMockToCreateMockRector`](/../master/rules/phpunit/src/Rector/MethodCall/GetMockBuilderGetMockToCreateMockRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/GetMockBuilderGetMockToCreateMockRector/Fixture)
2020-06-21 14:49:47 +00:00
Remove `getMockBuilder()` to `createMock()`
```diff
class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
- $applicationMock = $this->getMockBuilder('SomeClass')
- ->disableOriginalConstructor()
- ->getMock();
+ $applicationMock = $this->createMock('SomeClass');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `GetMockRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\GetMockRector`](/../master/rules/phpunit/src/Rector/GetMockRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/GetMockRector/Fixture)
2018-10-12 23:15:00 +00:00
2020-07-07 10:15:52 +00:00
Turns getMock*() methods to `createMock()`
2018-10-12 23:15:00 +00:00
```diff
-$this->getMock("Class");
+$this->createMock("Class");
2018-10-12 23:15:00 +00:00
```
```diff
-$this->getMockWithoutInvokingTheOriginalConstructor("Class");
+$this->createMock("Class");
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-23 18:58:57 +00:00
2019-10-15 14:46:31 +00:00
### `RemoveDataProviderTestPrefixRector`
- class: [`Rector\PHPUnit\Rector\Class_\RemoveDataProviderTestPrefixRector`](/../master/rules/phpunit/src/Rector/Class_/RemoveDataProviderTestPrefixRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/Class_/RemoveDataProviderTestPrefixRector/Fixture)
2019-10-15 14:46:31 +00:00
Data provider methods cannot start with "test" prefix
```diff
class SomeClass extends PHPUnit\Framework\TestCase
{
/**
- * @dataProvider testProvideData()
+ * @dataProvider provideData()
*/
public function test()
{
$nothing = 5;
}
- public function testProvideData()
+ public function provideData()
{
return ['123'];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `RemoveEmptyTestMethodRector`
- class: [`Rector\PHPUnit\Rector\ClassMethod\RemoveEmptyTestMethodRector`](/../master/rules/phpunit/src/Rector/ClassMethod/RemoveEmptyTestMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/ClassMethod/RemoveEmptyTestMethodRector/Fixture)
Remove empty test methods
```diff
class SomeTest extends \PHPUnit\Framework\TestCase
{
- /**
- * testGetTranslatedModelField method
- *
- * @return void
- */
- public function testGetTranslatedModelField()
- {
- }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveExpectAnyFromMockRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\RemoveExpectAnyFromMockRector`](/../master/rules/phpunit/src/Rector/MethodCall/RemoveExpectAnyFromMockRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/RemoveExpectAnyFromMockRector/Fixture)
2019-05-29 13:40:20 +00:00
Remove `expect($this->any())` from mocks as it has no added value
2019-05-29 13:40:20 +00:00
```diff
use PHPUnit\Framework\TestCase;
2019-05-29 13:40:20 +00:00
class SomeClass extends TestCase
2019-03-31 12:25:39 +00:00
{
public function test()
2019-03-31 12:25:39 +00:00
{
$translator = $this->getMock('SomeClass');
- $translator->expects($this->any())
- ->method('trans')
+ $translator->method('trans')
->willReturn('translated max {{ max }}!');
2019-03-31 12:25:39 +00:00
}
2019-05-29 13:40:20 +00:00
}
```
2019-03-31 12:25:39 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `ReplaceAssertArraySubsetRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\ReplaceAssertArraySubsetRector`](/../master/rules/phpunit/src/Rector/MethodCall/ReplaceAssertArraySubsetRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/ReplaceAssertArraySubsetRector/Fixture)
2019-05-29 13:40:20 +00:00
Replace deprecated "assertArraySubset()" method with alternative methods
2019-05-29 13:40:20 +00:00
```diff
class SomeTest extends \PHPUnit\Framework\TestCase
2019-05-29 13:40:20 +00:00
{
public function test()
2019-03-31 12:25:39 +00:00
{
$checkedArray = [];
- $this->assertArraySubset([
- 'cache_directory' => 'new_value',
- ], $checkedArray, true);
+ $this->assertArrayHasKey('cache_directory', $checkedArray);
+ $this->assertSame('new_value', $checkedArray['cache_directory']);
2019-03-31 12:25:39 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
### `ReplaceAssertArraySubsetWithDmsPolyfillRector`
- class: [`Rector\PHPUnit\Rector\MethodCall\ReplaceAssertArraySubsetWithDmsPolyfillRector`](/../master/rules/phpunit/src/Rector/MethodCall/ReplaceAssertArraySubsetWithDmsPolyfillRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/ReplaceAssertArraySubsetWithDmsPolyfillRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `assertArraySubset()` to static call of DMS\PHPUnitExtensions\ArraySubset\Assert
```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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SelfContainerGetMethodCallFromTestToInjectPropertyRector`
- class: [`Rector\PHPUnit\Rector\Class_\SelfContainerGetMethodCallFromTestToInjectPropertyRector`](/../master/rules/phpunit/src/Rector/Class_/SelfContainerGetMethodCallFromTestToInjectPropertyRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/Class_/SelfContainerGetMethodCallFromTestToInjectPropertyRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `$container->get()` calls in PHPUnit to @inject properties autowired by jakzal/phpunit-injector
```diff
use PHPUnit\Framework\TestCase;
class SomeClassTest extends TestCase {
+ /**
+ * @var SomeService
+ * @inject
+ */
+ private $someService;
public function test()
{
- $someService = $this->getContainer()->get(SomeService::class);
+ $someService = $this->someService;
}
}
class SomeService { }
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyForeachInstanceOfRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\Foreach_\SimplifyForeachInstanceOfRector`](/../master/rules/phpunit/src/Rector/Foreach_/SimplifyForeachInstanceOfRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/Foreach_/SimplifyForeachInstanceOfRector/Fixture)
2018-10-12 23:15:00 +00:00
Simplify unnecessary foreach check of instances
2018-10-12 23:15:00 +00:00
```diff
-foreach ($foos as $foo) {
- $this->assertInstanceOf(\SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SpecificAssertContainsRector`
2019-01-22 20:34:38 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\SpecificAssertContainsRector`](/../master/rules/phpunit/src/Rector/MethodCall/SpecificAssertContainsRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/SpecificAssertContainsRector/Fixture)
2019-01-22 20:34:38 +00:00
2020-06-21 14:49:47 +00:00
Change `assertContains()/assertNotContains()` method to new string and iterable alternatives
2019-01-22 20:34:38 +00:00
```diff
<?php
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');
}
}
2019-01-22 20:34:38 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-01-22 20:34:38 +00:00
### `SpecificAssertContainsWithoutIdentityRector`
- class: [`Rector\PHPUnit\Rector\MethodCall\SpecificAssertContainsWithoutIdentityRector`](/../master/rules/phpunit/src/Rector/MethodCall/SpecificAssertContainsWithoutIdentityRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/SpecificAssertContainsWithoutIdentityRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `assertContains()/assertNotContains()` with non-strict comparison to new specific alternatives
```diff
<?php
-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');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SpecificAssertInternalTypeRector`
2018-12-14 19:35:35 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\SpecificAssertInternalTypeRector`](/../master/rules/phpunit/src/Rector/MethodCall/SpecificAssertInternalTypeRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/SpecificAssertInternalTypeRector/Fixture)
2018-12-14 19:35:35 +00:00
2020-06-21 14:49:47 +00:00
Change `assertInternalType()/assertNotInternalType()` method to new specific alternatives
2018-12-14 19:35:35 +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);
}
}
2018-12-14 19:35:35 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-14 19:35:35 +00:00
### `TestListenerToHooksRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\Class_\TestListenerToHooksRector`](/../master/rules/phpunit/src/Rector/Class_/TestListenerToHooksRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/Class_/TestListenerToHooksRector/Fixture)
2018-10-12 23:15:00 +00:00
Refactor "*TestListener.php" to particular "*Hook.php" files
2018-10-12 23:15:00 +00:00
```diff
namespace App\Tests;
2019-05-29 13:40:20 +00:00
-use PHPUnit\Framework\TestListener;
-
-final class BeforeListHook implements TestListener
+final class BeforeListHook implements \PHPUnit\Runner\BeforeTestHook, \PHPUnit\Runner\AfterTestHook
2019-05-29 13:40:20 +00:00
{
- public function addError(Test $test, \Throwable $t, float $time): void
+ public function executeBeforeTest(Test $test): void
2019-05-29 13:40:20 +00:00
{
- }
-
- 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-05-29 13:40:20 +00:00
}
}
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `TryCatchToExpectExceptionRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\PHPUnit\Rector\TryCatchToExpectExceptionRector`](/../master/rules/phpunit/src/Rector/TryCatchToExpectExceptionRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/TryCatchToExpectExceptionRector/Fixture)
2018-10-12 23:15:00 +00:00
2020-06-21 14:49:47 +00:00
Turns try/catch to `expectException()` call
2018-10-12 23:15:00 +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();
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `UseSpecificWillMethodRector`
2018-07-31 12:50:39 +00:00
- class: [`Rector\PHPUnit\Rector\MethodCall\UseSpecificWillMethodRector`](/../master/rules/phpunit/src/Rector/MethodCall/UseSpecificWillMethodRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/UseSpecificWillMethodRector/Fixture)
2018-07-31 12:50:39 +00:00
Changes ->will($this->xxx()) to one specific method
2018-08-01 20:09:34 +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 }}!');
}
}
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
### `WithConsecutiveArgToArrayRector`
- class: [`Rector\PHPUnit\Rector\MethodCall\WithConsecutiveArgToArrayRector`](/../master/rules/phpunit/src/Rector/MethodCall/WithConsecutiveArgToArrayRector.php)
- [test fixtures](/../master/rules/phpunit/tests/Rector/MethodCall/WithConsecutiveArgToArrayRector/Fixture)
2019-11-06 23:52:19 +00:00
2020-06-21 14:49:47 +00:00
Split `withConsecutive()` arg to array
2019-11-06 23:52:19 +00:00
```diff
class SomeClass
{
public function run($one, $two)
{
}
}
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]);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
2019-08-05 21:10:47 +00:00
## PHPUnitSymfony
### `AddMessageToEqualsResponseCodeRector`
- class: [`Rector\PHPUnitSymfony\Rector\StaticCall\AddMessageToEqualsResponseCodeRector`](/../master/rules/phpunit-symfony/src/Rector/StaticCall/AddMessageToEqualsResponseCodeRector.php)
- [test fixtures](/../master/rules/phpunit-symfony/tests/Rector/StaticCall/AddMessageToEqualsResponseCodeRector/Fixture)
2019-08-05 21:10:47 +00:00
Add response content to response code assert, so it is easier to debug
```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()
);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
## PSR4
### `MultipleClassFileToPsr4ClassesRector`
- class: [`Rector\PSR4\Rector\MultipleClassFileToPsr4ClassesRector`](/../master/rules/psr4/src/Rector/MultipleClassFileToPsr4ClassesRector.php)
Turns namespaced classes in one file to standalone PSR-4 classes.
```diff
+// new file: "app/Exceptions/FirstException.php"
namespace App\Exceptions;
use Exception;
final class FirstException extends Exception
{
}
+
+// new file: "app/Exceptions/SecondException.php"
+namespace App\Exceptions;
+
+use Exception;
final class SecondException extends Exception
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `NormalizeNamespaceByPSR4ComposerAutoloadFileSystemRector`
- class: [`Rector\PSR4\Rector\FileSystem\NormalizeNamespaceByPSR4ComposerAutoloadFileSystemRector`](/../master/rules/psr4/src/Rector/FileSystem/NormalizeNamespaceByPSR4ComposerAutoloadFileSystemRector.php)
- [test fixtures](/../master/rules/psr4/tests/Rector/FileSystem/NormalizeNamespaceByPSR4ComposerAutoloadFileSystemRector/Fixture)
2020-06-16 14:39:45 +00:00
Adds namespace to namespace-less files to match PSR-4 in `composer.json` autoload section. Run with combination with `Rector\PSR4\Rector\MultipleClassFileToPsr4ClassesRector`
```diff
// src/SomeClass.php
+namespace App\CustomNamespace;
+
class SomeClass
{
}
```
2020-06-16 16:13:37 +00:00
`composer.json`
```json
{
"autoload": {
"psr-4": {
"App\\CustomNamespace\\": "src"
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `NormalizeNamespaceByPSR4ComposerAutoloadRector`
- class: [`Rector\PSR4\Rector\Namespace_\NormalizeNamespaceByPSR4ComposerAutoloadRector`](/../master/rules/psr4/src/Rector/Namespace_/NormalizeNamespaceByPSR4ComposerAutoloadRector.php)
- [test fixtures](/../master/rules/psr4/tests/Rector/Namespace_/NormalizeNamespaceByPSR4ComposerAutoloadRector/Fixture)
Changes namespace and class names to match PSR-4 in `composer.json` autoload section
```diff
// src/SomeClass.php
-namespace App\DifferentNamespace;
+namespace App\CustomNamespace;
class SomeClass
{
}
```
2020-06-16 16:13:37 +00:00
`composer.json`
```json
{
"autoload": {
"psr-4": {
"App\\CustomNamespace\\": "src"
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## Performance
### `PreslashSimpleFunctionRector`
- class: [`Rector\Performance\Rector\FuncCall\PreslashSimpleFunctionRector`](/../master/rules/performance/src/Rector/FuncCall/PreslashSimpleFunctionRector.php)
- [test fixtures](/../master/rules/performance/tests/Rector/FuncCall/PreslashSimpleFunctionRector/Fixture)
Add pre-slash to short named functions to improve performance
```diff
class SomeClass
{
public function shorten($value)
{
- return trim($value);
+ return \trim($value);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
## Phalcon
### `AddRequestToHandleMethodCallRector`
- class: [`Rector\Phalcon\Rector\MethodCall\AddRequestToHandleMethodCallRector`](/../master/rules/phalcon/src/Rector/MethodCall/AddRequestToHandleMethodCallRector.php)
- [test fixtures](/../master/rules/phalcon/tests/Rector/MethodCall/AddRequestToHandleMethodCallRector/Fixture)
2019-12-18 09:53:46 +00:00
Add $_SERVER REQUEST_URI to method call
```diff
class SomeClass {
public function run($di)
{
$application = new \Phalcon\Mvc\Application();
- $response = $application->handle();
+ $response = $application->handle($_SERVER["REQUEST_URI"]);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
### `DecoupleSaveMethodCallWithArgumentToAssignRector`
- class: [`Rector\Phalcon\Rector\MethodCall\DecoupleSaveMethodCallWithArgumentToAssignRector`](/../master/rules/phalcon/src/Rector/MethodCall/DecoupleSaveMethodCallWithArgumentToAssignRector.php)
- [test fixtures](/../master/rules/phalcon/tests/Rector/MethodCall/DecoupleSaveMethodCallWithArgumentToAssignRector/Fixture)
2020-06-21 14:49:47 +00:00
Decouple `Phalcon\Mvc\Model::save()` with argument to `assign()`
```diff
class SomeClass
{
public function run(\Phalcon\Mvc\Model $model, $data)
{
- $model->save($data);
+ $model->save();
+ $model->assign($data);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
### `FlashWithCssClassesToExtraCallRector`
- class: [`Rector\Phalcon\Rector\Assign\FlashWithCssClassesToExtraCallRector`](/../master/rules/phalcon/src/Rector/Assign/FlashWithCssClassesToExtraCallRector.php)
- [test fixtures](/../master/rules/phalcon/tests/Rector/Assign/FlashWithCssClassesToExtraCallRector/Fixture)
2019-12-18 09:53:46 +00:00
2020-07-07 10:15:52 +00:00
Add `$cssClasses` in Flash to separated method call
2019-12-18 09:53:46 +00:00
```diff
class SomeClass {
public function run()
{
$cssClasses = [];
- $flash = new Phalcon\Flash($cssClasses);
+ $flash = new Phalcon\Flash();
+ $flash->setCssClasses($cssClasses);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
### `NewApplicationToToFactoryWithDefaultContainerRector`
- class: [`Rector\Phalcon\Rector\Assign\NewApplicationToToFactoryWithDefaultContainerRector`](/../master/rules/phalcon/src/Rector/Assign/NewApplicationToToFactoryWithDefaultContainerRector.php)
- [test fixtures](/../master/rules/phalcon/tests/Rector/Assign/NewApplicationToToFactoryWithDefaultContainerRector/Fixture)
2019-12-18 09:53:46 +00:00
Change new application to default factory with application
```diff
class SomeClass
{
public function run($di)
{
- $application = new \Phalcon\Mvc\Application($di);
+ $container = new \Phalcon\Di\FactoryDefault();
+ $application = new \Phalcon\Mvc\Application($container);
- $response = $application->handle();
+ $response = $application->handle($_SERVER["REQUEST_URI"]);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
2019-09-25 08:49:53 +00:00
## Php52
2019-09-25 08:49:53 +00:00
### `ContinueToBreakInSwitchRector`
2019-01-22 20:34:38 +00:00
- class: [`Rector\Php52\Rector\Switch_\ContinueToBreakInSwitchRector`](/../master/rules/php52/src/Rector/Switch_/ContinueToBreakInSwitchRector.php)
- [test fixtures](/../master/rules/php52/tests/Rector/Switch_/ContinueToBreakInSwitchRector/Fixture)
2019-01-22 20:34:38 +00:00
2019-09-25 08:49:53 +00:00
Use break instead of continue in switch statements
2019-01-22 20:34:38 +00:00
```diff
2019-09-25 08:49:53 +00:00
function some_run($value)
2019-01-22 20:34:38 +00:00
{
2019-09-25 08:49:53 +00:00
switch ($value) {
case 1:
echo 'Hi';
- continue;
+ break;
case 2:
echo 'Hello';
break;
2019-01-22 20:34:38 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-01-22 20:34:38 +00:00
2019-09-25 08:49:53 +00:00
### `VarToPublicPropertyRector`
2019-08-24 11:08:59 +00:00
- class: [`Rector\Php52\Rector\Property\VarToPublicPropertyRector`](/../master/rules/php52/src/Rector/Property/VarToPublicPropertyRector.php)
- [test fixtures](/../master/rules/php52/tests/Rector/Property/VarToPublicPropertyRector/Fixture)
2019-08-24 11:08:59 +00:00
2019-09-25 08:49:53 +00:00
Remove unused private method
2019-08-24 11:08:59 +00:00
```diff
2019-09-25 08:49:53 +00:00
final class SomeController
2019-08-24 11:08:59 +00:00
{
2019-09-25 08:49:53 +00:00
- var $name = 'Tom';
+ public $name = 'Tom';
2019-08-24 11:08:59 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-24 11:08:59 +00:00
2019-09-25 08:49:53 +00:00
## Php53
2020-05-31 15:26:08 +00:00
### `ClearReturnNewByReferenceRector`
- class: [`Rector\Php53\Rector\Assign\ClearReturnNewByReferenceRector`](/../master/rules/php53/src/Rector/Assign/ClearReturnNewByReferenceRector.php)
- [test fixtures](/../master/rules/php53/tests/Rector/Assign/ClearReturnNewByReferenceRector/Fixture)
Remove reference from "$assign = &new Value;"
```diff
-$assign = &new Value;
+$assign = new Value;
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-31 15:26:08 +00:00
### `DirNameFileConstantToDirConstantRector`
- class: [`Rector\Php53\Rector\FuncCall\DirNameFileConstantToDirConstantRector`](/../master/rules/php53/src/Rector/FuncCall/DirNameFileConstantToDirConstantRector.php)
- [test fixtures](/../master/rules/php53/tests/Rector/FuncCall/DirNameFileConstantToDirConstantRector/Fixture)
Convert dirname(__FILE__) to __DIR__
```diff
class SomeClass
{
public function run()
{
- return dirname(__FILE__);
+ return __DIR__;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-31 15:45:51 +00:00
### `ReplaceHttpServerVarsByServerRector`
- class: [`Rector\Php53\Rector\Variable\ReplaceHttpServerVarsByServerRector`](/../master/rules/php53/src/Rector/Variable/ReplaceHttpServerVarsByServerRector.php)
- [test fixtures](/../master/rules/php53/tests/Rector/Variable/ReplaceHttpServerVarsByServerRector/Fixture)
2020-07-07 10:15:52 +00:00
Rename old `$HTTP_*` variable names to new replacements
2020-05-31 15:45:51 +00:00
```diff
-$serverVars = $HTTP_SERVER_VARS;
+$serverVars = $_SERVER;
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-31 15:45:51 +00:00
2019-09-25 08:49:53 +00:00
### `TernaryToElvisRector`
2018-07-31 12:50:39 +00:00
- class: [`Rector\Php53\Rector\Ternary\TernaryToElvisRector`](/../master/rules/php53/src/Rector/Ternary/TernaryToElvisRector.php)
- [test fixtures](/../master/rules/php53/tests/Rector/Ternary/TernaryToElvisRector/Fixture)
2018-07-31 12:50:39 +00:00
2019-09-25 08:49:53 +00:00
Use ?: instead of ?, where useful
2018-08-01 20:09:34 +00:00
```diff
2019-09-25 08:49:53 +00:00
function elvis()
{
- $value = $a ? $a : false;
+ $value = $a ?: false;
2018-10-12 23:15:00 +00:00
}
2019-05-19 08:27:38 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
2019-09-25 08:49:53 +00:00
## Php54
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
### `RemoveReferenceFromCallRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\Php54\Rector\FuncCall\RemoveReferenceFromCallRector`](/../master/rules/php54/src/Rector/FuncCall/RemoveReferenceFromCallRector.php)
- [test fixtures](/../master/rules/php54/tests/Rector/FuncCall/RemoveReferenceFromCallRector/Fixture)
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
Remove & from function and method calls
```diff
2019-09-25 08:49:53 +00:00
final class SomeClass
{
public function run($one)
{
- return strlen(&$one);
+ return strlen($one);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveZeroBreakContinueRector`
- class: [`Rector\Php54\Rector\Break_\RemoveZeroBreakContinueRector`](/../master/rules/php54/src/Rector/Break_/RemoveZeroBreakContinueRector.php)
- [test fixtures](/../master/rules/php54/tests/Rector/Break_/RemoveZeroBreakContinueRector/Fixture)
Remove 0 from break and continue
```diff
class SomeClass
{
public function run($random)
{
- continue 0;
- break 0;
+ continue;
+ break;
$five = 5;
- continue $five;
+ continue 5;
- break $random;
+ break;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
## Php55
2019-02-21 14:36:16 +00:00
2019-09-25 08:49:53 +00:00
### `PregReplaceEModifierRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\Php55\Rector\FuncCall\PregReplaceEModifierRector`](/../master/rules/php55/src/Rector/FuncCall/PregReplaceEModifierRector.php)
- [test fixtures](/../master/rules/php55/tests/Rector/FuncCall/PregReplaceEModifierRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-16 14:39:45 +00:00
The /e modifier is no longer supported, use `preg_replace_callback` instead
2019-02-21 14:36:16 +00:00
```diff
class SomeClass
2019-02-21 14:36:16 +00:00
{
2019-09-25 08:49:53 +00:00
public function run()
2019-02-21 14:36:16 +00:00
{
2019-09-25 08:49:53 +00:00
- $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);
2019-05-01 23:56:58 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
2019-09-25 08:49:53 +00:00
### `StringClassNameToClassConstantRector`
- class: [`Rector\Php55\Rector\String_\StringClassNameToClassConstantRector`](/../master/rules/php55/src/Rector/String_/StringClassNameToClassConstantRector.php)
- [test fixtures](/../master/rules/php55/tests/Rector/String_/StringClassNameToClassConstantRector/Fixture)
2019-09-25 08:49:53 +00:00
Replace string class names by <class>::class constant
```diff
2019-09-25 08:49:53 +00:00
class AnotherClass
{
}
class SomeClass
{
public function run()
{
- return 'AnotherClass';
+ return \AnotherClass::class;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
## Php56
2019-09-25 08:49:53 +00:00
### `AddDefaultValueForUndefinedVariableRector`
- class: [`Rector\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector`](/../master/rules/php56/src/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php)
- [test fixtures](/../master/rules/php56/tests/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector/Fixture)
2019-09-25 08:49:53 +00:00
Adds default value for undefined variable
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
{
public function run()
{
+ $a = null;
if (rand(0, 1)) {
$a = 5;
}
echo $a;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `PowToExpRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\Php56\Rector\FuncCall\PowToExpRector`](/../master/rules/php56/src/Rector/FuncCall/PowToExpRector.php)
- [test fixtures](/../master/rules/php56/tests/Rector/FuncCall/PowToExpRector/Fixture)
2019-02-21 14:36:16 +00:00
2020-06-16 14:39:45 +00:00
Changes pow(val, val2) to ** `(exp)` parameter
2019-02-21 14:36:16 +00:00
```diff
2019-09-25 08:49:53 +00:00
-pow(1, 2);
+1**2;
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
## Php70
### `BreakNotInLoopOrSwitchToReturnRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Php70\Rector\Break_\BreakNotInLoopOrSwitchToReturnRector`](/../master/rules/php70/src/Rector/Break_/BreakNotInLoopOrSwitchToReturnRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/Break_/BreakNotInLoopOrSwitchToReturnRector/Fixture)
2019-05-29 13:40:20 +00:00
Convert break outside for/foreach/switch context to return
```diff
class SomeClass
{
public function run()
{
if ($isphp5)
2020-04-23 20:35:01 +00:00
return 1;
else
2020-04-23 20:35:01 +00:00
return 2;
- break;
+ return;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CallUserMethodRector`
- class: [`Rector\Php70\Rector\FuncCall\CallUserMethodRector`](/../master/rules/php70/src/Rector/FuncCall/CallUserMethodRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FuncCall/CallUserMethodRector/Fixture)
2020-06-21 14:49:47 +00:00
Changes `call_user_method()/call_user_method_array()` to `call_user_func()/call_user_func_array()`
```diff
-call_user_method($method, $obj, "arg1", "arg2");
+call_user_func(array(&$obj, "method"), "arg1", "arg2");
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `EmptyListRector`
2019-03-09 13:24:30 +00:00
- class: [`Rector\Php70\Rector\List_\EmptyListRector`](/../master/rules/php70/src/Rector/List_/EmptyListRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/List_/EmptyListRector/Fixture)
2019-03-09 13:24:30 +00:00
2020-06-21 14:49:47 +00:00
`list()` cannot be empty
2019-03-09 13:24:30 +00:00
```diff
-'list() = $values;'
+'list($unusedGenerated) = $values;'
2019-03-09 13:24:30 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
2019-09-25 08:49:53 +00:00
### `EregToPregMatchRector`
- class: [`Rector\Php70\Rector\FuncCall\EregToPregMatchRector`](/../master/rules/php70/src/Rector/FuncCall/EregToPregMatchRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FuncCall/EregToPregMatchRector/Fixture)
2020-07-07 10:15:52 +00:00
Changes ereg*() to preg*() calls
```diff
2019-09-25 08:49:53 +00:00
-ereg("hi")
+preg_match("#hi#");
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `ExceptionHandlerTypehintRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\Php70\Rector\FunctionLike\ExceptionHandlerTypehintRector`](/../master/rules/php70/src/Rector/FunctionLike/ExceptionHandlerTypehintRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FunctionLike/ExceptionHandlerTypehintRector/Fixture)
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
Changes property `@var` annotations from annotation to type.
2018-12-31 11:50:32 +00:00
```diff
2019-09-25 08:49:53 +00:00
-function handler(Exception $exception) { ... }
+function handler(Throwable $exception) { ... }
set_exception_handler('handler');
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `IfToSpaceshipRector`
- class: [`Rector\Php70\Rector\If_\IfToSpaceshipRector`](/../master/rules/php70/src/Rector/If_/IfToSpaceshipRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/If_/IfToSpaceshipRector/Fixture)
2019-09-25 08:49:53 +00:00
Changes if/else to spaceship <=> where useful
```diff
class SomeClass
{
public function run()
{
2019-09-25 08:49:53 +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];
});
}
}
2018-12-31 11:50:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
### `ListSplitStringRector`
2019-05-24 20:30:15 +00:00
- class: [`Rector\Php70\Rector\List_\ListSplitStringRector`](/../master/rules/php70/src/Rector/List_/ListSplitStringRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/List_/ListSplitStringRector/Fixture)
2019-05-24 20:30:15 +00:00
2020-06-21 14:49:47 +00:00
`list()` cannot split string directly anymore, use `str_split()`
2019-05-24 20:30:15 +00:00
```diff
2019-09-25 08:49:53 +00:00
-list($foo) = "string";
+list($foo) = str_split("string");
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-07-31 12:50:39 +00:00
2019-09-25 08:49:53 +00:00
### `ListSwapArrayOrderRector`
- class: [`Rector\Php70\Rector\List_\ListSwapArrayOrderRector`](/../master/rules/php70/src/Rector/List_/ListSwapArrayOrderRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/List_/ListSwapArrayOrderRector/Fixture)
2020-06-21 14:49:47 +00:00
`list()` assigns variables in reverse order - relevant in array assign
2018-08-01 20:09:34 +00:00
```diff
2019-09-25 08:49:53 +00:00
-list($a[], $a[]) = [1, 2];
+list($a[], $a[]) = array_reverse([1, 2]);
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `MultiDirnameRector`
2018-07-31 12:50:39 +00:00
- class: [`Rector\Php70\Rector\FuncCall\MultiDirnameRector`](/../master/rules/php70/src/Rector/FuncCall/MultiDirnameRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FuncCall/MultiDirnameRector/Fixture)
2018-07-31 12:50:39 +00:00
2020-06-16 14:39:45 +00:00
Changes multiple `dirname()` calls to one with nesting level
```diff
2019-09-25 08:49:53 +00:00
-dirname(dirname($path));
+dirname($path, 2);
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `NonVariableToVariableOnFunctionCallRector`
- class: [`Rector\Php70\Rector\FuncCall\NonVariableToVariableOnFunctionCallRector`](/../master/rules/php70/src/Rector/FuncCall/NonVariableToVariableOnFunctionCallRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FuncCall/NonVariableToVariableOnFunctionCallRector/Fixture)
Transform non variable like arguments to variable where a function or method expects an argument passed by reference
```diff
-reset(a());
+$a = a(); reset($a);
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `Php4ConstructorRector`
- class: [`Rector\Php70\Rector\FunctionLike\Php4ConstructorRector`](/../master/rules/php70/src/Rector/FunctionLike/Php4ConstructorRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FunctionLike/Php4ConstructorRector/Fixture)
2019-09-25 08:49:53 +00:00
Changes PHP 4 style constructor to __construct.
```diff
class SomeClass
{
2019-09-25 08:49:53 +00:00
- public function SomeClass()
+ public function __construct()
{
}
}
2018-10-21 22:26:45 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
2019-09-25 08:49:53 +00:00
### `RandomFunctionRector`
2018-10-21 22:26:45 +00:00
- class: [`Rector\Php70\Rector\FuncCall\RandomFunctionRector`](/../master/rules/php70/src/Rector/FuncCall/RandomFunctionRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FuncCall/RandomFunctionRector/Fixture)
2018-10-21 22:26:45 +00:00
2020-06-16 14:39:45 +00:00
Changes rand, `srand` and `getrandmax` by new mt_* alternatives.
2018-10-21 22:26:45 +00:00
2018-10-23 18:58:57 +00:00
```diff
2019-09-25 08:49:53 +00:00
-rand();
+mt_rand();
2018-10-23 18:58:57 +00:00
```
2018-10-21 22:26:45 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-21 22:26:45 +00:00
2019-09-25 08:49:53 +00:00
### `ReduceMultipleDefaultSwitchRector`
- class: [`Rector\Php70\Rector\Switch_\ReduceMultipleDefaultSwitchRector`](/../master/rules/php70/src/Rector/Switch_/ReduceMultipleDefaultSwitchRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/Switch_/ReduceMultipleDefaultSwitchRector/Fixture)
2019-09-25 08:49:53 +00:00
Remove first default switch, that is ignored
```diff
2019-09-25 08:49:53 +00:00
switch ($expr) {
default:
- echo "Hello World";
-
- default:
echo "Goodbye Moon!";
break;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameMktimeWithoutArgsToTimeRector`
- class: [`Rector\Php70\Rector\FuncCall\RenameMktimeWithoutArgsToTimeRector`](/../master/rules/php70/src/Rector/FuncCall/RenameMktimeWithoutArgsToTimeRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/FuncCall/RenameMktimeWithoutArgsToTimeRector/Fixture)
2020-06-16 14:39:45 +00:00
Renames `mktime()` without arguments to `time()`
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
{
public function run()
{
$time = mktime(1, 2, 3);
- $nextTime = mktime();
+ $nextTime = time();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `StaticCallOnNonStaticToInstanceCallRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector`](/../master/rules/php70/src/Rector/StaticCall/StaticCallOnNonStaticToInstanceCallRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/StaticCall/StaticCallOnNonStaticToInstanceCallRector/Fixture)
2019-02-21 14:36:16 +00:00
2019-09-25 08:49:53 +00:00
Changes static call to instance call, where not useful
2019-02-21 14:36:16 +00:00
```diff
2019-09-25 08:49:53 +00:00
class Something
{
public function doWork()
{
}
}
class Another
{
public function run()
{
- return Something::doWork();
+ return (new Something)->doWork();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `TernaryToNullCoalescingRector`
- class: [`Rector\Php70\Rector\Ternary\TernaryToNullCoalescingRector`](/../master/rules/php70/src/Rector/Ternary/TernaryToNullCoalescingRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/Ternary/TernaryToNullCoalescingRector/Fixture)
2019-09-25 08:49:53 +00:00
Changes unneeded null check to ?? operator
```diff
2019-09-25 08:49:53 +00:00
-$value === null ? 10 : $value;
+$value ?? 10;
```
```diff
-isset($value) ? $value : 10;
+$value ?? 10;
2019-02-21 14:36:16 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
2019-09-25 08:49:53 +00:00
### `TernaryToSpaceshipRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\Php70\Rector\Ternary\TernaryToSpaceshipRector`](/../master/rules/php70/src/Rector/Ternary/TernaryToSpaceshipRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/Ternary/TernaryToSpaceshipRector/Fixture)
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
Use <=> spaceship instead of ternary with same effect
2018-12-31 11:50:32 +00:00
```diff
2019-09-25 08:49:53 +00:00
function order_func($a, $b) {
- return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
+ return $a <=> $b;
2019-09-21 22:14:49 +00:00
}
2018-12-31 11:50:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
### `ThisCallOnStaticMethodToStaticCallRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Php70\Rector\MethodCall\ThisCallOnStaticMethodToStaticCallRector`](/../master/rules/php70/src/Rector/MethodCall/ThisCallOnStaticMethodToStaticCallRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/MethodCall/ThisCallOnStaticMethodToStaticCallRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-21 14:49:47 +00:00
Changes `$this->call()` to static method to static call
2019-05-29 13:40:20 +00:00
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
2019-05-29 13:40:20 +00:00
{
2019-09-25 08:49:53 +00:00
public static function run()
{
- $this->eat();
2020-06-21 14:32:27 +00:00
+ static::eat();
2019-09-25 08:49:53 +00:00
}
public static function eat()
2019-05-29 13:40:20 +00:00
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `WrapVariableVariableNameInCurlyBracesRector`
- class: [`Rector\Php70\Rector\Variable\WrapVariableVariableNameInCurlyBracesRector`](/../master/rules/php70/src/Rector/Variable/WrapVariableVariableNameInCurlyBracesRector.php)
- [test fixtures](/../master/rules/php70/tests/Rector/Variable/WrapVariableVariableNameInCurlyBracesRector/Fixture)
Ensure variable variables are wrapped in curly braces
```diff
function run($foo)
{
- global $$foo->bar;
+ global ${$foo->bar};
}
```
<br><br>
2019-09-25 08:49:53 +00:00
## Php71
### `AssignArrayToStringRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Php71\Rector\Assign\AssignArrayToStringRector`](/../master/rules/php71/src/Rector/Assign/AssignArrayToStringRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/Assign/AssignArrayToStringRector/Fixture)
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
String cannot be turned into array by assignment anymore
```diff
-$string = '';
+$string = [];
$string[] = 1;
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `BinaryOpBetweenNumberAndStringRector`
- class: [`Rector\Php71\Rector\BinaryOp\BinaryOpBetweenNumberAndStringRector`](/../master/rules/php71/src/Rector/BinaryOp/BinaryOpBetweenNumberAndStringRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/BinaryOp/BinaryOpBetweenNumberAndStringRector/Fixture)
2019-09-25 08:49:53 +00:00
Change binary operation between some number + string to PHP 7.1 compatible version
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run()
{
2019-09-25 08:49:53 +00:00
- $value = 5 + '';
- $value = 5.0 + 'hi';
+ $value = 5 + 0;
+ $value = 5.0 + 0
}
2019-05-29 13:40:20 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
### `CountOnNullRector`
2019-05-19 08:27:38 +00:00
- class: [`Rector\Php71\Rector\FuncCall\CountOnNullRector`](/../master/rules/php71/src/Rector/FuncCall/CountOnNullRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/FuncCall/CountOnNullRector/Fixture)
2019-05-19 08:27:38 +00:00
2020-06-16 14:39:45 +00:00
Changes `count()` on null to safe ternary check
2019-05-19 08:27:38 +00:00
```diff
2019-09-25 08:49:53 +00:00
$values = null;
-$count = count($values);
+$count = is_array($values) || $values instanceof Countable ? count($values) : 0;
2019-05-19 08:27:38 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
### `IsIterableRector`
2018-10-23 18:58:57 +00:00
- class: [`Rector\Php71\Rector\BinaryOp\IsIterableRector`](/../master/rules/php71/src/Rector/BinaryOp/IsIterableRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/BinaryOp/IsIterableRector/Fixture)
2020-06-16 14:39:45 +00:00
Changes `is_array` + Traversable check to `is_iterable`
2018-10-21 22:26:45 +00:00
```diff
-is_array($foo) || $foo instanceof Traversable;
+is_iterable($foo);
2018-08-01 20:09:34 +00:00
```
2018-07-31 12:50:39 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
### `ListToArrayDestructRector`
- class: [`Rector\Php71\Rector\List_\ListToArrayDestructRector`](/../master/rules/php71/src/Rector/List_/ListToArrayDestructRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/List_/ListToArrayDestructRector/Fixture)
Remove & from new &X
```diff
class SomeClass
{
public function run()
{
- list($id1, $name1) = $data;
+ [$id1, $name1] = $data;
- foreach ($data as list($id, $name)) {
+ foreach ($data as [$id, $name]) {
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `MultiExceptionCatchRector`
- class: [`Rector\Php71\Rector\TryCatch\MultiExceptionCatchRector`](/../master/rules/php71/src/Rector/TryCatch/MultiExceptionCatchRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/TryCatch/MultiExceptionCatchRector/Fixture)
2018-07-31 12:50:39 +00:00
2019-09-25 08:49:53 +00:00
Changes multi catch of same exception to single one | separated.
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
2019-09-25 08:49:53 +00:00
try {
// Some code...
-} catch (ExceptionType1 $exception) {
- $sameCode;
-} catch (ExceptionType2 $exception) {
+} catch (ExceptionType1 | ExceptionType2 $exception) {
$sameCode;
}
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `PublicConstantVisibilityRector`
- class: [`Rector\Php71\Rector\ClassConst\PublicConstantVisibilityRector`](/../master/rules/php71/src/Rector/ClassConst/PublicConstantVisibilityRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/ClassConst/PublicConstantVisibilityRector/Fixture)
2019-09-25 08:49:53 +00:00
Add explicit public constant visibility.
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
{
- const HEY = 'you';
+ public const HEY = 'you';
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RemoveExtraParametersRector`
- class: [`Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector`](/../master/rules/php71/src/Rector/FuncCall/RemoveExtraParametersRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/FuncCall/RemoveExtraParametersRector/Fixture)
2018-07-31 12:50:39 +00:00
2019-09-25 08:49:53 +00:00
Remove extra parameters
2018-07-31 12:50:39 +00:00
```diff
2019-09-25 08:49:53 +00:00
-strlen("asdf", 1);
+strlen("asdf");
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-12 23:15:00 +00:00
2019-09-25 08:49:53 +00:00
### `ReservedObjectRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\Php71\Rector\Name\ReservedObjectRector`](/../master/rules/php71/src/Rector/Name/ReservedObjectRector.php)
- [test fixtures](/../master/rules/php71/tests/Rector/Name/ReservedObjectRector/Fixture)
2019-09-25 08:49:53 +00:00
Changes reserved "Object" name to "<Smart>Object" where <Smart> can be configured
2018-10-12 23:15:00 +00:00
2018-08-01 20:09:34 +00:00
```diff
2019-09-25 08:49:53 +00:00
-class Object
+class SmartObject
{
}
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
## Php72
2019-03-09 13:24:30 +00:00
2019-09-25 08:49:53 +00:00
### `BarewordStringRector`
2019-03-09 13:24:30 +00:00
- class: [`Rector\Php72\Rector\ConstFetch\BarewordStringRector`](/../master/rules/php72/src/Rector/ConstFetch/BarewordStringRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/ConstFetch/BarewordStringRector/Fixture)
2019-09-25 08:49:53 +00:00
Changes unquoted non-existing constants to strings
2019-03-09 13:24:30 +00:00
```diff
2019-09-25 08:49:53 +00:00
-var_dump(VAR);
+var_dump("VAR");
2019-03-09 13:24:30 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-09 13:24:30 +00:00
2019-09-25 08:49:53 +00:00
### `CreateFunctionToAnonymousFunctionRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\Php72\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector`](/../master/rules/php72/src/Rector/FuncCall/CreateFunctionToAnonymousFunctionRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/FuncCall/CreateFunctionToAnonymousFunctionRector/Fixture)
2019-02-21 14:36:16 +00:00
2020-06-16 14:39:45 +00:00
Use anonymous functions instead of deprecated `create_function()`
2019-02-21 14:36:16 +00:00
```diff
2019-09-25 08:49:53 +00:00
class ClassWithCreateFunction
{
public function run()
{
- $callable = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);");
+ $callable = function($matches) use ($delimiter) {
+ return $delimiter . strtolower($matches[1]);
+ };
}
}
2018-08-01 20:09:34 +00:00
```
2018-07-31 12:50:39 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-12 23:15:00 +00:00
2019-09-25 08:49:53 +00:00
### `GetClassOnNullRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\Php72\Rector\FuncCall\GetClassOnNullRector`](/../master/rules/php72/src/Rector/FuncCall/GetClassOnNullRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/FuncCall/GetClassOnNullRector/Fixture)
2018-12-31 11:50:32 +00:00
2020-06-16 14:39:45 +00:00
Null is no more allowed in `get_class()`
2018-12-31 11:50:32 +00:00
```diff
2019-09-25 08:49:53 +00:00
final class SomeClass
{
public function getItem()
{
$value = null;
- return get_class($value);
+ return $value !== null ? get_class($value) : self::class;
}
}
2018-12-31 11:50:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
### `IsObjectOnIncompleteClassRector`
2018-10-12 23:15:00 +00:00
- class: [`Rector\Php72\Rector\FuncCall\IsObjectOnIncompleteClassRector`](/../master/rules/php72/src/Rector/FuncCall/IsObjectOnIncompleteClassRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/FuncCall/IsObjectOnIncompleteClassRector/Fixture)
2020-06-16 14:39:45 +00:00
Incomplete class returns inverted bool on `is_object()`
2018-10-12 23:15:00 +00:00
2018-08-01 20:09:34 +00:00
```diff
2019-09-25 08:49:53 +00:00
$incompleteObject = new __PHP_Incomplete_Class;
-$isObject = is_object($incompleteObject);
+$isObject = ! is_object($incompleteObject);
2018-05-05 12:48:33 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `ListEachRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\Php72\Rector\Each\ListEachRector`](/../master/rules/php72/src/Rector/Each/ListEachRector.php)
2020-06-05 10:33:30 +00:00
- [test fixtures](/../master/rules/php72/tests/Rector/Each/ListEachRector/Fixture)
2019-05-01 23:56:58 +00:00
2020-06-16 14:39:45 +00:00
`each()` function is deprecated, use `key()` and `current()` instead
2019-05-01 23:56:58 +00:00
```diff
2019-09-25 08:49:53 +00:00
-list($key, $callback) = each($callbacks);
+$key = key($callbacks);
+$callback = current($callbacks);
+next($callbacks);
2019-05-01 23:56:58 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
### `ParseStrWithResultArgumentRector`
- class: [`Rector\Php72\Rector\FuncCall\ParseStrWithResultArgumentRector`](/../master/rules/php72/src/Rector/FuncCall/ParseStrWithResultArgumentRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/FuncCall/ParseStrWithResultArgumentRector/Fixture)
2020-07-07 10:15:52 +00:00
Use `$result` argument in `parse_str()` function
```diff
-parse_str($this->query);
-$data = get_defined_vars();
+parse_str($this->query, $result);
+$data = $result;
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ReplaceEachAssignmentWithKeyCurrentRector`
- class: [`Rector\Php72\Rector\Each\ReplaceEachAssignmentWithKeyCurrentRector`](/../master/rules/php72/src/Rector/Each/ReplaceEachAssignmentWithKeyCurrentRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/Each/ReplaceEachAssignmentWithKeyCurrentRector/Fixture)
Replace `each()` assign outside loop
```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><br>
2019-09-25 08:49:53 +00:00
### `StringifyDefineRector`
2019-05-24 20:30:15 +00:00
- class: [`Rector\Php72\Rector\FuncCall\StringifyDefineRector`](/../master/rules/php72/src/Rector/FuncCall/StringifyDefineRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/FuncCall/StringifyDefineRector/Fixture)
2019-05-24 20:30:15 +00:00
2020-06-16 14:39:45 +00:00
Make first argument of `define()` string
2019-05-24 20:30:15 +00:00
```diff
class SomeClass
{
2019-09-25 08:49:53 +00:00
public function run(int $a)
{
2019-09-25 08:49:53 +00:00
- define(CONSTANT_2, 'value');
+ define('CONSTANT_2', 'value');
define('CONSTANT', 'value');
}
}
2019-05-24 20:30:15 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-24 20:30:15 +00:00
2019-09-25 08:49:53 +00:00
### `StringsAssertNakedRector`
- class: [`Rector\Php72\Rector\FuncCall\StringsAssertNakedRector`](/../master/rules/php72/src/Rector/FuncCall/StringsAssertNakedRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/FuncCall/StringsAssertNakedRector/Fixture)
2020-06-16 14:39:45 +00:00
String asserts must be passed directly to `assert()`
```diff
2019-09-25 08:49:53 +00:00
function nakedAssert()
{
- assert('true === true');
- assert("true === true");
+ assert(true === true);
+ assert(true === true);
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `UnsetCastRector`
- class: [`Rector\Php72\Rector\Unset_\UnsetCastRector`](/../master/rules/php72/src/Rector/Unset_/UnsetCastRector.php)
- [test fixtures](/../master/rules/php72/tests/Rector/Unset_/UnsetCastRector/Fixture)
2019-09-25 08:49:53 +00:00
Removes (unset) cast
```diff
-$different = (unset) $value;
+$different = null;
2019-09-25 08:49:53 +00:00
-$value = (unset) $value;
+unset($value);
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `WhileEachToForeachRector`
- class: [`Rector\Php72\Rector\Each\WhileEachToForeachRector`](/../master/rules/php72/src/Rector/Each/WhileEachToForeachRector.php)
2020-06-05 10:33:30 +00:00
- [test fixtures](/../master/rules/php72/tests/Rector/Each/WhileEachToForeachRector/Fixture)
2020-06-21 14:49:47 +00:00
`each()` function is deprecated, use `foreach()` instead.
```diff
2019-09-25 08:49:53 +00:00
-while (list($key, $callback) = each($callbacks)) {
+foreach ($callbacks as $key => $callback) {
// ...
}
```
```diff
2019-09-25 08:49:53 +00:00
-while (list($key) = each($callbacks)) {
+foreach (array_keys($callbacks) as $key) {
// ...
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
## Php73
2018-08-01 20:09:34 +00:00
2019-09-25 08:49:53 +00:00
### `ArrayKeyFirstLastRector`
2018-08-01 20:09:34 +00:00
- class: [`Rector\Php73\Rector\FuncCall\ArrayKeyFirstLastRector`](/../master/rules/php73/src/Rector/FuncCall/ArrayKeyFirstLastRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/FuncCall/ArrayKeyFirstLastRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-16 14:39:45 +00:00
Make use of `array_key_first()` and `array_key_last()`
2018-08-01 20:09:34 +00:00
```diff
2019-09-25 08:49:53 +00:00
-reset($items);
-$firstKey = key($items);
+$firstKey = array_key_first($items);
```
```diff
-end($items);
-$lastKey = key($items);
+$lastKey = array_key_last($items);
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `IsCountableRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\Php73\Rector\BinaryOp\IsCountableRector`](/../master/rules/php73/src/Rector/BinaryOp/IsCountableRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/BinaryOp/IsCountableRector/Fixture)
2019-05-01 23:56:58 +00:00
2020-06-16 14:39:45 +00:00
Changes `is_array` + Countable check to `is_countable`
2019-05-01 23:56:58 +00:00
```diff
2019-09-25 08:49:53 +00:00
-is_array($foo) || $foo instanceof Countable;
+is_countable($foo);
2019-05-01 23:56:58 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
2019-09-25 08:49:53 +00:00
### `JsonThrowOnErrorRector`
2018-12-31 19:29:12 +00:00
- class: [`Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector`](/../master/rules/php73/src/Rector/FuncCall/JsonThrowOnErrorRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/FuncCall/JsonThrowOnErrorRector/Fixture)
2018-12-31 19:29:12 +00:00
2020-06-16 14:39:45 +00:00
Adds JSON_THROW_ON_ERROR to `json_encode()` and `json_decode()` to throw JsonException on error
```diff
2019-09-25 08:49:53 +00:00
-json_encode($content);
-json_decode($json);
+json_encode($content, JSON_THROW_ON_ERROR);
+json_decode($json, null, null, JSON_THROW_ON_ERROR);
2018-12-31 19:29:12 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 19:29:12 +00:00
### `RegexDashEscapeRector`
- class: [`Rector\Php73\Rector\FuncCall\RegexDashEscapeRector`](/../master/rules/php73/src/Rector/FuncCall/RegexDashEscapeRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/FuncCall/RegexDashEscapeRector/Fixture)
Escape - in some cases
```diff
-preg_match("#[\w-()]#", 'some text');
+preg_match("#[\w\-()]#", 'some text');
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveMissingCompactVariableRector`
2018-08-01 20:09:34 +00:00
- class: [`Rector\Php73\Rector\FuncCall\RemoveMissingCompactVariableRector`](/../master/rules/php73/src/Rector/FuncCall/RemoveMissingCompactVariableRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/FuncCall/RemoveMissingCompactVariableRector/Fixture)
2018-08-01 20:09:34 +00:00
2020-06-16 14:39:45 +00:00
Remove non-existing vars from `compact()`
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run()
{
$value = 'yes';
- compact('value', 'non_existing');
+ compact('value');
2019-05-29 13:40:20 +00:00
}
}
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `SensitiveConstantNameRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\Php73\Rector\ConstFetch\SensitiveConstantNameRector`](/../master/rules/php73/src/Rector/ConstFetch/SensitiveConstantNameRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/ConstFetch/SensitiveConstantNameRector/Fixture)
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
Changes case insensitive constants to sensitive ones.
2018-12-31 11:50:32 +00:00
```diff
2019-09-25 08:49:53 +00:00
define('FOO', 42, true);
var_dump(FOO);
-var_dump(foo);
+var_dump(FOO);
2018-12-31 11:50:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
2019-09-25 08:49:53 +00:00
### `SensitiveDefineRector`
2019-02-21 14:36:16 +00:00
- class: [`Rector\Php73\Rector\FuncCall\SensitiveDefineRector`](/../master/rules/php73/src/Rector/FuncCall/SensitiveDefineRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/FuncCall/SensitiveDefineRector/Fixture)
2019-02-21 14:36:16 +00:00
2019-09-25 08:49:53 +00:00
Changes case insensitive constants to sensitive ones.
2019-02-21 14:36:16 +00:00
```diff
2019-09-25 08:49:53 +00:00
-define('FOO', 42, true);
+define('FOO', 42);
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
### `SensitiveHereNowDocRector`
- class: [`Rector\Php73\Rector\String_\SensitiveHereNowDocRector`](/../master/rules/php73/src/Rector/String_/SensitiveHereNowDocRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/String_/SensitiveHereNowDocRector/Fixture)
2019-09-25 08:49:53 +00:00
Changes heredoc/nowdoc that contains closing word to safe wrapper name
```diff
2019-09-25 08:49:53 +00:00
-$value = <<<A
+$value = <<<A_WRAP
A
-A
+A_WRAP
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-03-19 12:46:17 +00:00
### `SetCookieRector`
2020-01-21 14:55:01 +00:00
- class: [`Rector\Php73\Rector\FuncCall\SetCookieRector`](/../master/rules/php73/src/Rector/FuncCall/SetCookieRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/FuncCall/SetcookieRector/Fixture)
2020-01-21 14:55:01 +00:00
2020-06-16 14:39:45 +00:00
Convert `setcookie` argument to PHP7.3 option array
2020-01-21 14:55:01 +00:00
```diff
-setcookie('name', $value, 360);
+setcookie('name', $value, ['expires' => 360]);
```
```diff
-setcookie('name', $name, 0, '', '', true, true);
+setcookie('name', $name, ['expires' => 0, 'path' => '', 'domain' => '', 'secure' => true, 'httponly' => true]);
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-21 14:55:01 +00:00
2019-09-25 08:49:53 +00:00
### `StringifyStrNeedlesRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Php73\Rector\FuncCall\StringifyStrNeedlesRector`](/../master/rules/php73/src/Rector/FuncCall/StringifyStrNeedlesRector.php)
- [test fixtures](/../master/rules/php73/tests/Rector/FuncCall/StringifyStrNeedlesRector/Fixture)
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
Makes needles explicit strings
2019-05-29 13:40:20 +00:00
```diff
2019-09-25 08:49:53 +00:00
$needle = 5;
-$fivePosition = strpos('725', $needle);
+$fivePosition = strpos('725', (string) $needle);
2019-02-21 14:36:16 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-21 14:36:16 +00:00
2019-09-25 08:49:53 +00:00
## Php74
2018-12-31 19:29:12 +00:00
2019-09-25 08:49:53 +00:00
### `AddLiteralSeparatorToNumberRector`
2018-12-31 19:29:12 +00:00
- class: [`Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector`](/../master/rules/php74/src/Rector/LNumber/AddLiteralSeparatorToNumberRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/LNumber/AddLiteralSeparatorToNumberRector/Fixture)
2019-09-25 08:49:53 +00:00
Add "_" as thousands separator in numbers
2018-12-31 19:29:12 +00:00
2019-05-29 13:40:20 +00:00
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
{
2019-09-25 08:49:53 +00:00
public function run()
{
- $int = 1000;
- $float = 1000500.001;
+ $int = 1_000;
+ $float = 1_000_500.001;
}
}
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
### `ArrayKeyExistsOnPropertyRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Php74\Rector\FuncCall\ArrayKeyExistsOnPropertyRector`](/../master/rules/php74/src/Rector/FuncCall/ArrayKeyExistsOnPropertyRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/FuncCall/ArrayKeyExistsOnPropertyRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-16 14:39:45 +00:00
Change `array_key_exists()` on property to `property_exists()`
2019-05-29 13:40:20 +00:00
```diff
2019-09-25 08:49:53 +00:00
class SomeClass {
public $value;
}
$someClass = new SomeClass;
2018-12-31 19:29:12 +00:00
2019-09-25 08:49:53 +00:00
-array_key_exists('value', $someClass);
+property_exists($someClass, 'value');
2018-12-31 19:29:12 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 19:29:12 +00:00
2019-09-25 08:49:53 +00:00
### `ArraySpreadInsteadOfArrayMergeRector`
2018-08-01 20:09:34 +00:00
- class: [`Rector\Php74\Rector\FuncCall\ArraySpreadInsteadOfArrayMergeRector`](/../master/rules/php74/src/Rector/FuncCall/ArraySpreadInsteadOfArrayMergeRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/FuncCall/ArraySpreadInsteadOfArrayMergeRector/Fixture)
2018-10-12 23:15:00 +00:00
2020-06-16 14:39:45 +00:00
Change `array_merge()` to spread operator, except values with possible string `key` values
2018-08-01 20:09:34 +00:00
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
{
2019-09-25 08:49:53 +00:00
public function run($iter1, $iter2)
{
2019-09-25 08:49:53 +00:00
- $values = array_merge(iterator_to_array($iter1), iterator_to_array($iter2));
+ $values = [...$iter1, ...$iter2];
2018-08-01 20:09:34 +00:00
2019-09-25 08:49:53 +00:00
// 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];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
### `ChangeReflectionTypeToStringToGetNameRector`
- class: [`Rector\Php74\Rector\MethodCall\ChangeReflectionTypeToStringToGetNameRector`](/../master/rules/php74/src/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector/Fixture)
2019-11-06 23:52:19 +00:00
Change string calls on ReflectionType
```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();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
2019-09-25 08:49:53 +00:00
### `ClassConstantToSelfClassRector`
2018-08-01 20:09:34 +00:00
- class: [`Rector\Php74\Rector\MagicConstClass\ClassConstantToSelfClassRector`](/../master/rules/php74/src/Rector/MagicConstClass/ClassConstantToSelfClassRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/MagicConstClass/ClassConstantToSelfClassRector/Fixture)
2018-10-12 23:15:00 +00:00
2020-07-15 17:25:56 +00:00
Change `__CLASS__` to self::class
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
2019-09-25 08:49:53 +00:00
public function callOnMe()
{
- var_dump(__CLASS__);
+ var_dump(self::class);
}
}
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `ClosureToArrowFunctionRector`
2018-12-31 19:29:12 +00:00
- class: [`Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector`](/../master/rules/php74/src/Rector/Closure/ClosureToArrowFunctionRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/Closure/ClosureToArrowFunctionRector/Fixture)
2018-12-31 19:29:12 +00:00
2019-09-25 08:49:53 +00:00
Change closure to arrow function
2018-12-31 19:29:12 +00:00
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
2019-09-25 08:49:53 +00:00
public function run($meetups)
{
2019-09-25 08:49:53 +00:00
- return array_filter($meetups, function (Meetup $meetup) {
- return is_object($meetup);
- });
+ return array_filter($meetups, fn(Meetup $meetup) => is_object($meetup));
}
2019-05-29 13:40:20 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
### `ExportToReflectionFunctionRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Php74\Rector\StaticCall\ExportToReflectionFunctionRector`](/../master/rules/php74/src/Rector/StaticCall/ExportToReflectionFunctionRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/StaticCall/ExportToReflectionFunctionRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-21 14:49:47 +00:00
Change `export()` to ReflectionFunction alternatives
2019-05-29 13:40:20 +00:00
```diff
2019-09-25 08:49:53 +00:00
-$reflectionFunction = ReflectionFunction::export('foo');
-$reflectionFunctionAsString = ReflectionFunction::export('foo', true);
+$reflectionFunction = new ReflectionFunction('foo');
+$reflectionFunctionAsString = (string) new ReflectionFunction('foo');
```
2018-12-31 19:29:12 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
### `FilterVarToAddSlashesRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Php74\Rector\FuncCall\FilterVarToAddSlashesRector`](/../master/rules/php74/src/Rector/FuncCall/FilterVarToAddSlashesRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/FuncCall/FilterVarToAddSlashesRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-16 14:39:45 +00:00
Change `filter_var()` with slash escaping to `addslashes()`
2019-05-29 13:40:20 +00:00
```diff
2019-09-25 08:49:53 +00:00
$var= "Satya's here!";
-filter_var($var, FILTER_SANITIZE_MAGIC_QUOTES);
+addslashes($var);
2018-12-31 19:29:12 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 19:29:12 +00:00
2019-09-25 08:49:53 +00:00
### `GetCalledClassToStaticClassRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\Php74\Rector\FuncCall\GetCalledClassToStaticClassRector`](/../master/rules/php74/src/Rector/FuncCall/GetCalledClassToStaticClassRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/FuncCall/GetCalledClassToStaticClassRector/Fixture)
2019-03-31 12:25:39 +00:00
2020-07-15 17:25:56 +00:00
Change `get_called_class()` to static::class
2019-03-31 12:25:39 +00:00
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
2019-03-31 12:25:39 +00:00
{
2019-09-25 08:49:53 +00:00
public function callOnMe()
{
- var_dump(get_called_class());
+ var_dump(static::class);
}
2019-03-31 12:25:39 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
2019-09-25 08:49:53 +00:00
### `MbStrrposEncodingArgumentPositionRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\Php74\Rector\FuncCall\MbStrrposEncodingArgumentPositionRector`](/../master/rules/php74/src/Rector/FuncCall/MbStrrposEncodingArgumentPositionRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/FuncCall/MbStrrposEncodingArgumentPositionRector/Fixture)
2019-03-31 12:25:39 +00:00
2020-06-16 14:39:45 +00:00
Change `mb_strrpos()` encoding argument position
2019-03-31 12:25:39 +00:00
```diff
2019-09-25 08:49:53 +00:00
-mb_strrpos($text, "abc", "UTF-8");
+mb_strrpos($text, "abc", 0, "UTF-8");
```
2019-03-31 12:25:39 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `NullCoalescingOperatorRector`
- class: [`Rector\Php74\Rector\Assign\NullCoalescingOperatorRector`](/../master/rules/php74/src/Rector/Assign/NullCoalescingOperatorRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/Assign/NullCoalescingOperatorRector/Fixture)
2019-09-25 08:49:53 +00:00
Use null coalescing operator ??=
```diff
2019-09-25 08:49:53 +00:00
$array = [];
-$array['user_id'] = $array['user_id'] ?? 'value';
+$array['user_id'] ??= 'value';
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RealToFloatTypeCastRector`
- class: [`Rector\Php74\Rector\Double\RealToFloatTypeCastRector`](/../master/rules/php74/src/Rector/Double/RealToFloatTypeCastRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/Double/RealToFloatTypeCastRector/Fixture)
2019-09-25 08:49:53 +00:00
Change deprecated (real) to (float)
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
{
public function run()
{
- $number = (real) 5;
+ $number = (float) 5;
$number = (float) 5;
$number = (double) 5;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `ReservedFnFunctionRector`
- class: [`Rector\Php74\Rector\Function_\ReservedFnFunctionRector`](/../master/rules/php74/src/Rector/Function_/ReservedFnFunctionRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/Function_/ReservedFnFunctionRector/Fixture)
2020-06-21 14:49:47 +00:00
Change `fn()` function name, since it will be reserved keyword
```diff
class SomeClass
{
2019-09-25 08:49:53 +00:00
public function run()
{
2019-09-25 08:49:53 +00:00
- function fn($value)
+ function f($value)
{
return $value;
}
2019-09-25 08:49:53 +00:00
- fn(5);
+ f(5);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RestoreDefaultNullToNullableTypePropertyRector`
- class: [`Rector\Php74\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector`](/../master/rules/php74/src/Rector/Property/RestoreDefaultNullToNullableTypePropertyRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/Property/RestoreDefaultNullToNullableTypePropertyRector/Fixture)
Add null default to properties with PHP 7.4 property nullable type
```diff
class SomeClass
{
- public ?string $name;
+ public ?string $name = null;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `TypedPropertyRector`
- class: [`Rector\Php74\Rector\Property\TypedPropertyRector`](/../master/rules/php74/src/Rector/Property/TypedPropertyRector.php)
- [test fixtures](/../master/rules/php74/tests/Rector/Property/TypedPropertyRector/Fixture)
Changes property `@var` annotations from annotation to type.
```diff
final class SomeClass
{
2020-01-03 18:20:13 +00:00
- /**
- * @var int
- */
- private count;
+ private int count;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## Php80
2020-04-24 22:57:13 +00:00
### `AnnotationToAttributeRector`
- class: [`Rector\Php80\Rector\Class_\AnnotationToAttributeRector`](/../master/rules/php80/src/Rector/Class_/AnnotationToAttributeRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/Class_/AnnotationToAttributeRector/Fixture)
2020-04-29 20:01:42 +00:00
Change annotation to attribute
2020-04-24 22:57:13 +00:00
```diff
use Doctrine\ORM\Attributes as ORM;
-/**
- * @ORM\Entity
- */
+<<ORM\Entity>>
class SomeClass
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-04-24 22:57:13 +00:00
2020-04-29 20:01:42 +00:00
### `ClassOnObjectRector`
- class: [`Rector\Php80\Rector\FuncCall\ClassOnObjectRector`](/../master/rules/php80/src/Rector/FuncCall/ClassOnObjectRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/FuncCall/ClassOnObjectRector/Fixture)
2020-07-07 10:15:52 +00:00
Change get_class($object) to faster `$object::class`
2020-04-29 20:01:42 +00:00
```diff
class SomeClass
{
public function run($object)
{
- return get_class($object);
+ return $object::class;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-04-29 20:01:42 +00:00
### `ClassPropertyAssignToConstructorPromotionRector`
- class: [`Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector`](/../master/rules/php80/src/Rector/Class_/ClassPropertyAssignToConstructorPromotionRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/Class_/ClassPropertyAssignToConstructorPromotionRector/Fixture)
Change simple property init and assign to constructor promotion
```diff
class SomeClass
{
- public float $x;
- public float $y;
- public float $z;
-
public function __construct(
- float $x = 0.0,
- float $y = 0.0,
- float $z = 0.0
- ) {
- $this->x = $x;
- $this->y = $y;
- $this->z = $z;
- }
+ public float $x = 0.0,
+ public float $y = 0.0,
+ public float $z = 0.0,
+ ) {}
}
```
<br><br>
2020-04-29 21:23:14 +00:00
### `GetDebugTypeRector`
- class: [`Rector\Php80\Rector\Ternary\GetDebugTypeRector`](/../master/rules/php80/src/Rector/Ternary/GetDebugTypeRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/Ternary/GetDebugTypeRector/Fixture)
Change ternary type resolve to `get_debug_type()`
2020-04-29 21:23:14 +00:00
```diff
class SomeClass
{
public function run($value)
{
- return is_object($value) ? get_class($value) : gettype($value);
+ return get_debug_type($value);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-04-29 21:23:14 +00:00
2020-06-05 10:33:30 +00:00
### `RemoveUnusedVariableInCatchRector`
- class: [`Rector\Php80\Rector\Catch_\RemoveUnusedVariableInCatchRector`](/../master/rules/php80/src/Rector/Catch_/RemoveUnusedVariableInCatchRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/Catch_/RemoveUnusedVariableInCatchRector/Fixture)
2020-06-21 14:49:47 +00:00
Remove unused variable in `catch()`
2020-06-05 10:33:30 +00:00
```diff
final class SomeClass
{
public function run()
{
try {
- } catch (Throwable $notUsedThrowable) {
+ } catch (Throwable) {
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-06-05 10:33:30 +00:00
2020-03-26 22:22:29 +00:00
### `StrContainsRector`
- class: [`Rector\Php80\Rector\NotIdentical\StrContainsRector`](/../master/rules/php80/src/Rector/NotIdentical/StrContainsRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/NotIdentical/StrContainsRector/Fixture)
2020-06-16 14:39:45 +00:00
Replace `strpos()` !== false and `strstr()` with `str_contains()`
2020-03-26 22:22:29 +00:00
```diff
class SomeClass
{
public function run()
{
- return strpos('abc', 'a') !== false;
+ return str_contains('abc', 'a');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-03-26 22:22:29 +00:00
2020-04-23 22:28:33 +00:00
### `StrEndsWithRector`
- class: [`Rector\Php80\Rector\Identical\StrEndsWithRector`](/../master/rules/php80/src/Rector/Identical/StrEndsWithRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/Identical/StrEndsWithRector/Fixture)
2020-06-16 14:39:45 +00:00
Change helper functions to `str_ends_with()`
2020-04-23 22:28:33 +00:00
```diff
class SomeClass
{
public function run()
{
- $isMatch = substr($haystack, -strlen($needle)) === $needle;
+ $isMatch = str_ends_with($haystack, $needle);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-04-23 22:28:33 +00:00
2020-04-23 12:34:27 +00:00
### `StrStartsWithRector`
- class: [`Rector\Php80\Rector\Identical\StrStartsWithRector`](/../master/rules/php80/src/Rector/Identical/StrStartsWithRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/Identical/StrStartsWithRector/Fixture)
2020-06-16 14:39:45 +00:00
Change helper functions to `str_starts_with()`
2020-04-23 12:34:27 +00:00
```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;
2020-05-23 14:03:54 +00:00
+ $isNotMatch = ! str_starts_with($haystack, $needle);
2020-04-23 12:34:27 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-04-23 12:34:27 +00:00
2020-04-24 12:00:49 +00:00
### `StringableForToStringRector`
- class: [`Rector\Php80\Rector\Class_\StringableForToStringRector`](/../master/rules/php80/src/Rector/Class_/StringableForToStringRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/Class_/StringableForToStringRector/Fixture)
Add `Stringable` interface to classes with `__toString()` method
```diff
-class SomeClass
+class SomeClass implements Stringable
{
- public function __toString()
+ public function __toString(): string
{
return 'I can stringz';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-04-24 12:00:49 +00:00
2020-06-05 10:33:30 +00:00
### `TokenGetAllToObjectRector`
- class: [`Rector\Php80\Rector\FuncCall\TokenGetAllToObjectRector`](/../master/rules/php80/src/Rector/FuncCall/TokenGetAllToObjectRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/FuncCall/TokenGetAllToObjectRector/Fixture)
Complete missing constructor dependency instance by type
```diff
final class SomeClass
{
public function run()
{
- $tokens = token_get_all($code);
- foreach ($tokens as $token) {
- if (is_array($token)) {
- $name = token_name($token[0]);
- $text = $token[1];
- } else {
- $name = null;
- $text = $token;
- }
+ $tokens = \PhpToken::getAll($code);
+ foreach ($tokens as $phpToken) {
+ $name = $phpToken->getTokenName();
+ $text = $phpToken->text;
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-06-05 10:33:30 +00:00
### `UnionTypesRector`
- class: [`Rector\Php80\Rector\FunctionLike\UnionTypesRector`](/../master/rules/php80/src/Rector/FunctionLike/UnionTypesRector.php)
- [test fixtures](/../master/rules/php80/tests/Rector/FunctionLike/UnionTypesRector/Fixture)
Change docs types to union types, where possible (properties are covered by TypedPropertiesRector)
```diff
class SomeClass {
/**
* @param array|int $number
* @return bool|float
*/
- public function go($number)
+ public function go(array|int $number): bool|float
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## PhpDeglobalize
### `ChangeGlobalVariablesToPropertiesRector`
- class: [`Rector\PhpDeglobalize\Rector\Class_\ChangeGlobalVariablesToPropertiesRector`](/../master/rules/php-deglobalize/src/Rector/Class_/ChangeGlobalVariablesToPropertiesRector.php)
- [test fixtures](/../master/rules/php-deglobalize/tests/Rector/Class_/ChangeGlobalVariablesToPropertiesRector/Fixture)
2020-07-07 10:15:52 +00:00
Change global `$variables` to private properties
```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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
## PhpSpecToPHPUnit
### `AddMockPropertiesRector`
- class: [`Rector\PhpSpecToPHPUnit\Rector\Class_\AddMockPropertiesRector`](/../master/rules/php-spec-to-phpunit/src/Rector/Class_/AddMockPropertiesRector.php)
2019-09-25 08:49:53 +00:00
Migrate PhpSpec behavior to PHPUnit test
```diff
2019-09-25 08:49:53 +00:00
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `MockVariableToPropertyFetchRector`
- class: [`Rector\PhpSpecToPHPUnit\Rector\ClassMethod\MockVariableToPropertyFetchRector`](/../master/rules/php-spec-to-phpunit/src/Rector/ClassMethod/MockVariableToPropertyFetchRector.php)
Migrate PhpSpec behavior to PHPUnit test
```diff
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
2019-03-31 12:25:39 +00:00
{
- $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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
2019-09-25 08:49:53 +00:00
### `PhpSpecClassToPHPUnitClassRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\Class_\PhpSpecClassToPHPUnitClassRector`](/../master/rules/php-spec-to-phpunit/src/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php)
2019-03-31 12:25:39 +00:00
Migrate PhpSpec behavior to PHPUnit test
```diff
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
2019-09-25 08:49:53 +00:00
### `PhpSpecMethodToPHPUnitMethodRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\ClassMethod\PhpSpecMethodToPHPUnitMethodRector`](/../master/rules/php-spec-to-phpunit/src/Rector/ClassMethod/PhpSpecMethodToPHPUnitMethodRector.php)
2019-03-31 12:25:39 +00:00
Migrate PhpSpec behavior to PHPUnit test
```diff
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
2019-09-25 08:49:53 +00:00
### `PhpSpecMocksToPHPUnitMocksRector`
2019-03-16 20:31:46 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecMocksToPHPUnitMocksRector`](/../master/rules/php-spec-to-phpunit/src/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php)
2019-03-16 20:31:46 +00:00
2019-03-31 12:25:39 +00:00
Migrate PhpSpec behavior to PHPUnit test
2019-03-16 20:31:46 +00:00
```diff
2019-03-31 12:25:39 +00:00
namespace spec\SomeNamespaceForThisTest;
2019-03-16 20:31:46 +00:00
2019-03-31 12:25:39 +00:00
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
2019-03-16 20:31:46 +00:00
{
2019-03-31 12:25:39 +00:00
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
2019-03-16 20:31:46 +00:00
+ protected function setUp()
{
2019-03-31 12:25:39 +00:00
- $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-03-16 20:31:46 +00:00
}
2019-03-31 12:25:39 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
2019-09-25 08:49:53 +00:00
### `PhpSpecPromisesToPHPUnitAssertRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecPromisesToPHPUnitAssertRector`](/../master/rules/php-spec-to-phpunit/src/Rector/MethodCall/PhpSpecPromisesToPHPUnitAssertRector.php)
2019-03-16 20:31:46 +00:00
2019-03-31 12:25:39 +00:00
Migrate PhpSpec behavior to PHPUnit test
```diff
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
2019-03-16 20:31:46 +00:00
{
2019-03-31 12:25:39 +00:00
- $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-03-16 20:31:46 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-16 20:31:46 +00:00
2019-09-25 08:49:53 +00:00
### `RenameSpecFileToTestFileRector`
- class: [`Rector\PhpSpecToPHPUnit\Rector\FileSystem\RenameSpecFileToTestFileRector`](/../master/rules/php-spec-to-phpunit/src/Rector/FileSystem/RenameSpecFileToTestFileRector.php)
2019-09-25 08:49:53 +00:00
Rename "*Spec.php" file to "*Test.php" file
```diff
-// tests/SomeSpec.php
+// tests/SomeTest.php
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-06 15:06:07 +00:00
## Polyfill
### `UnwrapFutureCompatibleIfFunctionExistsRector`
2020-01-06 15:06:07 +00:00
- class: [`Rector\Polyfill\Rector\If_\UnwrapFutureCompatibleIfFunctionExistsRector`](/../master/packages/polyfill/src/Rector/If_/UnwrapFutureCompatibleIfFunctionExistsRector.php)
- [test fixtures](/../master/packages/polyfill/tests/Rector/If_/UnwrapFutureCompatibleIfFunctionExistsRector/Fixture)
2020-01-06 15:06:07 +00:00
Remove functions exists if with else for always existing
```diff
class SomeClass
{
public function run()
{
// session locking trough other addons
- if (function_exists('session_abort')) {
- session_abort();
- } else {
- session_write_close();
- }
+ session_abort();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-06 15:06:07 +00:00
### `UnwrapFutureCompatibleIfPhpVersionRector`
- class: [`Rector\Polyfill\Rector\If_\UnwrapFutureCompatibleIfPhpVersionRector`](/../master/packages/polyfill/src/Rector/If_/UnwrapFutureCompatibleIfPhpVersionRector.php)
- [test fixtures](/../master/packages/polyfill/tests/Rector/If_/UnwrapFutureCompatibleIfPhpVersionRector/Fixture)
Remove php version checks if they are passed
```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+';
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-03-28 23:06:05 +00:00
## Privatization
2020-05-12 15:09:29 +00:00
### `ChangeLocalPropertyToVariableRector`
- class: [`Rector\Privatization\Rector\Class_\ChangeLocalPropertyToVariableRector`](/../master/rules/privatization/src/Rector/Class_/ChangeLocalPropertyToVariableRector.php)
- [test fixtures](/../master/rules/privatization/tests/Rector/Class_/ChangeLocalPropertyToVariableRector/Fixture)
Change local property used in single method to local variable
```diff
class SomeClass
{
- private $count;
public function run()
{
- $this->count = 5;
- return $this->count;
+ $count = 5;
+ return $count;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-12 15:09:29 +00:00
2020-05-29 10:41:25 +00:00
### `PrivatizeFinalClassMethodRector`
- class: [`Rector\Privatization\Rector\ClassMethod\PrivatizeFinalClassMethodRector`](/../master/rules/privatization/src/Rector/ClassMethod/PrivatizeFinalClassMethodRector.php)
- [test fixtures](/../master/rules/privatization/tests/Rector/ClassMethod/PrivatizeFinalClassMethodRector/Fixture)
Change protected class method to private if possible
```diff
final class SomeClass
{
- protected function someMethod()
+ private function someMethod()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-29 10:41:25 +00:00
### `PrivatizeFinalClassPropertyRector`
- class: [`Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector`](/../master/rules/privatization/src/Rector/Property/PrivatizeFinalClassPropertyRector.php)
- [test fixtures](/../master/rules/privatization/tests/Rector/Property/PrivatizeFinalClassPropertyRector/Fixture)
Change property to private if possible
```diff
final class SomeClass
{
- protected $value;
+ private $value;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `PrivatizeLocalClassConstantRector`
- class: [`Rector\Privatization\Rector\ClassConst\PrivatizeLocalClassConstantRector`](/../master/rules/privatization/src/Rector/ClassConst/PrivatizeLocalClassConstantRector.php)
- [test fixtures](/../master/rules/privatization/tests/Rector/ClassConst/PrivatizeLocalClassConstantRector/Fixture)
Finalize every class constant that is used only locally
```diff
class ClassWithConstantUsedOnlyHere
{
- const LOCAL_ONLY = true;
+ private const LOCAL_ONLY = true;
public function isLocalOnly()
{
return self::LOCAL_ONLY;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `PrivatizeLocalGetterToPropertyRector`
- class: [`Rector\Privatization\Rector\MethodCall\PrivatizeLocalGetterToPropertyRector`](/../master/rules/privatization/src/Rector/MethodCall/PrivatizeLocalGetterToPropertyRector.php)
- [test fixtures](/../master/rules/privatization/tests/Rector/MethodCall/PrivatizeLocalGetterToPropertyRector/Fixture)
Privatize getter of local property to property
```diff
class SomeClass
{
private $some;
public function run()
{
- return $this->getSome() + 5;
+ return $this->some + 5;
}
private function getSome()
{
return $this->some;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-03-28 23:06:05 +00:00
### `PrivatizeLocalOnlyMethodRector`
- class: [`Rector\Privatization\Rector\ClassMethod\PrivatizeLocalOnlyMethodRector`](/../master/rules/privatization/src/Rector/ClassMethod/PrivatizeLocalOnlyMethodRector.php)
- [test fixtures](/../master/rules/privatization/tests/Rector/ClassMethod/PrivatizeLocalOnlyMethodRector/Fixture)
Privatize local-only use methods
```diff
class SomeClass
{
/**
* @api
*/
public function run()
{
return $this->useMe();
}
- public function useMe()
+ private function useMe()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-03-28 23:06:05 +00:00
### `PrivatizeLocalPropertyToPrivatePropertyRector`
- class: [`Rector\Privatization\Rector\Property\PrivatizeLocalPropertyToPrivatePropertyRector`](/../master/rules/privatization/src/Rector/Property/PrivatizeLocalPropertyToPrivatePropertyRector.php)
- [test fixtures](/../master/rules/privatization/tests/Rector/Property/PrivatizeLocalPropertyToPrivatePropertyRector/Fixture)
Privatize local-only property to private property
```diff
class SomeClass
{
- public $value;
+ private $value;
public function run()
{
return $this->value;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## RectorGenerator
### `AddNewServiceToSymfonyPhpConfigRector`
- class: [`Rector\RectorGenerator\Rector\Closure\AddNewServiceToSymfonyPhpConfigRector`](/../master/packages/rector-generator/src/Rector/Closure/AddNewServiceToSymfonyPhpConfigRector.php)
Adds a new `$services->set(...)` call to PHP Config
```diff
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
+ $services->set(AddNewServiceToSymfonyPhpConfigRector::class);
};
```
<br><br>
2019-09-25 08:49:53 +00:00
## RemovingStatic
### `NewUniqueObjectToEntityFactoryRector`
- class: [`Rector\RemovingStatic\Rector\Class_\NewUniqueObjectToEntityFactoryRector`](/../master/rules/removing-static/src/Rector/Class_/NewUniqueObjectToEntityFactoryRector.php)
2019-09-25 08:49:53 +00:00
Convert new X to new factories
```diff
-<?php
-
2019-09-25 08:49:53 +00:00
class SomeClass
{
2019-09-25 08:49:53 +00:00
+ 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();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `PHPUnitStaticToKernelTestCaseGetRector`
- class: [`Rector\RemovingStatic\Rector\Class_\PHPUnitStaticToKernelTestCaseGetRector`](/../master/rules/removing-static/src/Rector/Class_/PHPUnitStaticToKernelTestCaseGetRector.php)
- [test fixtures](/../master/rules/removing-static/tests/Rector/Class_/PHPUnitStaticToKernelTestCaseGetRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-21 14:49:47 +00:00
Convert static calls in PHPUnit test cases, to `get()` from the container of KernelTestCase
2019-09-25 08:49:53 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\RemovingStatic\Rector\Class_\PHPUnitStaticToKernelTestCaseGetRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(PHPUnitStaticToKernelTestCaseGetRector::class)
->arg('staticClassTypes', ['EntityFactory']);
};
2019-09-25 08:49:53 +00:00
```
```diff
-<?php
+use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
-use PHPUnit\Framework\TestCase;
+final class SomeTestCase extends KernelTestCase
+{
+ /**
2019-09-25 08:49:53 +00:00
+ * @var EntityFactory
+ */
2019-09-25 08:49:53 +00:00
+ private $entityFactory;
2019-11-06 23:52:19 +00:00
-final class SomeTestCase extends TestCase
-{
2019-09-25 08:49:53 +00:00
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->entityFactory = self::$container->get(EntityFactory::class);
+ }
2019-11-06 23:52:19 +00:00
+
2019-09-25 08:49:53 +00:00
public function test()
{
2019-09-25 08:49:53 +00:00
- $product = EntityFactory::create('product');
+ $product = $this->entityFactory->create('product');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `PassFactoryToUniqueObjectRector`
- class: [`Rector\RemovingStatic\Rector\Class_\PassFactoryToUniqueObjectRector`](/../master/rules/removing-static/src/Rector/Class_/PassFactoryToUniqueObjectRector.php)
2019-09-25 08:49:53 +00:00
2020-06-21 14:49:47 +00:00
Convert new `X/Static::call()` to factories in entities, pass them via constructor to `each` other
2019-09-25 08:49:53 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\RemovingStatic\Rector\Class_\PassFactoryToUniqueObjectRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(PassFactoryToUniqueObjectRector::class)
->arg('$typesToServices', ['StaticClass']);
};
2019-09-25 08:49:53 +00:00
```
```diff
-<?php
-
class SomeClass
{
+ public function __construct(AnotherClassFactory $anotherClassFactory)
+ {
+ $this->anotherClassFactory = $anotherClassFactory;
+ }
+
2019-09-25 08:49:53 +00:00
public function run()
{
- return new AnotherClass;
+ return $this->anotherClassFactory->create();
}
}
class AnotherClass
{
+ public function __construct(StaticClass $staticClass)
+ {
+ $this->staticClass = $staticClass;
+ }
+
2019-09-25 08:49:53 +00:00
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);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `StaticTypeToSetterInjectionRector`
- class: [`Rector\RemovingStatic\Rector\Class_\StaticTypeToSetterInjectionRector`](/../master/rules/removing-static/src/Rector/Class_/StaticTypeToSetterInjectionRector.php)
- [test fixtures](/../master/rules/removing-static/tests/Rector/Class_/StaticTypeToSetterInjectionRector/Fixture)
2019-09-25 08:49:53 +00:00
Changes types to setter injection
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\RemovingStatic\Rector\Class_\StaticTypeToSetterInjectionRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(StaticTypeToSetterInjectionRector::class)
->arg('$staticTypes', ['SomeStaticClass']);
};
2019-09-25 08:49:53 +00:00
```
```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();
}
}
2019-09-25 08:49:53 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
## Renaming
### `RenameAnnotationRector`
- class: [`Rector\Renaming\Rector\Annotation\RenameAnnotationRector`](/../master/rules/renaming/src/Rector/Annotation/RenameAnnotationRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/Annotation/RenameAnnotationRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-16 16:13:37 +00:00
Turns defined annotations above properties and methods to their new values.
2019-09-25 08:49:53 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\Annotation\RenameAnnotationRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameAnnotationRector::class)
->arg('$classToAnnotationMap', ['PHPUnit\Framework\TestCase' => ['test' => 'scenario']]);
};
2019-09-25 08:49:53 +00:00
```
```diff
class SomeTest extends PHPUnit\Framework\TestCase
{
2020-02-04 08:04:52 +00:00
/**
2019-09-25 08:49:53 +00:00
- * @test
+ * @scenario
*/
public function someMethod()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameClassConstantRector`
- class: [`Rector\Renaming\Rector\Constant\RenameClassConstantRector`](/../master/rules/renaming/src/Rector/Constant/RenameClassConstantRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/Constant/RenameClassConstantRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-16 16:13:37 +00:00
Replaces defined class constants in their calls.
2019-09-25 08:49:53 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\Constant\RenameClassConstantRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameClassConstantRector::class)
->arg('SomeClass', ['OLD_CONSTANT' => 'NEW_CONSTANT', 'OTHER_OLD_CONSTANT' => 'DifferentClass::NEW_CONSTANT']);
};
2019-09-25 08:49:53 +00:00
```
```diff
-$value = SomeClass::OLD_CONSTANT;
-$value = SomeClass::OTHER_OLD_CONSTANT;
+$value = SomeClass::NEW_CONSTANT;
+$value = DifferentClass::NEW_CONSTANT;
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameClassRector`
- class: [`Rector\Renaming\Rector\Class_\RenameClassRector`](/../master/rules/renaming/src/Rector/Class_/RenameClassRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/Class_/RenameClassRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-16 16:13:37 +00:00
Replaces defined classes by new ones.
2019-09-25 08:49:53 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\Class_\RenameClassRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameClassRector::class)
->arg('$oldToNewClasses', ['App\SomeOldClass' => 'App\SomeNewClass']);
};
2019-09-25 08:49:53 +00:00
```
```diff
namespace App;
-use SomeOldClass;
+use SomeNewClass;
-function someFunction(SomeOldClass $someOldClass): SomeOldClass
+function someFunction(SomeNewClass $someOldClass): SomeNewClass
{
- if ($someOldClass instanceof SomeOldClass) {
- return new SomeOldClass;
+ if ($someOldClass instanceof SomeNewClass) {
+ return new SomeNewClass;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameConstantRector`
- class: [`Rector\Renaming\Rector\ConstFetch\RenameConstantRector`](/../master/rules/renaming/src/Rector/ConstFetch/RenameConstantRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/ConstFetch/RenameConstantRector/Fixture)
2019-09-25 08:49:53 +00:00
Replace constant by new ones
```diff
final class SomeClass
{
public function run()
{
- return MYSQL_ASSOC;
+ return MYSQLI_ASSOC;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameFuncCallToStaticCallRector`
- class: [`Rector\Renaming\Rector\FuncCall\RenameFuncCallToStaticCallRector`](/../master/rules/renaming/src/Rector/FuncCall/RenameFuncCallToStaticCallRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/FuncCall/RenameFuncCallToStaticCallRector/Fixture)
Rename func call to static call
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\FuncCall\RenameFuncCallToStaticCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameFuncCallToStaticCallRector::class)
->arg('$functionsToStaticCalls', ['strPee' => ['Strings', 'strPaa']]);
};
2020-02-13 21:48:16 +00:00
```
```diff
class SomeClass
{
public function run()
{
- strPee('...');
2020-02-13 21:48:16 +00:00
+ \Strings::strPaa('...');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameFunctionRector`
- class: [`Rector\Renaming\Rector\Function_\RenameFunctionRector`](/../master/rules/renaming/src/Rector/Function_/RenameFunctionRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/Function_/RenameFunctionRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-16 16:13:37 +00:00
Turns defined function call new one.
2019-09-25 08:49:53 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\Function_\RenameFunctionRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameFunctionRector::class)
->arg('$oldFunctionToNewFunction', ['view' => 'Laravel\Templating\render']);
};
2019-09-25 08:49:53 +00:00
```
```diff
-view("...", []);
+Laravel\Templating\render("...", []);
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameMethodRector`
- class: [`Rector\Renaming\Rector\MethodCall\RenameMethodRector`](/../master/rules/renaming/src/Rector/MethodCall/RenameMethodRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/MethodCall/RenameMethodRector/Fixture)
2019-09-25 08:49:53 +00:00
Turns method names to new ones.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\MethodCall\RenameMethodRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameMethodRector::class)
->arg('SomeExampleClass', ['$oldToNewMethodsByClass' => ['oldMethod' => 'newMethod']]);
};
```
```diff
2019-09-25 08:49:53 +00:00
$someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `RenameNamespaceRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\Renaming\Rector\Namespace_\RenameNamespaceRector`](/../master/rules/renaming/src/Rector/Namespace_/RenameNamespaceRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/Namespace_/RenameNamespaceRector/Fixture)
2019-05-01 23:56:58 +00:00
2019-09-25 08:49:53 +00:00
Replaces old namespace by new one.
2019-05-01 23:56:58 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\Namespace_\RenameNamespaceRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameNamespaceRector::class)
->arg('$oldToNewNamespaces', ['SomeOldNamespace' => 'SomeNewNamespace']);
};
2019-05-01 23:56:58 +00:00
```
```diff
2019-09-25 08:49:53 +00:00
-$someObject = new SomeOldNamespace\SomeClass;
+$someObject = new SomeNewNamespace\SomeClass;
2019-05-01 23:56:58 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
2019-09-25 08:49:53 +00:00
### `RenameStaticMethodRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\Renaming\Rector\MethodCall\RenameStaticMethodRector`](/../master/rules/renaming/src/Rector/MethodCall/RenameStaticMethodRector.php)
- [test fixtures](/../master/rules/renaming/tests/Rector/MethodCall/RenameStaticMethodRector/Fixture)
2019-05-01 23:56:58 +00:00
2019-09-25 08:49:53 +00:00
Turns method names to new ones.
2019-05-01 23:56:58 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\MethodCall\RenameStaticMethodRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameStaticMethodRector::class)
->arg('SomeClass', ['oldMethod' => ['AnotherExampleClass', 'newStaticMethod']]);
};
2019-05-29 13:40:20 +00:00
```
2019-05-01 23:56:58 +00:00
```diff
2019-09-25 08:49:53 +00:00
-SomeClass::oldStaticMethod();
+AnotherExampleClass::newStaticMethod();
```
2019-05-29 13:40:20 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Renaming\Rector\MethodCall\RenameStaticMethodRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameStaticMethodRector::class)
->arg('$oldToNewMethodByClasses', ['SomeClass' => ['oldMethod' => 'newStaticMethod']]);
};
2019-09-25 08:49:53 +00:00
```
```diff
-SomeClass::oldStaticMethod();
+SomeClass::newStaticMethod();
2019-05-29 13:40:20 +00:00
```
2019-05-01 23:56:58 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-08-05 21:10:47 +00:00
## Restoration
### `CompleteImportForPartialAnnotationRector`
- class: [`Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector`](/../master/rules/restoration/src/Rector/Namespace_/CompleteImportForPartialAnnotationRector.php)
- [test fixtures](/../master/rules/restoration/tests/Rector/Namespace_/CompleteImportForPartialAnnotationRector/Fixture)
2019-08-05 21:10:47 +00:00
In case you have accidentally removed use imports but code still contains partial use statements, this will save you
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(CompleteImportForPartialAnnotationRector::class)
->arg('$useImportsToRestore', [['Doctrine\ORM\Mapping', 'ORM']]);
};
2019-08-05 21:10:47 +00:00
```
```diff
+use Doctrine\ORM\Mapping as ORM;
+
class SomeClass
{
/**
* @ORM\Id
*/
public $id;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CompleteMissingDependencyInNewRector`
- class: [`Rector\Restoration\Rector\New_\CompleteMissingDependencyInNewRector`](/../master/rules/restoration/src/Rector/New_/CompleteMissingDependencyInNewRector.php)
- [test fixtures](/../master/rules/restoration/tests/Rector/New_/CompleteMissingDependencyInNewRector/Fixture)
Complete missing constructor dependency instance by type
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Restoration\Rector\New_\CompleteMissingDependencyInNewRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(CompleteMissingDependencyInNewRector::class)
->arg('$classToInstantiateByType', ['RandomDependency' => 'RandomDependency']);
};
```
```diff
final class SomeClass
{
public function run()
{
- $valueObject = new RandomValueObject();
+ $valueObject = new RandomValueObject(new RandomDependency());
}
}
class RandomValueObject
{
public function __construct(RandomDependency $randomDependency)
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `MakeTypedPropertyNullableIfCheckedRector`
- class: [`Rector\Restoration\Rector\Property\MakeTypedPropertyNullableIfCheckedRector`](/../master/rules/restoration/src/Rector/Property/MakeTypedPropertyNullableIfCheckedRector.php)
- [test fixtures](/../master/rules/restoration/tests/Rector/Property/MakeTypedPropertyNullableIfCheckedRector/Fixture)
Make typed property nullable if checked
```diff
final class SomeClass
{
- private AnotherClass $anotherClass;
+ private ?AnotherClass $anotherClass = null;
public function run()
{
if ($this->anotherClass === null) {
$this->anotherClass = new AnotherClass;
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `MissingClassConstantReferenceToStringRector`
- class: [`Rector\Restoration\Rector\ClassConstFetch\MissingClassConstantReferenceToStringRector`](/../master/rules/restoration/src/Rector/ClassConstFetch/MissingClassConstantReferenceToStringRector.php)
- [test fixtures](/../master/rules/restoration/tests/Rector/ClassConstFetch/MissingClassConstantReferenceToStringRector/Fixture)
Convert missing class reference to string
```diff
class SomeClass
{
public function run()
{
- return NonExistingClass::class;
+ return 'NonExistingClass';
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveFinalFromEntityRector`
- class: [`Rector\Restoration\Rector\Class_\RemoveFinalFromEntityRector`](/../master/rules/restoration/src/Rector/Class_/RemoveFinalFromEntityRector.php)
- [test fixtures](/../master/rules/restoration/tests/Rector/Class_/RemoveFinalFromEntityRector/Fixture)
Remove final from Doctrine entities
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
-final class SomeClass
+class SomeClass
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveUselessJustForSakeInterfaceRector`
- class: [`Rector\Restoration\Rector\Class_\RemoveUselessJustForSakeInterfaceRector`](/../master/rules/restoration/src/Rector/Class_/RemoveUselessJustForSakeInterfaceRector.php)
- [test fixtures](/../master/rules/restoration/tests/Rector/Class_/RemoveUselessJustForSakeInterfaceRector/Fixture)
Remove interface, that are added just for its sake, but nowhere useful
```diff
-class SomeClass implements OnlyHereUsedInterface
+class SomeClass
{
}
-interface OnlyHereUsedInterface
-{
-}
-
class SomePresenter
{
- public function __construct(OnlyHereUsedInterface $onlyHereUsed)
+ public function __construct(SomeClass $onlyHereUsed)
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `UpdateFileNameByClassNameFileSystemRector`
- class: [`Rector\Restoration\Rector\FileSystem\UpdateFileNameByClassNameFileSystemRector`](/../master/rules/restoration/src/Rector/FileSystem/UpdateFileNameByClassNameFileSystemRector.php)
- [test fixtures](/../master/rules/restoration/tests/Rector/FileSystem/UpdateFileNameByClassNameFileSystemRector/Fixture)
Rename file to respect class name
```diff
-// app/SomeClass.php
+// app/AnotherClass.php
class AnotherClass
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## SOLID
2019-05-29 13:40:20 +00:00
### `AddFalseDefaultToBoolPropertyRector`
- class: [`Rector\SOLID\Rector\Property\AddFalseDefaultToBoolPropertyRector`](/../master/rules/solid/src/Rector/Property/AddFalseDefaultToBoolPropertyRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/Property/AddFalseDefaultToBoolPropertyRector/Fixture)
Add false default to bool properties, to prevent null compare errors
```diff
class SomeClass
{
/**
* @var bool
*/
- private $isDisabled;
+ private $isDisabled = false;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-06 15:06:07 +00:00
### `ChangeIfElseValueAssignToEarlyReturnRector`
- class: [`Rector\SOLID\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector`](/../master/rules/solid/src/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector/Fixture)
2020-01-06 15:06:07 +00:00
Change if/else value to early return
```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;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-06 15:06:07 +00:00
### `ChangeNestedForeachIfsToEarlyContinueRector`
- class: [`Rector\SOLID\Rector\Foreach_\ChangeNestedForeachIfsToEarlyContinueRector`](/../master/rules/solid/src/Rector/Foreach_/ChangeNestedForeachIfsToEarlyContinueRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/Foreach_/ChangeNestedForeachIfsToEarlyContinueRector/Fixture)
Change nested ifs to foreach with continue
```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';
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-06 15:06:07 +00:00
### `ChangeNestedIfsToEarlyReturnRector`
- class: [`Rector\SOLID\Rector\If_\ChangeNestedIfsToEarlyReturnRector`](/../master/rules/solid/src/Rector/If_/ChangeNestedIfsToEarlyReturnRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/If_/ChangeNestedIfsToEarlyReturnRector/Fixture)
2020-01-06 15:06:07 +00:00
Change nested ifs to early return
```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-06-16 16:14:51 +00:00
<br><br>
2020-01-06 15:06:07 +00:00
### `ChangeReadOnlyPropertyWithDefaultValueToConstantRector`
- class: [`Rector\SOLID\Rector\Property\ChangeReadOnlyPropertyWithDefaultValueToConstantRector`](/../master/rules/solid/src/Rector/Property/ChangeReadOnlyPropertyWithDefaultValueToConstantRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/Property/ChangeReadOnlyPropertyWithDefaultValueToConstantRector/Fixture)
Change property with read only status with default value to constant
```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;
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeReadOnlyVariableWithDefaultValueToConstantRector`
- class: [`Rector\SOLID\Rector\ClassMethod\ChangeReadOnlyVariableWithDefaultValueToConstantRector`](/../master/rules/solid/src/Rector/ClassMethod/ChangeReadOnlyVariableWithDefaultValueToConstantRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/ClassMethod/ChangeReadOnlyVariableWithDefaultValueToConstantRector/Fixture)
Change variable with read only status with default value to constant
```diff
class SomeClass
{
2020-02-18 23:15:04 +00:00
+ /**
+ * @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) {
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `FinalizeClassesWithoutChildrenRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\SOLID\Rector\Class_\FinalizeClassesWithoutChildrenRector`](/../master/rules/solid/src/Rector/Class_/FinalizeClassesWithoutChildrenRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/Class_/FinalizeClassesWithoutChildrenRector/Fixture)
2019-05-29 13:40:20 +00:00
Finalize every class that has no children
2019-05-29 13:40:20 +00:00
```diff
-class FirstClass
+final class FirstClass
{
}
2019-05-29 13:40:20 +00:00
class SecondClass
{
}
2019-05-29 13:40:20 +00:00
-class ThirdClass extends SecondClass
+final class ThirdClass extends SecondClass
{
2019-05-01 23:56:58 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
### `MakeUnusedClassesWithChildrenAbstractRector`
- class: [`Rector\SOLID\Rector\Class_\MakeUnusedClassesWithChildrenAbstractRector`](/../master/rules/solid/src/Rector/Class_/MakeUnusedClassesWithChildrenAbstractRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/Class_/MakeUnusedClassesWithChildrenAbstractRector/Fixture)
Classes that have no children nor are used, should have abstract
```diff
class SomeClass extends PossibleAbstractClass
{
}
-class PossibleAbstractClass
+abstract class PossibleAbstractClass
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `MultiParentingToAbstractDependencyRector`
- class: [`Rector\SOLID\Rector\Class_\MultiParentingToAbstractDependencyRector`](/../master/rules/solid/src/Rector/Class_/MultiParentingToAbstractDependencyRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/Class_/MultiParentingToAbstractDependencyRector/Fixture)
Move dependency passed to all children to parent as @inject/@required dependency
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\SOLID\Rector\Class_\MultiParentingToAbstractDependencyRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(MultiParentingToAbstractDependencyRector::class)
->arg('$framework', 'nette');
};
```
```diff
abstract class AbstractParentClass
{
- 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);
- }
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-03 18:20:13 +00:00
### `RemoveAlwaysElseRector`
- class: [`Rector\SOLID\Rector\If_\RemoveAlwaysElseRector`](/../master/rules/solid/src/Rector/If_/RemoveAlwaysElseRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/If_/RemoveAlwaysElseRector/Fixture)
2020-01-03 18:20:13 +00:00
Split if statement, when if condition always break execution flow
2020-01-03 18:20:13 +00:00
```diff
class SomeClass
{
public function run($value)
{
if ($value) {
throw new \InvalidStateException;
- } else {
- return 10;
}
+
+ return 10;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-01-03 18:20:13 +00:00
### `RepeatedLiteralToClassConstantRector`
- class: [`Rector\SOLID\Rector\Class_\RepeatedLiteralToClassConstantRector`](/../master/rules/solid/src/Rector/Class_/RepeatedLiteralToClassConstantRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/Class_/RepeatedLiteralToClassConstantRector/Fixture)
Replace repeated strings with constant
```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];
}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `UseInterfaceOverImplementationInConstructorRector`
- class: [`Rector\SOLID\Rector\ClassMethod\UseInterfaceOverImplementationInConstructorRector`](/../master/rules/solid/src/Rector/ClassMethod/UseInterfaceOverImplementationInConstructorRector.php)
- [test fixtures](/../master/rules/solid/tests/Rector/ClassMethod/UseInterfaceOverImplementationInConstructorRector/Fixture)
2019-10-15 14:46:31 +00:00
Use interface instead of specific class
```diff
class SomeClass
{
- public function __construct(SomeImplementation $someImplementation)
+ public function __construct(SomeInterface $someImplementation)
{
}
}
class SomeImplementation implements SomeInterface
{
}
interface SomeInterface
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
## Sensio
2018-12-31 11:50:32 +00:00
### `RemoveServiceFromSensioRouteRector`
- class: [`Rector\Sensio\Rector\ClassMethod\RemoveServiceFromSensioRouteRector`](/../master/rules/sensio/src/Rector/ClassMethod/RemoveServiceFromSensioRouteRector.php)
- [test fixtures](/../master/rules/sensio/tests/Rector/ClassMethod/RemoveServiceFromSensioRouteRector/Fixture)
Remove service from Sensio @Route
```diff
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
final class SomeClass
{
/**
- * @Route(service="some_service")
+ * @Route()
*/
public function run()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-06-06 13:07:56 +00:00
### `ReplaceSensioRouteAnnotationWithSymfonyRector`
- class: [`Rector\Sensio\Rector\ClassMethod\ReplaceSensioRouteAnnotationWithSymfonyRector`](/../master/rules/sensio/src/Rector/ClassMethod/ReplaceSensioRouteAnnotationWithSymfonyRector.php)
- [test fixtures](/../master/rules/sensio/tests/Rector/ClassMethod/ReplaceSensioRouteAnnotationWithSymfonyRector/Fixture)
Replace Sensio @Route annotation with Symfony one
```diff
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
+use Symfony\Component\Routing\Annotation\Route;
final class SomeClass
{
/**
* @Route()
*/
public function run()
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-06-06 13:07:56 +00:00
### `TemplateAnnotationToThisRenderRector`
2018-12-31 11:50:32 +00:00
- class: [`Rector\Sensio\Rector\FrameworkExtraBundle\TemplateAnnotationToThisRenderRector`](/../master/rules/sensio/src/Rector/FrameworkExtraBundle/TemplateAnnotationToThisRenderRector.php)
- [test fixtures](/../master/rules/sensio/tests/Rector/FrameworkExtraBundle/TemplateAnnotationToThisRenderRector/Fixture)
Turns `@Template` annotation to explicit method call in Controller of FrameworkExtraBundle in Symfony
2018-12-31 11:50:32 +00:00
```diff
-/**
- * @Template()
- */
public function indexAction()
{
2020-06-30 08:46:05 +00:00
+ return $this->render('index.html.twig');
}
2018-12-31 11:50:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-12-31 11:50:32 +00:00
2019-10-15 14:46:31 +00:00
## StrictCodeQuality
### `VarInlineAnnotationToAssertRector`
- class: [`Rector\StrictCodeQuality\Rector\Stmt\VarInlineAnnotationToAssertRector`](/../master/rules/strict-code-quality/src/Rector/Stmt/VarInlineAnnotationToAssertRector.php)
- [test fixtures](/../master/rules/strict-code-quality/tests/Rector/Stmt/VarInlineAnnotationToAssertRector/Fixture)
2019-10-15 14:46:31 +00:00
2020-06-16 14:39:45 +00:00
Turn @var inline checks above code to `assert()` of hte type
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
{
public function run()
{
/** @var SpecificClass $value */
+ assert($value instanceof SpecificClass);
$value->call();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
## Symfony
2018-08-01 20:09:34 +00:00
### `ActionSuffixRemoverRector`
2018-10-21 22:26:45 +00:00
- class: [`Rector\Symfony\Rector\Controller\ActionSuffixRemoverRector`](/../master/rules/symfony/src/Rector/Controller/ActionSuffixRemoverRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Controller/ActionSuffixRemoverRector/Fixture)
2018-10-21 22:26:45 +00:00
Removes Action suffixes from methods in Symfony Controllers
2018-10-21 22:26:45 +00:00
```diff
class SomeController
{
- public function indexAction()
+ public function index()
{
}
}
2018-10-21 22:26:45 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `AddFlashRector`
2018-08-01 20:09:34 +00:00
- class: [`Rector\Symfony\Rector\Controller\AddFlashRector`](/../master/rules/symfony/src/Rector/Controller/AddFlashRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Controller/AddFlashRector/Fixture)
2018-08-01 20:09:34 +00:00
2019-05-29 13:40:20 +00:00
Turns long flash adding to short helper method in Controller in Symfony
2018-08-01 20:09:34 +00:00
```diff
2019-05-29 13:40:20 +00:00
class SomeController extends Controller
2018-08-01 20:09:34 +00:00
{
2019-05-29 13:40:20 +00:00
public function some(Request $request)
{
2019-05-29 13:40:20 +00:00
- $request->getSession()->getFlashBag()->add("success", "something");
+ $this->addFlash("success", "something");
}
2018-08-01 20:09:34 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `CascadeValidationFormBuilderRector`
2018-09-28 16:33:35 +00:00
- class: [`Rector\Symfony\Rector\MethodCall\CascadeValidationFormBuilderRector`](/../master/rules/symfony/src/Rector/MethodCall/CascadeValidationFormBuilderRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/MethodCall/CascadeValidationFormBuilderRector/Fixture)
2018-09-28 16:33:35 +00:00
Change "cascade_validation" option to specific node attribute
2018-09-28 16:33:35 +00:00
```diff
class SomeController
{
public function someMethod()
{
- $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();
}
2018-09-28 16:33:35 +00:00
protected function createFormBuilder()
{
return new FormBuilder();
}
}
2018-09-28 16:33:35 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector`
- class: [`Rector\Symfony\Rector\MethodCall\ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector`](/../master/rules/symfony/src/Rector/MethodCall/ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/MethodCall/ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector/Fixture)
Rename `type` option to `entry_type` in CollectionType
```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],
]);
}
}
```
<br><br>
### `ChangeCollectionTypeOptionTypeFromStringToClassReferenceRector`
- class: [`Rector\Symfony\Rector\MethodCall\ChangeCollectionTypeOptionTypeFromStringToClassReferenceRector`](/../master/rules/symfony/src/Rector/MethodCall/ChangeCollectionTypeOptionTypeFromStringToClassReferenceRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/MethodCall/ChangeCollectionTypeOptionTypeFromStringToClassReferenceRector/Fixture)
Change type in CollectionType from alias string to class reference
```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><br>
2020-07-09 16:38:52 +00:00
### `ChangeFileLoaderInExtensionAndKernelRector`
2020-07-09 16:38:52 +00:00
- class: [`Rector\Symfony\Rector\Class_\ChangeFileLoaderInExtensionAndKernelRector`](/../master/rules/symfony/src/Rector/Class_/ChangeFileLoaderInExtensionAndKernelRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Class_/ChangeFileLoaderInExtensionAndKernelRector/Fixture)
Change XML loader to YAML in Bundle Extension
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Symfony\Rector\Class_\ChangeFileLoaderInExtensionAndKernelRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ChangeFileLoaderInExtensionAndKernelRector::class)
->arg('$from', 'xml')
->arg('$to', 'yaml');
};
```
```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><br>
### `ConsoleExceptionToErrorEventConstantRector`
2019-05-01 23:56:58 +00:00
- class: [`Rector\Symfony\Rector\Console\ConsoleExceptionToErrorEventConstantRector`](/../master/rules/symfony/src/Rector/Console/ConsoleExceptionToErrorEventConstantRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Console/ConsoleExceptionToErrorEventConstantRector/Fixture)
2019-05-01 23:56:58 +00:00
Turns old event name with EXCEPTION to ERROR constant in Console in Symfony
2019-05-01 23:56:58 +00:00
```diff
-"console.exception"
+Symfony\Component\Console\ConsoleEvents::ERROR
2019-05-29 13:40:20 +00:00
```
2019-05-01 23:56:58 +00:00
2019-05-29 13:40:20 +00:00
```diff
-Symfony\Component\Console\ConsoleEvents::EXCEPTION
+Symfony\Component\Console\ConsoleEvents::ERROR
2019-05-01 23:56:58 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-01 23:56:58 +00:00
2019-10-15 14:46:31 +00:00
### `ConsoleExecuteReturnIntRector`
- class: [`Rector\Symfony\Rector\Console\ConsoleExecuteReturnIntRector`](/../master/rules/symfony/src/Rector/Console/ConsoleExecuteReturnIntRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Console/ConsoleExecuteReturnIntRector/Fixture)
2019-10-15 14:46:31 +00:00
Returns int from Command::execute command
```diff
class SomeCommand extends Command
{
- public function execute(InputInterface $input, OutputInterface $output)
+ public function index(InputInterface $input, OutputInterface $output): int
{
- return null;
+ return 0;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-10-15 14:46:31 +00:00
### `ConstraintUrlOptionRector`
- class: [`Rector\Symfony\Rector\Validator\ConstraintUrlOptionRector`](/../master/rules/symfony/src/Rector/Validator/ConstraintUrlOptionRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Validator/ConstraintUrlOptionRector/Fixture)
Turns true value to `Url::CHECK_DNS_TYPE_ANY` in Validator in Symfony.
```diff
-$constraint = new Url(["checkDNS" => true]);
+$constraint = new Url(["checkDNS" => Url::CHECK_DNS_TYPE_ANY]);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ContainerBuilderCompileEnvArgumentRector`
- class: [`Rector\Symfony\Rector\DependencyInjection\ContainerBuilderCompileEnvArgumentRector`](/../master/rules/symfony/src/Rector/DependencyInjection/ContainerBuilderCompileEnvArgumentRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/DependencyInjection/ContainerBuilderCompileEnvArgumentRector/Fixture)
2020-07-04 21:14:12 +00:00
Turns old default value to parameter in `ContainerBuilder->build()` method in DI in Symfony
2018-07-31 12:50:39 +00:00
```diff
2020-05-02 09:51:01 +00:00
use Symfony\Component\DependencyInjection\ContainerBuilder;
$containerBuilder = new ContainerBuilder();
-$containerBuilder->compile();
+$containerBuilder->compile(true);
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `ContainerGetToConstructorInjectionRector`
2019-03-31 12:25:39 +00:00
- class: [`Rector\Symfony\Rector\FrameworkBundle\ContainerGetToConstructorInjectionRector`](/../master/rules/symfony/src/Rector/FrameworkBundle/ContainerGetToConstructorInjectionRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/FrameworkBundle/ContainerGetToConstructorInjectionRector/Fixture)
2019-03-31 12:25:39 +00:00
2019-05-29 13:40:20 +00:00
Turns fetching of dependencies via `$container->get()` in ContainerAware to constructor injection in Command and Controller in Symfony
2019-03-31 12:25:39 +00:00
```diff
2019-05-29 13:40:20 +00:00
-final class SomeCommand extends ContainerAwareCommand
+final class SomeCommand extends Command
2019-03-31 12:25:39 +00:00
{
2019-05-29 13:40:20 +00:00
+ public function __construct(SomeService $someService)
+ {
+ $this->someService = $someService;
+ }
+
public function someMethod()
2019-03-31 12:25:39 +00:00
{
2019-05-29 13:40:20 +00:00
// ...
- $this->getContainer()->get('some_service');
- $this->container->get('some_service');
+ $this->someService;
+ $this->someService;
2019-03-31 12:25:39 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-31 12:25:39 +00:00
### `FormIsValidRector`
2018-05-04 22:30:32 +00:00
- class: [`Rector\Symfony\Rector\Form\FormIsValidRector`](/../master/rules/symfony/src/Rector/Form/FormIsValidRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Form/FormIsValidRector/Fixture)
2019-10-02 08:04:14 +00:00
Adds `$form->isSubmitted()` validation to all `$form->isValid()` calls in Form in Symfony
2018-05-04 22:30:32 +00:00
```diff
-if ($form->isValid()) {
+if ($form->isSubmitted() && $form->isValid()) {
2018-05-04 22:30:32 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `FormTypeGetParentRector`
- class: [`Rector\Symfony\Rector\Form\FormTypeGetParentRector`](/../master/rules/symfony/src/Rector/Form/FormTypeGetParentRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Form/FormTypeGetParentRector/Fixture)
2018-05-04 22:30:32 +00:00
2020-06-16 14:39:45 +00:00
Turns string Form Type references to their `CONSTANT` alternatives in `getParent()` and `getExtendedType()` methods in Form in Symfony
2018-05-04 22:30:32 +00:00
```diff
use Symfony\Component\Form\AbstractType;
class SomeType extends AbstractType
{
public function getParent()
{
- return 'collection';
+ return \Symfony\Component\Form\Extension\Core\Type\CollectionType::class;
}
}
2018-05-04 22:30:32 +00:00
```
```diff
use Symfony\Component\Form\AbstractTypeExtension;
class SomeExtension extends AbstractTypeExtension
{
public function getExtendedType()
{
- return 'collection';
+ return \Symfony\Component\Form\Extension\Core\Type\CollectionType::class;
}
}
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `FormTypeInstanceToClassConstRector`
- class: [`Rector\Symfony\Rector\MethodCall\FormTypeInstanceToClassConstRector`](/../master/rules/symfony/src/Rector/MethodCall/FormTypeInstanceToClassConstRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/MethodCall/FormTypeInstanceToClassConstRector/Fixture)
2018-05-04 22:30:32 +00:00
2019-05-29 13:40:20 +00:00
Changes createForm(new FormType), add(new FormType) to ones with "FormType::class"
2018-05-04 22:30:32 +00:00
```diff
2019-05-29 13:40:20 +00:00
class SomeController
{
public function action()
{
- $form = $this->createForm(new TeamType, $entity);
+ $form = $this->createForm(TeamType::class, $entity);
2019-05-29 13:40:20 +00:00
}
2018-08-01 20:09:34 +00:00
}
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `GetParameterToConstructorInjectionRector`
2018-10-23 18:58:57 +00:00
- class: [`Rector\Symfony\Rector\FrameworkBundle\GetParameterToConstructorInjectionRector`](/../master/rules/symfony/src/Rector/FrameworkBundle/GetParameterToConstructorInjectionRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/FrameworkBundle/GetParameterToConstructorInjectionRector/Fixture)
2018-10-23 18:58:57 +00:00
Turns fetching of parameters via `getParameter()` in ContainerAware to constructor injection in Command and Controller in Symfony
2018-10-23 18:58:57 +00:00
```diff
-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
2019-05-29 13:40:20 +00:00
{
+ private $someParameter;
+
+ public function __construct($someParameter)
+ {
+ $this->someParameter = $someParameter;
+ }
+
public function someMethod()
{
- $this->getParameter('someParameter');
+ $this->someParameter;
}
2019-05-29 13:40:20 +00:00
}
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-23 18:58:57 +00:00
### `GetRequestRector`
2018-10-23 18:58:57 +00:00
- class: [`Rector\Symfony\Rector\HttpKernel\GetRequestRector`](/../master/rules/symfony/src/Rector/HttpKernel/GetRequestRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/HttpKernel/GetRequestRector/Fixture)
2018-10-23 18:58:57 +00:00
Turns fetching of dependencies via `$this->get()` to constructor injection in Command and Controller in Symfony
2018-10-23 18:58:57 +00:00
```diff
+use Symfony\Component\HttpFoundation\Request;
+
class SomeController
2019-05-29 13:40:20 +00:00
{
- public function someAction()
+ public function someAction(Request $request)
2019-05-29 13:40:20 +00:00
{
- $this->getRequest()->...();
+ $request->...();
2019-05-29 13:40:20 +00:00
}
}
```
2019-05-29 13:40:20 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `GetToConstructorInjectionRector`
- class: [`Rector\Symfony\Rector\FrameworkBundle\GetToConstructorInjectionRector`](/../master/rules/symfony/src/Rector/FrameworkBundle/GetToConstructorInjectionRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/FrameworkBundle/GetToConstructorInjectionRector/Fixture)
Turns fetching of dependencies via `$this->get()` to constructor injection in Command and Controller in Symfony
```diff
-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
{
+ public function __construct(SomeService $someService)
+ {
+ $this->someService = $someService;
+ }
+
public function someMethod()
2019-05-29 13:40:20 +00:00
{
- // ...
- $this->get('some_service');
+ $this->someService;
2019-05-29 13:40:20 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-06-06 13:01:53 +00:00
### `MakeCommandLazyRector`
- class: [`Rector\Symfony\Rector\Class_\MakeCommandLazyRector`](/../master/rules/symfony/src/Rector/Class_/MakeCommandLazyRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Class_/MakeCommandLazyRector/Fixture)
2019-06-06 13:01:53 +00:00
Make Symfony commands lazy
```diff
use Symfony\Component\Console\Command\Command
class SunshineCommand extends Command
{
+ protected static $defaultName = 'sunshine';
public function configure()
{
- $this->setName('sunshine');
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-06-06 13:01:53 +00:00
2019-05-29 13:40:20 +00:00
### `MakeDispatchFirstArgumentEventRector`
- class: [`Rector\Symfony\Rector\MethodCall\MakeDispatchFirstArgumentEventRector`](/../master/rules/symfony/src/Rector/MethodCall/MakeDispatchFirstArgumentEventRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/MethodCall/MakeDispatchFirstArgumentEventRector/Fixture)
2020-06-21 14:49:47 +00:00
Make event object a first argument of `dispatch()` method, event name as second
```diff
2019-12-08 21:00:38 +00:00
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
2019-05-29 13:40:20 +00:00
class SomeClass
{
2019-06-06 13:01:53 +00:00
public function run(EventDispatcherInterface $eventDispatcher)
2019-05-29 13:40:20 +00:00
{
2019-06-06 13:01:53 +00:00
- $eventDispatcher->dispatch('event_name', new Event());
+ $eventDispatcher->dispatch(new Event(), 'event_name');
2019-05-29 13:40:20 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-09-25 08:49:53 +00:00
### `MergeMethodAnnotationToRouteAnnotationRector`
- class: [`Rector\Symfony\Rector\ClassMethod\MergeMethodAnnotationToRouteAnnotationRector`](/../master/rules/symfony/src/Rector/ClassMethod/MergeMethodAnnotationToRouteAnnotationRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/ClassMethod/MergeMethodAnnotationToRouteAnnotationRector/Fixture)
2019-09-25 08:49:53 +00:00
Merge removed @Method annotation to @Route one
```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)
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `OptionNameRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Symfony\Rector\Form\OptionNameRector`](/../master/rules/symfony/src/Rector/Form/OptionNameRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Form/OptionNameRector/Fixture)
2019-05-29 13:40:20 +00:00
Turns old option names to new ones in FormTypes in Form in Symfony
2019-05-29 13:40:20 +00:00
```diff
$builder = new FormBuilder;
-$builder->add("...", ["precision" => "...", "virtual" => "..."];
+$builder->add("...", ["scale" => "...", "inherit_data" => "..."];
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `ParseFileRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Symfony\Rector\Yaml\ParseFileRector`](/../master/rules/symfony/src/Rector/Yaml/ParseFileRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Yaml/ParseFileRector/Fixture)
2019-05-29 13:40:20 +00:00
session > use_strict_mode is true by default and can be removed
2019-05-29 13:40:20 +00:00
```diff
-session > use_strict_mode: true
+session:
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `ProcessBuilderGetProcessRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Symfony\Rector\Process\ProcessBuilderGetProcessRector`](/../master/rules/symfony/src/Rector/Process/ProcessBuilderGetProcessRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Process/ProcessBuilderGetProcessRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-07-07 10:15:52 +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.
2019-05-29 13:40:20 +00:00
```diff
$processBuilder = new Symfony\Component\Process\ProcessBuilder;
-$process = $processBuilder->getProcess();
-$commamdLine = $processBuilder->getProcess()->getCommandLine();
+$process = $processBuilder;
+$commamdLine = $processBuilder->getCommandLine();
```
2018-10-23 18:58:57 +00:00
2020-06-16 16:14:51 +00:00
<br><br>
### `ProcessBuilderInstanceRector`
2018-05-04 22:30:32 +00:00
- class: [`Rector\Symfony\Rector\Process\ProcessBuilderInstanceRector`](/../master/rules/symfony/src/Rector/Process/ProcessBuilderInstanceRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Process/ProcessBuilderInstanceRector/Fixture)
2018-05-04 22:30:32 +00:00
Turns `ProcessBuilder::instance()` to new ProcessBuilder in Process in Symfony. Part of multi-step Rector.
2018-07-31 12:50:39 +00:00
```diff
-$processBuilder = Symfony\Component\Process\ProcessBuilder::instance($args);
+$processBuilder = new Symfony\Component\Process\ProcessBuilder($args);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ReadOnlyOptionToAttributeRector`
- class: [`Rector\Symfony\Rector\MethodCall\ReadOnlyOptionToAttributeRector`](/../master/rules/symfony/src/Rector/MethodCall/ReadOnlyOptionToAttributeRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/MethodCall/ReadOnlyOptionToAttributeRector/Fixture)
Change "read_only" option in form to attribute
```diff
use Symfony\Component\Form\FormBuilderInterface;
function buildForm(FormBuilderInterface $builder, array $options)
{
- $builder->add('cuid', TextType::class, ['read_only' => true]);
2019-09-06 20:08:48 +00:00
+ $builder->add('cuid', TextType::class, ['attr' => ['read_only' => true]]);
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RedirectToRouteRector`
- class: [`Rector\Symfony\Rector\Controller\RedirectToRouteRector`](/../master/rules/symfony/src/Rector/Controller/RedirectToRouteRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Controller/RedirectToRouteRector/Fixture)
Turns redirect to route to short helper method in Controller in Symfony
```diff
-$this->redirect($this->generateUrl("homepage"));
+$this->redirectToRoute("homepage");
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveDefaultGetBlockPrefixRector`
- class: [`Rector\Symfony\Rector\ClassMethod\RemoveDefaultGetBlockPrefixRector`](/../master/rules/symfony/src/Rector/ClassMethod/RemoveDefaultGetBlockPrefixRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/ClassMethod/RemoveDefaultGetBlockPrefixRector/Fixture)
Rename `getBlockPrefix()` if it returns the default value - class to underscore, e.g. UserFormType = user_form
```diff
use Symfony\Component\Form\AbstractType;
class TaskType extends AbstractType
{
- public function getBlockPrefix()
- {
- return 'task';
- }
}
```
<br><br>
2019-05-29 13:40:20 +00:00
### `ResponseStatusCodeRector`
- class: [`Rector\Symfony\Rector\BinaryOp\ResponseStatusCodeRector`](/../master/rules/symfony/src/Rector/BinaryOp/ResponseStatusCodeRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/BinaryOp/ResponseStatusCodeRector/Fixture)
2019-05-29 13:40:20 +00:00
Turns status code numbers to constants
```diff
2019-05-29 13:40:20 +00:00
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) {}
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `RootNodeTreeBuilderRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Symfony\Rector\New_\RootNodeTreeBuilderRector`](/../master/rules/symfony/src/Rector/New_/RootNodeTreeBuilderRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/New_/RootNodeTreeBuilderRector/Fixture)
2019-05-29 13:40:20 +00:00
Changes Process string argument to an array
2019-05-29 13:40:20 +00:00
```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();
```
2020-06-16 16:14:51 +00:00
<br><br>
### `SimplifyWebTestCaseAssertionsRector`
- class: [`Rector\Symfony\Rector\MethodCall\SimplifyWebTestCaseAssertionsRector`](/../master/rules/symfony/src/Rector/MethodCall/SimplifyWebTestCaseAssertionsRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/MethodCall/SimplifyWebTestCaseAssertionsRector/Fixture)
Simplify use of assertions in WebTestCase
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
2019-05-29 13:40:20 +00:00
{
public function test()
2019-05-29 13:40:20 +00:00
{
- $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);
}
public function testContains()
{
- $this->assertContains('Hello World', $crawler->filter('h1')->text());
+ $this->assertSelectorTextContains('h1', 'Hello World');
2019-05-29 13:40:20 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `StringFormTypeToClassRector`
- class: [`Rector\Symfony\Rector\Form\StringFormTypeToClassRector`](/../master/rules/symfony/src/Rector/Form/StringFormTypeToClassRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/Form/StringFormTypeToClassRector/Fixture)
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 > symfony_container_xml_path"
```diff
$formBuilder = new Symfony\Component\Form\FormBuilder;
-$formBuilder->add('name', 'form.type.text');
2019-09-06 20:08:48 +00:00
+$formBuilder->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `StringToArrayArgumentProcessRector`
- class: [`Rector\Symfony\Rector\New_\StringToArrayArgumentProcessRector`](/../master/rules/symfony/src/Rector/New_/StringToArrayArgumentProcessRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/New_/StringToArrayArgumentProcessRector/Fixture)
Changes Process string argument to an array
```diff
use Symfony\Component\Process\Process;
-$process = new Process('ls -l');
+$process = new Process(['ls', '-l']);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `VarDumperTestTraitMethodArgsRector`
- class: [`Rector\Symfony\Rector\VarDumper\VarDumperTestTraitMethodArgsRector`](/../master/rules/symfony/src/Rector/VarDumper/VarDumperTestTraitMethodArgsRector.php)
- [test fixtures](/../master/rules/symfony/tests/Rector/VarDumper/VarDumperTestTraitMethodArgsRector/Fixture)
Adds a new `$filter` argument in `VarDumperTestTrait->assertDumpEquals()` and `VarDumperTestTrait->assertDumpMatchesFormat()` in Validator in Symfony.
```diff
-$varDumperTestTrait->assertDumpEquals($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpEquals($dump, $data, $filter = 0, $message = "");
```
```diff
-$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $filter = 0, $message = "");
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
## SymfonyCodeQuality
### `EventListenerToEventSubscriberRector`
- class: [`Rector\SymfonyCodeQuality\Rector\Class_\EventListenerToEventSubscriberRector`](/../master/rules/symfony-code-quality/src/Rector/Class_/EventListenerToEventSubscriberRector.php)
- [test fixtures](/../master/rules/symfony-code-quality/tests/Rector/Class_/EventListenerToEventSubscriberRector/Fixture)
2019-08-05 21:10:47 +00:00
Change Symfony Event listener class to Event Subscriber based on configuration in service.yaml file
```diff
<?php
-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' }
+}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
## SymfonyPHPUnit
2019-09-21 19:06:31 +00:00
### `SelfContainerGetMethodCallFromTestToSetUpMethodRector`
- class: [`Rector\SymfonyPHPUnit\Rector\Class_\SelfContainerGetMethodCallFromTestToSetUpMethodRector`](/../master/rules/symfony-phpunit/src/Rector/Class_/SelfContainerGetMethodCallFromTestToSetUpMethodRector.php)
- [test fixtures](/../master/rules/symfony-phpunit/tests/Rector/Class_/SelfContainerGetMethodCallFromTestToSetUpMethodRector/Fixture)
2019-09-21 22:14:49 +00:00
Move self::$container service fetching from test methods up to setUp method
```diff
use ItemRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class SomeTest extends KernelTestCase
{
+ /**
+ * @var \ItemRepository
+ */
+ private $itemRepository;
+
+ protected function setUp()
+ {
+ parent::setUp();
+ $this->itemRepository = self::$container->get(ItemRepository::class);
+ }
+
public function testOne()
{
- $itemRepository = self::$container->get(ItemRepository::class);
- $itemRepository->doStuff();
+ $this->itemRepository->doStuff();
}
public function testTwo()
{
- $itemRepository = self::$container->get(ItemRepository::class);
- $itemRepository->doAnotherStuff();
+ $this->itemRepository->doAnotherStuff();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
## SymfonyPhpConfig
### `AddEmptyLineBetweenCallsInPhpConfigRector`
- class: [`Rector\SymfonyPhpConfig\Rector\Closure\AddEmptyLineBetweenCallsInPhpConfigRector`](/../master/rules/symfony-php-config/src/Rector/Closure/AddEmptyLineBetweenCallsInPhpConfigRector.php)
- [test fixtures](/../master/rules/symfony-php-config/tests/Rector/Closure/AddEmptyLineBetweenCallsInPhpConfigRector/Fixture)
Make calls in PHP Symfony config separated by newline
```diff
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$parameters = $containerConfigurator->parameters();
+
$parameters->set('key', 'value');
};
```
<br><br>
2018-09-28 16:33:35 +00:00
## Twig
### `SimpleFunctionAndFilterRector`
- class: [`Rector\Twig\Rector\SimpleFunctionAndFilterRector`](/../master/rules/twig/src/Rector/SimpleFunctionAndFilterRector.php)
- [test fixtures](/../master/rules/twig/tests/Rector/SimpleFunctionAndFilterRector/Fixture)
2018-09-28 16:33:35 +00:00
Changes Twig_Function_Method to Twig_SimpleFunction calls in Twig_Extension.
2018-09-28 16:33:35 +00:00
```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']),
];
}
2019-03-31 12:25:39 +00:00
public function getFilters()
2018-09-28 16:33:35 +00:00
{
return [
- 'is_mobile' => new Twig_Filter_Method($this, 'isMobile'),
+ new Twig_SimpleFilter('is_mobile', [$this, 'isMobile']),
];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
## TypeDeclaration
2019-08-17 13:06:02 +00:00
### `AddArrayParamDocTypeRector`
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddArrayParamDocTypeRector`](/../master/rules/type-declaration/src/Rector/ClassMethod/AddArrayParamDocTypeRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/ClassMethod/AddArrayParamDocTypeRector/Fixture)
2019-08-17 13:06:02 +00:00
Adds @param annotation to array parameters inferred from the rest of the code
```diff
class SomeClass
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @param int[] $values
+ */
public function __construct(array $values)
{
$this->values = $values;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-17 13:06:02 +00:00
### `AddArrayReturnDocTypeRector`
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddArrayReturnDocTypeRector`](/../master/rules/type-declaration/src/Rector/ClassMethod/AddArrayReturnDocTypeRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/ClassMethod/AddArrayReturnDocTypeRector/Fixture)
2019-08-17 13:06:02 +00:00
Adds @return annotation to array parameters inferred from the rest of the code
```diff
class SomeClass
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @return int[]
+ */
public function getValues(): array
{
return $this->values;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-17 13:06:02 +00:00
### `AddClosureReturnTypeRector`
2019-05-19 08:27:38 +00:00
- class: [`Rector\TypeDeclaration\Rector\Closure\AddClosureReturnTypeRector`](/../master/rules/type-declaration/src/Rector/Closure/AddClosureReturnTypeRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/Closure/AddClosureReturnTypeRector/Fixture)
2019-05-19 08:27:38 +00:00
Add known return type to functions
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
{
public function run($meetups)
2019-05-19 08:27:38 +00:00
{
2019-09-25 08:49:53 +00:00
- return array_filter($meetups, function (Meetup $meetup) {
+ return array_filter($meetups, function (Meetup $meetup): bool {
return is_object($meetup);
});
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `AddMethodCallBasedParamTypeRector`
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedParamTypeRector`](/../master/rules/type-declaration/src/Rector/ClassMethod/AddMethodCallBasedParamTypeRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/ClassMethod/AddMethodCallBasedParamTypeRector/Fixture)
2019-09-25 08:49:53 +00:00
2020-06-21 14:49:47 +00:00
Change param type of passed `getId()` to UuidInterface type declaration
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
{
- public function getById($id)
+ public function getById(\Ramsey\Uuid\UuidInterface $id)
{
}
}
class CallerClass
{
public function run()
{
$building = new Building();
$someClass = new SomeClass();
$someClass->getById($building->getId());
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
2019-12-18 09:53:46 +00:00
### `AddParamTypeDeclarationRector`
- class: [`Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector`](/../master/rules/type-declaration/src/Rector/ClassMethod/AddParamTypeDeclarationRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/ClassMethod/AddParamTypeDeclarationRector/Fixture)
2019-12-18 09:53:46 +00:00
Add param types where needed
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(AddParamTypeDeclarationRector::class)
->arg('$typehintForParameterByMethodByClass', ['SomeClass' => ['process' => ['string']]]);
};
2019-12-18 09:53:46 +00:00
```
```diff
class SomeClass
{
- public function process($name)
+ public function process(string $name)
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
2019-09-25 08:49:53 +00:00
### `CompleteVarDocTypePropertyRector`
- class: [`Rector\TypeDeclaration\Rector\Property\CompleteVarDocTypePropertyRector`](/../master/rules/type-declaration/src/Rector/Property/CompleteVarDocTypePropertyRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/Property/CompleteVarDocTypePropertyRector/Fixture)
2019-09-25 08:49:53 +00:00
Complete property `@var` annotations or correct the old ones
```diff
final class SomeClass
{
+ /**
+ * @var EventDispatcher
+ */
private $eventDispatcher;
public function __construct(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
2019-05-19 08:27:38 +00:00
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
### `ParamTypeDeclarationRector`
- class: [`Rector\TypeDeclaration\Rector\FunctionLike\ParamTypeDeclarationRector`](/../master/rules/type-declaration/src/Rector/FunctionLike/ParamTypeDeclarationRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/FunctionLike/ParamTypeDeclarationRector/Fixture)
2019-05-19 08:27:38 +00:00
Change @param types to type declarations if not a BC-break
```diff
<?php
class ParentClass
{
/**
* @param int $number
*/
public function keep($number)
{
}
}
final class ChildClass extends ParentClass
{
/**
* @param int $number
*/
public function keep($number)
{
}
/**
* @param int $number
*/
- public function change($number)
+ public function change(int $number)
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-19 08:27:38 +00:00
2019-08-05 21:10:47 +00:00
### `PropertyTypeDeclarationRector`
- class: [`Rector\TypeDeclaration\Rector\Property\PropertyTypeDeclarationRector`](/../master/rules/type-declaration/src/Rector/Property/PropertyTypeDeclarationRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/Property/PropertyTypeDeclarationRector/Fixture)
2019-08-05 21:10:47 +00:00
2019-09-15 18:28:10 +00:00
Add @var to properties that are missing it
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
+ /**
+ * @var int
+ */
private $value;
public function run()
{
$this->value = 123;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `ReturnTypeDeclarationRector`
2018-05-04 22:30:32 +00:00
- class: [`Rector\TypeDeclaration\Rector\FunctionLike\ReturnTypeDeclarationRector`](/../master/rules/type-declaration/src/Rector/FunctionLike/ReturnTypeDeclarationRector.php)
- [test fixtures](/../master/rules/type-declaration/tests/Rector/FunctionLike/ReturnTypeDeclarationRector/Fixture)
2018-08-01 20:09:34 +00:00
Change @return types and type from static analysis to type declarations if not a BC-break
2018-05-04 22:30:32 +00:00
```diff
<?php
2019-05-29 13:40:20 +00:00
class SomeClass
{
/**
* @return int
*/
- public function getCount()
+ public function getCount(): int
2019-05-29 13:40:20 +00:00
{
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
---
2019-05-29 13:40:20 +00:00
## General
- [Core](#core) (39)
2019-05-29 13:40:20 +00:00
## Core
### `ActionInjectionToConstructorInjectionRector`
- class: [`Rector\Core\Rector\Architecture\DependencyInjection\ActionInjectionToConstructorInjectionRector`](/../master/src/Rector/Architecture/DependencyInjection/ActionInjectionToConstructorInjectionRector.php)
- [test fixtures](/../master/tests/Rector/Architecture/DependencyInjection/ActionInjectionToConstructorInjectionRector/Fixture)
Turns action injection in Controllers to constructor injection
```diff
final class SomeController
2018-08-01 20:09:34 +00:00
{
- 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();
}
2018-08-01 20:09:34 +00:00
}
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-19 22:07:06 +00:00
### `AddInterfaceByTraitRector`
- class: [`Rector\Core\Rector\Class_\AddInterfaceByTraitRector`](/../master/src/Rector/Class_/AddInterfaceByTraitRector.php)
- [test fixtures](/../master/tests/Rector/Class_/AddInterfaceByTraitRector/Fixture)
2019-12-19 22:07:06 +00:00
Add interface by used trait
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Class_\AddInterfaceByTraitRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(AddInterfaceByTraitRector::class)
->arg('$interfaceByTrait', ['SomeTrait' => 'SomeInterface']);
};
2019-12-19 22:07:06 +00:00
```
```diff
-class SomeClass
+class SomeClass implements SomeInterface
{
use SomeTrait;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-19 22:07:06 +00:00
2019-06-06 13:01:53 +00:00
### `AddMethodParentCallRector`
- class: [`Rector\Core\Rector\ClassMethod\AddMethodParentCallRector`](/../master/src/Rector/ClassMethod/AddMethodParentCallRector.php)
- [test fixtures](/../master/tests/Rector/ClassMethod/AddMethodParentCallRector/Fixture)
2019-06-06 13:01:53 +00:00
Add method parent call, in case new parent method is added
```diff
class SunshineCommand extends ParentClassWithNewConstructor
{
public function __construct()
{
$value = 5;
+
+ parent::__construct();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-06-06 13:01:53 +00:00
### `AddReturnTypeDeclarationRector`
2018-05-04 22:30:32 +00:00
- class: [`Rector\Core\Rector\ClassMethod\AddReturnTypeDeclarationRector`](/../master/src/Rector/ClassMethod/AddReturnTypeDeclarationRector.php)
- [test fixtures](/../master/tests/Rector/ClassMethod/AddReturnTypeDeclarationRector/Fixture)
2018-05-04 22:30:32 +00:00
2020-06-16 16:13:37 +00:00
Changes defined return typehint of method and class.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\ClassMethod\AddReturnTypeDeclarationRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(AddReturnTypeDeclarationRector::class)
->arg('$typehintForMethodByClass', ['SomeClass' => ['getData' => 'array']]);
};
2018-05-04 22:30:32 +00:00
```
2018-08-01 20:09:34 +00:00
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
2019-12-26 10:21:09 +00:00
- public getData()
+ public getData(): array
{
}
2019-05-29 13:40:20 +00:00
}
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `AnnotatedPropertyInjectToConstructorInjectionRector`
- class: [`Rector\Core\Rector\Architecture\DependencyInjection\AnnotatedPropertyInjectToConstructorInjectionRector`](/../master/src/Rector/Architecture/DependencyInjection/AnnotatedPropertyInjectToConstructorInjectionRector.php)
- [test fixtures](/../master/tests/Rector/Architecture/DependencyInjection/AnnotatedPropertyInjectToConstructorInjectionRector/Fixture)
Turns non-private properties with `@annotation` to private properties and constructor injection
2018-05-04 22:30:32 +00:00
```diff
/**
* @var SomeService
- * @inject
*/
-public $someService;
+private $someService;
+
+public function __construct(SomeService $someService)
+{
+ $this->someService = $someService;
+}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ArgumentAdderRector`
- class: [`Rector\Core\Rector\Argument\ArgumentAdderRector`](/../master/src/Rector/Argument/ArgumentAdderRector.php)
- [test fixtures](/../master/tests/Rector/Argument/ArgumentAdderRector/Fixture)
2020-06-16 16:13:37 +00:00
This Rector adds new default arguments in calls of defined methods and class types.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Argument\ArgumentAdderRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ArgumentAdderRector::class)
->arg('$positionWithDefaultValueByMethodNamesByClassTypes', ['SomeExampleClass' => ['someMethod' => [['name' => 'someArgument', 'default_value' => 'true', 'type' => 'SomeType']]]]);
};
2018-05-04 22:30:32 +00:00
```
2018-08-01 20:09:34 +00:00
2018-05-04 22:30:32 +00:00
```diff
$someObject = new SomeExampleClass;
-$someObject->someMethod();
+$someObject->someMethod(true);
2018-05-04 22:30:32 +00:00
```
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Argument\ArgumentAdderRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ArgumentAdderRector::class)
->arg('$positionWithDefaultValueByMethodNamesByClassTypes', ['SomeExampleClass' => ['someMethod' => [['name' => 'someArgument', 'default_value' => 'true', 'type' => 'SomeType']]]]);
};
2018-08-01 20:09:34 +00:00
```
2018-05-04 22:30:32 +00:00
```diff
class MyCustomClass extends SomeExampleClass
2019-05-29 13:40:20 +00:00
{
- public function someMethod()
+ public function someMethod($value = true)
2019-05-29 13:40:20 +00:00
{
}
}
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ArgumentDefaultValueReplacerRector`
2019-03-16 20:31:46 +00:00
- class: [`Rector\Core\Rector\Argument\ArgumentDefaultValueReplacerRector`](/../master/src/Rector/Argument/ArgumentDefaultValueReplacerRector.php)
- [test fixtures](/../master/tests/Rector/Argument/ArgumentDefaultValueReplacerRector/Fixture)
2019-03-16 20:31:46 +00:00
2020-06-16 16:13:37 +00:00
Replaces defined map of arguments in defined methods and their calls.
2019-03-16 20:31:46 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Argument\ArgumentDefaultValueReplacerRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ArgumentDefaultValueReplacerRector::class)
->arg('SomeExampleClass', ['someMethod' => [[['before' => 'SomeClass::OLD_CONSTANT', 'after' => 'false']]]]);
};
2019-03-16 20:31:46 +00:00
```
```diff
$someObject = new SomeClass;
-$someObject->someMethod(SomeClass::OLD_CONSTANT);
+$someObject->someMethod(false);'
2019-03-16 20:31:46 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-03-16 20:31:46 +00:00
### `ArgumentRemoverRector`
- class: [`Rector\Core\Rector\Argument\ArgumentRemoverRector`](/../master/src/Rector/Argument/ArgumentRemoverRector.php)
- [test fixtures](/../master/tests/Rector/Argument/ArgumentRemoverRector/Fixture)
2018-05-04 22:30:32 +00:00
2020-06-16 16:13:37 +00:00
Removes defined arguments in defined methods and their calls.
2018-08-01 20:09:34 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Argument\ArgumentRemoverRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ArgumentRemoverRector::class)
->arg('ExampleClass', ['someMethod' => [['value' => 'true']]]);
};
2018-08-01 20:09:34 +00:00
```
2018-05-04 22:30:32 +00:00
```diff
$someObject = new SomeClass;
-$someObject->someMethod(true);
+$someObject->someMethod();'
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeConstantVisibilityRector`
- class: [`Rector\Core\Rector\Visibility\ChangeConstantVisibilityRector`](/../master/src/Rector/Visibility/ChangeConstantVisibilityRector.php)
- [test fixtures](/../master/tests/Rector/Visibility/ChangeConstantVisibilityRector/Fixture)
Change visibility of constant from parent class.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Visibility\ChangeConstantVisibilityRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ChangeConstantVisibilityRector::class)
->arg('ParentObject', ['SOME_CONSTANT' => 'protected']);
};
```
```diff
class FrameworkClass
2018-10-23 18:58:57 +00:00
{
protected const SOME_CONSTANT = 1;
}
2018-05-04 22:30:32 +00:00
class MyClass extends FrameworkClass
{
- public const SOME_CONSTANT = 1;
+ protected const SOME_CONSTANT = 1;
2018-10-21 22:26:45 +00:00
}
2018-10-12 23:15:00 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeContractMethodSingleToManyRector`
- class: [`Rector\Core\Rector\ClassMethod\ChangeContractMethodSingleToManyRector`](/../master/src/Rector/ClassMethod/ChangeContractMethodSingleToManyRector.php)
- [test fixtures](/../master/tests/Rector/ClassMethod/ChangeContractMethodSingleToManyRector/Fixture)
Change method that returns single value to multiple values
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\ClassMethod\ChangeContractMethodSingleToManyRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ChangeContractMethodSingleToManyRector::class)
->arg('$oldToNewMethodByType', ['SomeClass' => ['getNode' => 'getNodes']]);
};
```
```diff
class SomeClass
{
- public function getNode(): string
+ /**
+ * @return string[]
+ */
+ public function getNodes(): array
{
- return 'Echo_';
+ return ['Echo_'];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangeMethodVisibilityRector`
- class: [`Rector\Core\Rector\Visibility\ChangeMethodVisibilityRector`](/../master/src/Rector/Visibility/ChangeMethodVisibilityRector.php)
- [test fixtures](/../master/tests/Rector/Visibility/ChangeMethodVisibilityRector/Fixture)
2018-07-31 12:50:39 +00:00
Change visibility of method from parent class.
2018-08-01 20:09:34 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Visibility\ChangeMethodVisibilityRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ChangeMethodVisibilityRector::class)
->arg('$methodToVisibilityByClass', ['FrameworkClass' => ['someMethod' => 'protected']]);
};
2018-08-01 20:09:34 +00:00
```
2018-07-31 12:50:39 +00:00
```diff
class FrameworkClass
{
protected someMethod()
{
}
}
class MyClass extends FrameworkClass
{
- public someMethod()
+ protected someMethod()
{
}
}
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ChangePropertyVisibilityRector`
- class: [`Rector\Core\Rector\Visibility\ChangePropertyVisibilityRector`](/../master/src/Rector/Visibility/ChangePropertyVisibilityRector.php)
- [test fixtures](/../master/tests/Rector/Visibility/ChangePropertyVisibilityRector/Fixture)
2018-07-31 12:50:39 +00:00
Change visibility of property from parent class.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Visibility\ChangePropertyVisibilityRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ChangePropertyVisibilityRector::class)
->arg('FrameworkClass', ['someProperty' => 'protected']);
};
2018-08-01 20:09:34 +00:00
```
2018-07-31 12:50:39 +00:00
```diff
class FrameworkClass
{
protected $someProperty;
}
class MyClass extends FrameworkClass
{
- public $someProperty;
+ protected $someProperty;
}
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `FunctionToMethodCallRector`
- class: [`Rector\Core\Rector\Function_\FunctionToMethodCallRector`](/../master/src/Rector/Function_/FunctionToMethodCallRector.php)
- [test fixtures](/../master/tests/Rector/Function_/FunctionToMethodCallRector/Fixture)
2020-06-16 16:13:37 +00:00
Turns defined function calls to local method calls.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Function_\FunctionToMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(FunctionToMethodCallRector::class)
->arg('view', ['this', 'render']);
};
2018-08-01 20:09:34 +00:00
```
2018-08-01 20:09:34 +00:00
2018-08-01 20:09:34 +00:00
```diff
-view("...", []);
+$this->render("...", []);
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `FunctionToNewRector`
2018-09-28 16:33:35 +00:00
- class: [`Rector\Core\Rector\FuncCall\FunctionToNewRector`](/../master/src/Rector/FuncCall/FunctionToNewRector.php)
- [test fixtures](/../master/tests/Rector/FuncCall/FunctionToNewRector/Fixture)
2018-09-28 16:33:35 +00:00
Change configured function calls to new Instance
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
public function run()
{
- $array = collection([]);
+ $array = new \Collection([]);
}
2018-08-01 20:09:34 +00:00
}
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2018-10-23 18:58:57 +00:00
### `FunctionToStaticCallRector`
2019-02-18 15:51:24 +00:00
- class: [`Rector\Core\Rector\Function_\FunctionToStaticCallRector`](/../master/src/Rector/Function_/FunctionToStaticCallRector.php)
- [test fixtures](/../master/tests/Rector/Function_/FunctionToStaticCallRector/Fixture)
2019-02-18 15:51:24 +00:00
2020-06-16 16:13:37 +00:00
Turns defined function call to static method call.
2019-02-18 15:51:24 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Function_\FunctionToStaticCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(FunctionToStaticCallRector::class)
->arg('view', ['SomeStaticClass', 'render']);
};
2019-02-18 15:51:24 +00:00
```
```diff
-view("...", []);
+SomeClass::render("...", []);
2019-02-18 15:51:24 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-02-18 15:51:24 +00:00
### `InjectAnnotationClassRector`
- class: [`Rector\Core\Rector\Property\InjectAnnotationClassRector`](/../master/src/Rector/Property/InjectAnnotationClassRector.php)
- [test fixtures](/../master/tests/Rector/Property/InjectAnnotationClassRector/Fixture)
Changes properties with specified annotations class to constructor injection
2018-05-04 22:30:32 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Property\InjectAnnotationClassRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(InjectAnnotationClassRector::class)
->arg('$annotationClasses', ['DI\Annotation\Inject', 'JMS\DiExtraBundle\Annotation\Inject']);
};
2018-08-01 20:09:34 +00:00
```
2018-05-04 22:30:32 +00:00
2018-08-01 20:09:34 +00:00
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
use JMS\DiExtraBundle\Annotation as DI;
2018-05-04 22:30:32 +00:00
class SomeController
{
/**
- * @DI\Inject("entity.manager")
+ * @var EntityManager
*/
private $entityManager;
+
+ public function __construct(EntityManager $entityManager)
+ {
+ $this->entityManager = entityManager;
+ }
}
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `MergeInterfacesRector`
2018-08-01 20:09:34 +00:00
- class: [`Rector\Core\Rector\Interface_\MergeInterfacesRector`](/../master/src/Rector/Interface_/MergeInterfacesRector.php)
- [test fixtures](/../master/tests/Rector/Interface_/MergeInterfacesRector/Fixture)
Merges old interface to a new one, that already has its methods
2018-05-05 00:04:41 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Interface_\MergeInterfacesRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(MergeInterfacesRector::class)
->arg('SomeOldInterface', 'SomeInterface');
};
2018-08-01 20:09:34 +00:00
```
2018-05-05 00:04:41 +00:00
2018-08-01 20:09:34 +00:00
2018-08-01 20:09:34 +00:00
```diff
-class SomeClass implements SomeInterface, SomeOldInterface
+class SomeClass implements SomeInterface
{
}
2018-05-05 00:04:41 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `MethodCallToAnotherMethodCallWithArgumentsRector`
- class: [`Rector\Core\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector`](/../master/src/Rector/MethodCall/MethodCallToAnotherMethodCallWithArgumentsRector.php)
- [test fixtures](/../master/tests/Rector/MethodCall/MethodCallToAnotherMethodCallWithArgumentsRector/Fixture)
2019-08-24 11:08:59 +00:00
Turns old method call with specific types to new one with arguments
2018-05-04 22:30:32 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(MethodCallToAnotherMethodCallWithArgumentsRector::class)
->arg('Nette\DI\ServiceDefinition', ['setInject' => [['addTag', ['inject']]]]);
};
```
```diff
2019-05-29 13:40:20 +00:00
$serviceDefinition = new Nette\DI\ServiceDefinition;
-$serviceDefinition->setInject();
+$serviceDefinition->addTag('inject');
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2019-11-06 23:52:19 +00:00
### `MethodCallToReturnRector`
- class: [`Rector\Core\Rector\MethodCall\MethodCallToReturnRector`](/../master/src/Rector/MethodCall/MethodCallToReturnRector.php)
- [test fixtures](/../master/tests/Rector/MethodCall/MethodCallToReturnRector/Fixture)
2019-11-06 23:52:19 +00:00
Wrap method call to return
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\MethodCall\MethodCallToReturnRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(MethodCallToReturnRector::class)
->arg('$methodNamesByType', ['SomeClass' => ['deny']]);
};
2019-11-06 23:52:19 +00:00
```
```diff
class SomeClass
{
public function run()
{
- $this->deny();
+ return $this->deny();
}
public function deny()
{
return 1;
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-11-06 23:52:19 +00:00
### `NewObjectToFactoryCreateRector`
- class: [`Rector\Core\Rector\Architecture\Factory\NewObjectToFactoryCreateRector`](/../master/src/Rector/Architecture/Factory/NewObjectToFactoryCreateRector.php)
- [test fixtures](/../master/tests/Rector/Architecture/Factory/NewObjectToFactoryCreateRector/Fixture)
Replaces creating object instances with "new" keyword with factory method.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Architecture\Factory\NewObjectToFactoryCreateRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(NewObjectToFactoryCreateRector::class)
->arg('MyClass', ['class' => 'MyClassFactory', 'method' => 'create']);
};
```
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
+ /**
+ * @var \MyClassFactory
+ */
+ private $myClassFactory;
+
public function example() {
- new MyClass($argument);
+ $this->myClassFactory->create($argument);
}
2019-05-29 13:40:20 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `NewToStaticCallRector`
- class: [`Rector\Core\Rector\New_\NewToStaticCallRector`](/../master/src/Rector/New_/NewToStaticCallRector.php)
- [test fixtures](/../master/tests/Rector/New_/NewToStaticCallRector/Fixture)
Change new Object to static call
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\New_\NewToStaticCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(NewToStaticCallRector::class)
->arg('$typeToStaticCalls', ['Cookie' => ['Cookie', 'create']]);
};
```
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run()
{
- new Cookie($name);
+ Cookie::create($name);
}
2019-05-29 13:40:20 +00:00
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `NormalToFluentRector`
2018-05-04 22:30:32 +00:00
- class: [`Rector\Core\Rector\MethodBody\NormalToFluentRector`](/../master/src/Rector/MethodBody/NormalToFluentRector.php)
- [test fixtures](/../master/tests/Rector/MethodBody/NormalToFluentRector/Fixture)
2018-05-04 22:30:32 +00:00
Turns fluent interface calls to classic ones.
2018-07-31 12:50:39 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\MethodBody\NormalToFluentRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(NormalToFluentRector::class)
->arg('SomeClass', ['someFunction', 'otherFunction']);
};
2018-08-01 20:09:34 +00:00
```
2018-05-04 22:30:32 +00:00
2018-08-01 20:09:34 +00:00
```diff
$someObject = new SomeClass();
-$someObject->someFunction();
-$someObject->otherFunction();
+$someObject->someFunction()
+ ->otherFunction();
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
### `ParentClassToTraitsRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Core\Rector\Class_\ParentClassToTraitsRector`](/../master/src/Rector/Class_/ParentClassToTraitsRector.php)
- [test fixtures](/../master/tests/Rector/Class_/ParentClassToTraitsRector/Fixture)
2019-05-29 13:40:20 +00:00
Replaces parent class to specific traits
2019-05-29 13:40:20 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Class_\ParentClassToTraitsRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ParentClassToTraitsRector::class)
->arg('Nette\Object', ['Nette\SmartObject']);
};
2018-09-28 16:33:35 +00:00
```
```diff
-class SomeClass extends Nette\Object
+class SomeClass
2019-05-29 13:40:20 +00:00
{
+ use Nette\SmartObject;
2019-05-29 13:40:20 +00:00
}
2018-09-28 16:33:35 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `PropertyAssignToMethodCallRector`
- class: [`Rector\Core\Rector\Assign\PropertyAssignToMethodCallRector`](/../master/src/Rector/Assign/PropertyAssignToMethodCallRector.php)
- [test fixtures](/../master/tests/Rector/Assign/PropertyAssignToMethodCallRector/Fixture)
Turns property assign of specific type and property name to method call
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Assign\PropertyAssignToMethodCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(PropertyAssignToMethodCallRector::class)
->arg('$oldPropertiesToNewMethodCallsByType', ['SomeClass' => ['oldPropertyName' => 'oldProperty', 'newMethodName' => 'newMethodCall']]);
};
```
```diff
$someObject = new SomeClass;
-$someObject->oldProperty = false;
+$someObject->newMethodCall(false);
```
2020-06-16 16:14:51 +00:00
<br><br>
### `PropertyToMethodRector`
- class: [`Rector\Core\Rector\Property\PropertyToMethodRector`](/../master/src/Rector/Property/PropertyToMethodRector.php)
- [test fixtures](/../master/tests/Rector/Property/PropertyToMethodRector/Fixture)
2020-06-16 16:13:37 +00:00
Replaces properties assign calls be defined methods.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Property\PropertyToMethodRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(PropertyToMethodRector::class)
->arg('$perClassPropertyToMethods', ['SomeObject' => ['property' => ['get' => 'getProperty', 'set' => 'setProperty']]]);
};
```
2019-05-29 13:40:20 +00:00
```diff
-$result = $object->property;
-$object->property = $value;
+$result = $object->getProperty();
+$object->setProperty($value);
```
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Property\PropertyToMethodRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(PropertyToMethodRector::class)
->arg('$perClassPropertyToMethods', ['SomeObject' => ['property' => ['get' => ['method' => 'getConfig', 'arguments' => ['someArg']]]]]);
};
```
```diff
-$result = $object->property;
+$result = $object->getProperty('someArg');
```
2020-06-16 16:14:51 +00:00
<br><br>
### `PseudoNamespaceToNamespaceRector`
- class: [`Rector\Core\Rector\Namespace_\PseudoNamespaceToNamespaceRector`](/../master/src/Rector/Namespace_/PseudoNamespaceToNamespaceRector.php)
- [test fixtures](/../master/tests/Rector/Namespace_/PseudoNamespaceToNamespaceRector/Fixture)
2020-06-16 16:13:37 +00:00
Replaces defined Pseudo_Namespaces by Namespace\Ones.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Namespace_\PseudoNamespaceToNamespaceRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(PseudoNamespaceToNamespaceRector::class)
->arg('$namespacePrefixesWithExcludedClasses', ['Some_' => ['Some_Class_To_Keep']]);
};
```
```diff
2019-09-25 08:49:53 +00:00
-/** @var Some_Chicken $someService */
-$someService = new Some_Chicken;
+/** @var Some\Chicken $someService */
+$someService = new Some\Chicken;
$someClassToKeep = new Some_Class_To_Keep;
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-05-29 13:40:20 +00:00
2020-05-31 15:26:08 +00:00
### `RemoveFuncCallArgRector`
- class: [`Rector\Core\Rector\FuncCall\RemoveFuncCallArgRector`](/../master/src/Rector/FuncCall/RemoveFuncCallArgRector.php)
- [test fixtures](/../master/tests/Rector/FuncCall/RemoveFuncCallArgRector/Fixture)
Remove argument by position by function name
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\FuncCall\RemoveFuncCallArgRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RemoveFuncCallArgRector::class)
->arg('$argumentPositionByFunctionName', ['remove_last_arg' => [1]]);
};
2020-05-31 15:26:08 +00:00
```
```diff
-remove_last_arg(1, 2);
+remove_last_arg(1);
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-31 15:26:08 +00:00
### `RemoveIniGetSetFuncCallRector`
- class: [`Rector\Core\Rector\FuncCall\RemoveIniGetSetFuncCallRector`](/../master/src/Rector/FuncCall/RemoveIniGetSetFuncCallRector.php)
- [test fixtures](/../master/tests/Rector/FuncCall/RemoveIniGetSetFuncCallRector/Fixture)
2020-06-16 14:39:45 +00:00
Remove `ini_get` by configuration
2020-05-31 15:26:08 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\FuncCall\RemoveIniGetSetFuncCallRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RemoveIniGetSetFuncCallRector::class)
->arg('$keysToRemove', ['y2k_compliance']);
};
2020-05-31 15:26:08 +00:00
```
```diff
-ini_get('y2k_compliance');
-ini_set('y2k_compliance', 1);
```
2020-06-16 16:14:51 +00:00
<br><br>
2020-05-31 15:26:08 +00:00
### `RemoveInterfacesRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Core\Rector\Interface_\RemoveInterfacesRector`](/../master/src/Rector/Interface_/RemoveInterfacesRector.php)
- [test fixtures](/../master/tests/Rector/Interface_/RemoveInterfacesRector/Fixture)
2019-05-29 13:40:20 +00:00
Removes interfaces usage from class.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Interface_\RemoveInterfacesRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RemoveInterfacesRector::class)
->arg(0, 'SomeInterface');
};
```
```diff
-class SomeClass implements SomeInterface
+class SomeClass
{
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RemoveTraitRector`
- class: [`Rector\Core\Rector\ClassLike\RemoveTraitRector`](/../master/src/Rector/ClassLike/RemoveTraitRector.php)
- [test fixtures](/../master/tests/Rector/ClassLike/RemoveTraitRector/Fixture)
Remove specific traits from code
```diff
class SomeClass
{
- use SomeTrait;
}
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RenameClassConstantsUseToStringsRector`
- class: [`Rector\Core\Rector\Constant\RenameClassConstantsUseToStringsRector`](/../master/src/Rector/Constant/RenameClassConstantsUseToStringsRector.php)
- [test fixtures](/../master/tests/Rector/Constant/RenameClassConstantsUseToStringsRector/Fixture)
Replaces constant by value
2019-05-29 13:40:20 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Constant\RenameClassConstantsUseToStringsRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenameClassConstantsUseToStringsRector::class)
->arg('Nette\Configurator', ['DEVELOPMENT' => 'development', 'PRODUCTION' => 'production']);
};
2019-05-29 13:40:20 +00:00
```
```diff
-$value === Nette\Configurator::DEVELOPMENT
+$value === "development"
2019-05-29 13:40:20 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `RenamePropertyRector`
2019-05-29 13:40:20 +00:00
- class: [`Rector\Core\Rector\Property\RenamePropertyRector`](/../master/src/Rector/Property/RenamePropertyRector.php)
- [test fixtures](/../master/tests/Rector/Property/RenamePropertyRector/Fixture)
2019-05-29 13:40:20 +00:00
2020-06-16 16:13:37 +00:00
Replaces defined old properties by new ones.
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\Property\RenamePropertyRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(RenamePropertyRector::class)
->arg('$oldToNewPropertyByTypes', ['SomeClass' => ['someOldProperty' => 'someNewProperty']]);
};
```
2019-05-29 13:40:20 +00:00
```diff
-$someObject->someOldProperty;
+$someObject->someNewProperty;
2018-07-31 12:50:39 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `ReplaceVariableByPropertyFetchRector`
- class: [`Rector\Core\Rector\Architecture\DependencyInjection\ReplaceVariableByPropertyFetchRector`](/../master/src/Rector/Architecture/DependencyInjection/ReplaceVariableByPropertyFetchRector.php)
2018-05-04 22:30:32 +00:00
Turns variable in controller action to property fetch, as follow up to action injection variable to property change.
2018-08-01 20:09:34 +00:00
```diff
final class SomeController
{
/**
* @var ProductRepository
*/
private $productRepository;
2018-08-01 20:09:34 +00:00
public function __construct(ProductRepository $productRepository)
{
$this->productRepository = $productRepository;
}
2018-05-04 22:30:32 +00:00
public function default()
{
- $products = $productRepository->fetchAll();
+ $products = $this->productRepository->fetchAll();
}
}
2018-08-01 20:09:34 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `ServiceGetterToConstructorInjectionRector`
- class: [`Rector\Core\Rector\MethodCall\ServiceGetterToConstructorInjectionRector`](/../master/src/Rector/MethodCall/ServiceGetterToConstructorInjectionRector.php)
- [test fixtures](/../master/tests/Rector/MethodCall/ServiceGetterToConstructorInjectionRector/Fixture)
2019-08-05 21:10:47 +00:00
Get service call to constructor injection
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\MethodCall\ServiceGetterToConstructorInjectionRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(ServiceGetterToConstructorInjectionRector::class)
->arg('$methodNamesByTypesToServiceTypes', ['FirstService' => ['getAnotherService' => 'AnotherService']]);
};
2019-08-05 21:10:47 +00:00
```
```diff
final class SomeClass
{
/**
* @var FirstService
*/
private $firstService;
2019-08-05 21:10:47 +00:00
- public function __construct(FirstService $firstService)
- {
- $this->firstService = $firstService;
- }
-
- public function run()
- {
- $anotherService = $this->firstService->getAnotherService();
- $anotherService->run();
- }
-}
-
-class FirstService
-{
/**
* @var AnotherService
*/
private $anotherService;
2019-08-05 21:10:47 +00:00
- 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();
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-08-05 21:10:47 +00:00
### `StaticCallToFunctionRector`
2018-05-04 22:30:32 +00:00
- class: [`Rector\Core\Rector\StaticCall\StaticCallToFunctionRector`](/../master/src/Rector/StaticCall/StaticCallToFunctionRector.php)
- [test fixtures](/../master/tests/Rector/StaticCall/StaticCallToFunctionRector/Fixture)
Turns static call to function call.
2018-05-04 22:30:32 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\StaticCall\StaticCallToFunctionRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(StaticCallToFunctionRector::class)
->arg('$staticCallToFunction', ['OldClass' => ['oldMethod' => 'new_function']]);
};
2018-08-01 20:09:34 +00:00
```
2018-05-04 22:30:32 +00:00
```diff
-OldClass::oldMethod("args");
+new_function("args");
2018-07-31 06:38:48 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
### `StringToClassConstantRector`
- class: [`Rector\Core\Rector\String_\StringToClassConstantRector`](/../master/src/Rector/String_/StringToClassConstantRector.php)
- [test fixtures](/../master/tests/Rector/String_/StringToClassConstantRector/Fixture)
2018-05-04 22:30:32 +00:00
Changes strings to specific constants
2018-05-04 22:30:32 +00:00
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\String_\StringToClassConstantRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(StringToClassConstantRector::class)
->arg('compiler.post_dump', ['Yet\AnotherClass', 'CONSTANT']);
};
2018-08-01 20:09:34 +00:00
```
2018-05-04 22:30:32 +00:00
```diff
final class SomeSubscriber
{
public static function getSubscribedEvents()
{
- return ['compiler.post_dump' => 'compile'];
+ return [\Yet\AnotherClass::CONSTANT => 'compile'];
}
}
2018-05-04 22:30:32 +00:00
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
### `SwapClassMethodArgumentsRector`
- class: [`Rector\Core\Rector\StaticCall\SwapClassMethodArgumentsRector`](/../master/src/Rector/StaticCall/SwapClassMethodArgumentsRector.php)
- [test fixtures](/../master/tests/Rector/StaticCall/SwapClassMethodArgumentsRector/Fixture)
2019-12-18 09:53:46 +00:00
Reorder class method arguments, including their calls
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\StaticCall\SwapClassMethodArgumentsRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(SwapClassMethodArgumentsRector::class)
->arg('$newArgumentPositionsByMethodAndClass', ['SomeClass' => ['run' => [1, 0]]]);
};
2019-12-18 09:53:46 +00:00
```
```diff
class SomeClass
{
- public static function run($first, $second)
+ public static function run($second, $first)
{
- self::run($first, $second);
+ self::run($second, $first);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-12-18 09:53:46 +00:00
2019-09-25 08:49:53 +00:00
### `SwapFuncCallArgumentsRector`
- class: [`Rector\Core\Rector\Argument\SwapFuncCallArgumentsRector`](/../master/src/Rector/Argument/SwapFuncCallArgumentsRector.php)
- [test fixtures](/../master/tests/Rector/Argument/SwapFuncCallArgumentsRector/Fixture)
2019-09-25 08:49:53 +00:00
Swap arguments in function calls
```diff
final class SomeClass
{
public function run($one, $two)
{
- return some_function($one, $two);
+ return some_function($two, $one);
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>
2019-09-25 08:49:53 +00:00
### `WrapReturnRector`
- class: [`Rector\Core\Rector\ClassMethod\WrapReturnRector`](/../master/src/Rector/ClassMethod/WrapReturnRector.php)
- [test fixtures](/../master/tests/Rector/ClassMethod/WrapReturnRector/Fixture)
Wrap return value of specific method
2020-07-24 11:46:57 +00:00
```php
<?php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Core\Rector\ClassMethod\WrapReturnRector;
return function (ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfiguration->services();
$services->set(WrapReturnRector::class)
->arg('SomeClass', ['getItem' => 'array']);
};
```
```diff
final class SomeClass
{
public function getItem()
{
- return 1;
+ return [1];
}
}
```
2020-06-16 16:14:51 +00:00
<br><br>