rector/docs/rector_rules_overview.md

15913 lines
338 KiB
Markdown
Raw Normal View History

# Rules Overview
2020-02-13 13:42:40 +00:00
## AbsolutizeRequireAndIncludePathRector
2020-02-13 13:42:40 +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.
2020-02-13 13:42:40 +00:00
- class: `Rector\CodeQuality\Rector\Include_\AbsolutizeRequireAndIncludePathRector`
2020-02-13 13:42:40 +00:00
```diff
class SomeClass
2020-02-13 13:42:40 +00:00
{
public function run()
2020-02-13 13:42:40 +00:00
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
require $variable;
2020-02-13 13:42:40 +00:00
}
}
```
<br>
2020-02-13 13:42:40 +00:00
## ActionInjectionToConstructorInjectionRector
2020-02-13 13:42:40 +00:00
Turns action injection in Controllers to constructor injection
2020-02-13 13:42:40 +00:00
- class: `Rector\Generic\Rector\Class_\ActionInjectionToConstructorInjectionRector`
2020-02-13 13:42:40 +00:00
```diff
final class SomeController
2020-02-13 13:42:40 +00:00
{
- public function default(ProductRepository $productRepository)
2020-02-13 13:42:40 +00:00
+ /**
+ * @var ProductRepository
+ */
+ private $productRepository;
+ public function __construct(ProductRepository $productRepository)
{
- $products = $productRepository->fetchAll();
2020-02-13 13:42:40 +00:00
+ $this->productRepository = $productRepository;
+ }
+
+ public function default()
+ {
+ $products = $this->productRepository->fetchAll();
2020-02-13 13:42:40 +00:00
}
}
```
<br>
2019-09-15 18:28:10 +00:00
## ActionSuffixRemoverRector
2019-09-15 18:28:10 +00:00
Removes Action suffixes from methods in Symfony Controllers
2019-09-15 18:28:10 +00:00
- class: `Rector\Symfony\Rector\ClassMethod\ActionSuffixRemoverRector`
2019-09-15 18:28:10 +00:00
```diff
class SomeController
2019-09-15 18:28:10 +00:00
{
- public function indexAction()
+ public function index()
{
}
2019-09-15 18:28:10 +00:00
}
```
<br>
2019-09-15 18:28:10 +00:00
## AddArrayDefaultToArrayPropertyRector
2019-09-15 18:28:10 +00:00
Adds array default value to property to prevent foreach over null error
2019-09-15 18:28:10 +00:00
- class: `Rector\CodingStyle\Rector\Class_\AddArrayDefaultToArrayPropertyRector`
2019-09-15 18:28:10 +00:00
```diff
class SomeClass
2019-09-15 18:28:10 +00:00
{
/**
* @var int[]
*/
- private $values;
+ private $values = [];
public function isEmpty()
{
- return $this->values === null;
+ return $this->values === [];
}
}
2019-09-15 18:28:10 +00:00
```
<br>
2019-09-15 18:28:10 +00:00
## AddArrayParamDocTypeRector
2019-09-15 18:28:10 +00:00
Adds `@param` annotation to array parameters inferred from the rest of the code
2019-09-15 18:28:10 +00:00
- class: `Rector\TypeDeclaration\Rector\ClassMethod\AddArrayParamDocTypeRector`
2019-09-15 18:28:10 +00:00
```diff
class SomeClass
{
/**
* @var int[]
*/
private $values;
2020-07-24 11:46:57 +00:00
+ /**
+ * @param int[] $values
+ */
public function __construct(array $values)
{
$this->values = $values;
}
}
```
<br>
2020-07-24 11:46:57 +00:00
## AddArrayReturnDocTypeRector
Adds `@return` annotation to array parameters inferred from the rest of the code
2019-09-15 18:28:10 +00:00
- class: `Rector\TypeDeclaration\Rector\ClassMethod\AddArrayReturnDocTypeRector`
2019-09-15 18:28:10 +00:00
```diff
class SomeClass
2019-09-15 18:28:10 +00:00
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @return int[]
+ */
public function getValues(): array
{
return $this->values;
}
2019-09-15 18:28:10 +00:00
}
```
<br>
2019-12-26 10:21:09 +00:00
## AddClosureReturnTypeRector
2019-12-26 10:21:09 +00:00
Add known return type to functions
2019-12-26 10:21:09 +00:00
- class: `Rector\TypeDeclaration\Rector\Closure\AddClosureReturnTypeRector`
```diff
class SomeClass
{
public function run($meetups)
{
- return array_filter($meetups, function (Meetup $meetup) {
+ return array_filter($meetups, function (Meetup $meetup): bool {
return is_object($meetup);
});
}
}
```
<br>
## AddDefaultValueForUndefinedVariableRector
Adds default value for undefined variable
- class: `Rector\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector`
```diff
class SomeClass
{
public function run()
{
+ $a = null;
if (rand(0, 1)) {
$a = 5;
}
echo $a;
}
}
```
<br>
2019-12-26 10:21:09 +00:00
## AddDoesNotPerformAssertionToNonAssertingTestRector
2018-09-28 16:33:35 +00:00
Tests without assertion will have `@doesNotPerformAssertion`
- class: `Rector\PHPUnit\Rector\ClassMethod\AddDoesNotPerformAssertionToNonAssertingTestRector`
```diff
class SomeClass extends PHPUnit\Framework\TestCase
{
+ /**
+ * @doesNotPerformAssertions
+ */
public function test()
{
$nothing = 5;
}
}
```
<br>
## AddEntityIdByConditionRector
Add entity id with annotations when meets condition
:wrench: **configure it!**
- class: `Rector\Doctrine\Rector\Class_\AddEntityIdByConditionRector`
```php
use Rector\Doctrine\Rector\Class_\AddEntityIdByConditionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddEntityIdByConditionRector::class);
};
```
```diff
class SomeClass
{
use SomeTrait;
+
+ /**
+ * @ORM\Id
+ * @ORM\Column(type="integer")
+ * @ORM\GeneratedValue(strategy="AUTO")
+ */
+ private $id;
+
+ public function getId(): int
+ {
+ return $this->id;
+ }
}
```
<br>
## AddFalseDefaultToBoolPropertyRector
Add false default to bool properties, to prevent null compare errors
- class: `Rector\SOLID\Rector\Property\AddFalseDefaultToBoolPropertyRector`
```diff
class SomeClass
{
/**
* @var bool
*/
- private $isDisabled;
+ private $isDisabled = false;
}
```
<br>
## AddFlashRector
Turns long flash adding to short helper method in Controller in Symfony
- class: `Rector\Symfony\Rector\MethodCall\AddFlashRector`
```diff
class SomeController extends Controller
{
public function some(Request $request)
{
- $request->getSession()->getFlashBag()->add("success", "something");
+ $this->addFlash("success", "something");
}
}
```
<br>
## AddGuardToLoginEventRector
Add new `$guard` argument to Illuminate\Auth\Events\Login
- class: `Rector\Laravel\Rector\New_\AddGuardToLoginEventRector`
2018-09-28 16:33:35 +00:00
```diff
use Illuminate\Auth\Events\Login;
2018-09-28 16:33:35 +00:00
final class SomeClass
{
public function run(): void
{
- $loginEvent = new Login('user', false);
+ $guard = config('auth.defaults.guard');
+ $loginEvent = new Login($guard, 'user', false);
}
}
2018-09-28 16:33:35 +00:00
```
2018-08-01 20:09:34 +00:00
<br>
2019-10-02 08:04:14 +00:00
## AddInterfaceByTraitRector
2019-10-02 08:04:14 +00:00
Add interface by used trait
2019-10-02 08:04:14 +00:00
:wrench: **configure it!**
2020-07-24 11:46:57 +00:00
- class: `Rector\Generic\Rector\Class_\AddInterfaceByTraitRector`
```php
use Rector\Generic\Rector\Class_\AddInterfaceByTraitRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(AddInterfaceByTraitRector::class)
->call('configure', [[
AddInterfaceByTraitRector::INTERFACE_BY_TRAIT => [
'SomeTrait' => SomeInterface::class,
],
]]);
2020-07-24 11:46:57 +00:00
};
2019-10-02 08:04:14 +00:00
```
```diff
-class SomeClass
+class SomeClass implements SomeInterface
{
use SomeTrait;
}
2019-10-02 08:04:14 +00:00
```
<br>
## AddLiteralSeparatorToNumberRector
Add "_" as thousands separator in numbers
- class: `Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector`
```diff
class SomeClass
{
public function run()
{
- $int = 1000;
- $float = 1000500.001;
+ $int = 1_000;
+ $float = 1_000_500.001;
}
}
```
<br>
## AddMessageToEqualsResponseCodeRector
Add response content to response code assert, so it is easier to debug
- class: `Rector\PHPUnitSymfony\Rector\StaticCall\AddMessageToEqualsResponseCodeRector`
```diff
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
final class SomeClassTest extends TestCase
{
public function test(Response $response)
{
$this->assertEquals(
Response::HTTP_NO_CONTENT,
$response->getStatusCode()
+ $response->getContent()
);
}
}
```
<br>
2019-03-09 13:24:30 +00:00
## AddMethodCallBasedParamTypeRector
2020-01-03 18:20:13 +00:00
Change param type of passed `getId()` to UuidInterface type declaration
2020-01-03 18:20:13 +00:00
- class: `Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedParamTypeRector`
2020-01-03 18:20:13 +00:00
```diff
class SomeClass
{
- public function getById($id)
+ public function getById(\Ramsey\Uuid\UuidInterface $id)
2020-01-03 18:20:13 +00:00
{
}
}
2020-01-03 18:20:13 +00:00
class CallerClass
{
public function run()
{
$building = new Building();
$someClass = new SomeClass();
$someClass->getById($building->getId());
2020-01-03 18:20:13 +00:00
}
}
```
<br>
2020-01-03 18:20:13 +00:00
## AddMethodParentCallRector
2019-11-06 23:52:19 +00:00
Add method parent call, in case new parent method is added
2019-11-06 23:52:19 +00:00
:wrench: **configure it!**
2019-11-06 23:52:19 +00:00
- class: `Rector\Generic\Rector\ClassMethod\AddMethodParentCallRector`
2019-11-06 23:52:19 +00:00
```php
use Rector\Generic\Rector\ClassMethod\AddMethodParentCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-11-06 23:52:19 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-03-09 13:24:30 +00:00
$services->set(AddMethodParentCallRector::class)
->call('configure', [[
AddMethodParentCallRector::METHODS_BY_PARENT_TYPES => [
'ParentClassWithNewConstructor' => '__construct',
],
]]);
};
```
2019-05-29 13:40:20 +00:00
2019-03-09 13:24:30 +00:00
```diff
class SunshineCommand extends ParentClassWithNewConstructor
2019-03-09 13:24:30 +00:00
{
public function __construct()
2019-03-09 13:24:30 +00:00
{
$value = 5;
+
+ parent::__construct();
2019-03-09 13:24:30 +00:00
}
}
```
<br>
2019-03-09 13:24:30 +00:00
## AddMockConsoleOutputFalseToConsoleTestsRector
2020-01-03 18:20:13 +00:00
Add "$this->mockConsoleOutput = false"; to console tests that work with output content
2020-01-03 18:20:13 +00:00
- class: `Rector\Laravel\Rector\Class_\AddMockConsoleOutputFalseToConsoleTestsRector`
2020-01-03 18:20:13 +00:00
```diff
use Illuminate\Support\Facades\Artisan;
use Illuminate\Foundation\Testing\TestCase;
final class SomeTest extends TestCase
2020-01-03 18:20:13 +00:00
{
+ public function setUp(): void
+ {
+ parent::setUp();
+
+ $this->mockConsoleOutput = false;
+ }
+
public function test(): void
2020-01-03 18:20:13 +00:00
{
$this->assertEquals('content', \trim((new Artisan())::output()));
2020-01-03 18:20:13 +00:00
}
}
```
<br>
2020-01-03 18:20:13 +00:00
## AddMockPropertiesRector
Migrate PhpSpec behavior to PHPUnit test
- class: `Rector\PhpSpecToPHPUnit\Rector\Class_\AddMockPropertiesRector`
```diff
-
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
```
<br>
## AddNewServiceToSymfonyPhpConfigRector
2019-11-06 23:52:19 +00:00
Adds a new `$services->set(...)` call to PHP Config
2019-11-06 23:52:19 +00:00
- class: `Rector\RectorGenerator\Rector\Closure\AddNewServiceToSymfonyPhpConfigRector`
2019-11-06 23:52:19 +00:00
```diff
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-11-06 23:52:19 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
+ $services->set(AddNewServiceToSymfonyPhpConfigRector::class);
};
2019-11-06 23:52:19 +00:00
```
<br>
2019-11-06 23:52:19 +00:00
## AddNextrasDatePickerToDateControlRector
Nextras/Form upgrade of addDatePicker method call to DateControl assign
- class: `Rector\Nette\Rector\MethodCall\AddNextrasDatePickerToDateControlRector`
```diff
use Nette\Application\UI\Form;
class SomeClass
{
public function run()
{
$form = new Form();
- $form->addDatePicker('key', 'Label');
+ $form['key'] = new \Nextras\FormComponents\Controls\DateControl('Label');
}
}
```
<br>
## AddParamTypeDeclarationRector
Add param types where needed
:wrench: **configure it!**
- class: `Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use PHPStan\Type\StringType;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector;
use Rector\TypeDeclaration\ValueObject\AddParamTypeDeclaration;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-12-31 11:50:32 +00:00
$services->set(AddParamTypeDeclarationRector::class)
->call('configure', [[
AddParamTypeDeclarationRector::PARAMETER_TYPEHINTS => inline_value_objects([
new AddParamTypeDeclaration('SomeClass', 'process', 0, new StringType()),
]),
]]);
};
```
2018-12-31 11:50:32 +00:00
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
- public function process($name)
+ public function process(string $name)
{
}
}
2018-12-31 11:50:32 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
## AddParentBootToModelClassMethodRector
Add `parent::boot();` call to `boot()` class method in child of Illuminate\Database\Eloquent\Model
- class: `Rector\Laravel\Rector\ClassMethod\AddParentBootToModelClassMethodRector`
```diff
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function boot()
{
+ parent::boot();
}
}
```
<br>
## AddPregQuoteDelimiterRector
2020-01-15 20:40:44 +00:00
Add `preg_quote` delimiter when missing
2020-01-15 20:40:44 +00:00
- class: `Rector\CodeQuality\Rector\FuncCall\AddPregQuoteDelimiterRector`
2020-01-15 20:40:44 +00:00
```diff
-'#' . preg_quote('name') . '#';
+'#' . preg_quote('name', '#') . '#';
2020-01-15 20:40:44 +00:00
```
<br>
2020-01-15 20:40:44 +00:00
## AddPropertyByParentRector
2018-10-21 22:26:45 +00:00
Add dependency via constructor by parent class type
2018-10-21 22:26:45 +00:00
:wrench: **configure it!**
2018-10-21 22:26:45 +00:00
- class: `Rector\Generic\Rector\Class_\AddPropertyByParentRector`
2018-10-21 22:26:45 +00:00
```php
use Rector\Generic\Rector\Class_\AddPropertyByParentRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-07-27 08:16:16 +00:00
$services->set(AddPropertyByParentRector::class)
->call('configure', [[
AddPropertyByParentRector::PARENT_DEPENDENCIES => [
'SomeParentClass' => ['SomeDependency'],
],
]]);
};
```
2020-07-27 08:16:16 +00:00
2020-07-27 08:16:16 +00:00
```diff
final class SomeClass extends SomeParentClass
2020-07-27 08:16:16 +00:00
{
+ /**
+ * @var SomeDependency
+ */
+ private $someDependency;
+
+ public function __construct(SomeDependency $someDependency)
+ {
+ $this->someDependency = $someDependency;
+ }
2020-07-27 08:16:16 +00:00
}
```
<br>
2020-07-27 08:16:16 +00:00
## AddProphecyTraitRector
2019-05-01 23:56:58 +00:00
Add Prophecy trait for method using `$this->prophesize()`
2019-05-01 23:56:58 +00:00
- class: `Rector\PHPUnit\Rector\Class_\AddProphecyTraitRector`
2019-05-29 13:40:20 +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);
}
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
## AddRemovedDefaultValuesRector
2019-05-29 13:40:20 +00:00
Complete removed default values explicitly
2019-05-29 13:40:20 +00:00
- class: `Rector\PHPOffice\Rector\StaticCall\AddRemovedDefaultValuesRector`
```diff
final class SomeClass
{
public function run(): void
{
$logger = new \PHPExcel_CalcEngine_Logger;
- $logger->setWriteDebugLog();
+ $logger->setWriteDebugLog(false);
}
}
```
<br>
## AddRequestToHandleMethodCallRector
Add $_SERVER REQUEST_URI to method call
- class: `Rector\Phalcon\Rector\MethodCall\AddRequestToHandleMethodCallRector`
2019-05-01 23:56:58 +00:00
```diff
class SomeClass
{
public function run($di)
2019-05-01 23:56:58 +00:00
{
$application = new \Phalcon\Mvc\Application();
- $response = $application->handle();
+ $response = $application->handle($_SERVER["REQUEST_URI"]);
2019-05-01 23:56:58 +00:00
}
}
```
<br>
## AddReturnTypeDeclarationRector
2019-05-01 23:56:58 +00:00
Changes defined return typehint of method and class.
2019-05-19 08:27:38 +00:00
:wrench: **configure it!**
2019-05-19 08:27:38 +00:00
- class: `Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use PHPStan\Type\ArrayType;
use PHPStan\Type\MixedType;
use Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector;
use Rector\TypeDeclaration\ValueObject\AddReturnTypeDeclaration;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddReturnTypeDeclarationRector::class)
->call('configure', [[
AddReturnTypeDeclarationRector::METHOD_RETURN_TYPES => inline_value_objects([
new AddReturnTypeDeclaration('SomeClass', 'getData', new ArrayType(new MixedType(false, null), new MixedType(
false,
null
))),
]),
]]);
};
```
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
2019-05-19 08:27:38 +00:00
{
- public getData()
+ public getData(): array
2019-05-19 08:27:38 +00:00
{
}
}
```
<br>
2019-05-19 08:27:38 +00:00
## AddSeeTestAnnotationRector
2020-07-27 13:40:30 +00:00
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.
2020-07-27 13:40:30 +00:00
- class: `Rector\PHPUnit\Rector\Class_\AddSeeTestAnnotationRector`
2020-07-27 13:40:30 +00:00
```diff
+/**
+ * @see \SomeServiceTest
+ */
class SomeService
2020-07-27 13:40:30 +00:00
{
}
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
2020-07-27 13:40:30 +00:00
{
}
```
<br>
2020-07-27 13:40:30 +00:00
## AddTopIncludeRector
2020-01-04 17:49:26 +00:00
Adds an include file at the top of matching files, except class definitions
2020-01-04 17:49:26 +00:00
:wrench: **configure it!**
2020-01-04 17:49:26 +00:00
- class: `Rector\Legacy\Rector\FileWithoutNamespace\AddTopIncludeRector`
2020-01-04 17:49:26 +00:00
```php
use Rector\Legacy\Rector\FileWithoutNamespace\AddTopIncludeRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-01-04 17:49:26 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(AddTopIncludeRector::class)
->call('configure', [[
AddTopIncludeRector::AUTOLOAD_FILE_PATH => '/../autoloader.php',
AddTopIncludeRector::PATTERNS => [
'pat*/*/?ame.php',
'somepath/?ame.php',
],
]]);
};
```
```diff
+require_once __DIR__ . '/../autoloader.php';
+
if (isset($_POST['csrf'])) {
processPost($_POST);
2019-05-29 13:40:20 +00:00
}
```
<br>
2018-10-21 22:26:45 +00:00
## AddUuidAnnotationsToIdPropertyRector
2020-01-04 17:49:26 +00:00
Add uuid annotations to `$id` property
2020-01-04 17:49:26 +00:00
- class: `Rector\Doctrine\Rector\Property\AddUuidAnnotationsToIdPropertyRector`
2020-01-04 17:49:26 +00:00
```diff
use Doctrine\ORM\Attributes as ORM;
/**
* @ORM\Entity
*/
2020-01-04 17:49:26 +00:00
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-01-04 17:49:26 +00:00
}
```
<br>
2020-01-04 17:49:26 +00:00
## AddUuidMirrorForRelationPropertyRector
2018-10-21 22:26:45 +00:00
Adds `$uuid` property to entities, that already have `$id` with integer type.Require for step-by-step migration from int to uuid.
2018-10-21 22:26:45 +00:00
- class: `Rector\Doctrine\Rector\Class_\AddUuidMirrorForRelationPropertyRector`
2018-10-21 22:26:45 +00:00
```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;
}
2018-10-21 22:26:45 +00:00
```
<br>
## AddUuidToEntityWhereMissingRector
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
- class: `Rector\Doctrine\Rector\Class_\AddUuidToEntityWhereMissingRector`
```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;
}
```
<br>
## AlwaysInitializeUuidInEntityRector
2019-05-19 08:27:38 +00:00
Add uuid initializion to all entities that misses it
2019-05-19 08:27:38 +00:00
- class: `Rector\Doctrine\Rector\Class_\AlwaysInitializeUuidInEntityRector`
2019-05-19 08:27:38 +00:00
```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();
+ }
}
```
<br>
## AndAssignsToSeparateLinesRector
Split 2 assigns ands to separate line
- class: `Rector\CodeQuality\Rector\LogicalAnd\AndAssignsToSeparateLinesRector`
```diff
class SomeClass
{
public function run()
{
$tokens = [];
- $token = 4 and $tokens[] = $token;
+ $token = 4;
+ $tokens[] = $token;
}
}
```
<br>
## AnnotateThrowablesRector
2019-12-27 17:50:00 +00:00
Adds `@throws` DocBlock comments to methods that thrwo \Throwables.
2019-12-27 17:50:00 +00:00
- class: `Rector\CodingStyle\Rector\Throw_\AnnotateThrowablesRector`
2019-12-27 17:50:00 +00:00
```diff
class RootExceptionInMethodWithDocblock
2019-12-27 17:50:00 +00:00
{
/**
* This is a comment.
*
* @param int $code
+ * @throws \RuntimeException
*/
public function throwException(int $code)
2019-12-27 17:50:00 +00:00
{
throw new \RuntimeException('', $code);
2019-12-27 17:50:00 +00:00
}
}
```
<br>
2019-12-27 17:50:00 +00:00
## AnnotatedPropertyInjectToConstructorInjectionRector
2019-08-05 21:10:47 +00:00
Turns non-private properties with `@annotation` to private properties and constructor injection
2019-08-05 21:10:47 +00:00
- class: `Rector\Generic\Rector\Property\AnnotatedPropertyInjectToConstructorInjectionRector`
2019-08-05 21:10:47 +00:00
```diff
/**
* @var SomeService
- * @inject
*/
-public $someService;
+private $someService;
+
+public function __construct(SomeService $someService)
+{
+ $this->someService = $someService;
+}
2019-08-05 21:10:47 +00:00
```
<br>
2019-08-05 21:10:47 +00:00
## AnnotationToAttributeRector
Change annotation to attribute
- class: `Rector\Php80\Rector\Class_\AnnotationToAttributeRector`
```diff
use Doctrine\ORM\Attributes as ORM;
-/**
- * @ORM\Entity
- */
+#[ORM\Entity]
class SomeClass
{
}
```
<br>
## AppUsesStaticCallToUseStatementRector
Change `App::uses()` to use imports
- class: `Rector\CakePHP\Rector\Namespace_\AppUsesStaticCallToUseStatementRector`
```diff
-App::uses('NotificationListener', 'Event');
+use Event\NotificationListener;
CakeEventManager::instance()->attach(new NotificationListener());
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
## ArgumentAdderRector
2020-07-27 08:16:16 +00:00
This Rector adds new default arguments in calls of defined methods and class types.
2020-07-27 08:16:16 +00:00
:wrench: **configure it!**
2020-07-27 08:16:16 +00:00
- class: `Rector\Generic\Rector\ClassMethod\ArgumentAdderRector`
2020-07-27 08:16:16 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassMethod\ArgumentAdderRector;
use Rector\Generic\ValueObject\ArgumentAdder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-27 08:16:16 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentAdderRector::class)
->call('configure', [[
ArgumentAdderRector::ADDED_ARGUMENTS => inline_value_objects([
new ArgumentAdder('SomeExampleClass', 'someMethod', 0, 'someArgument', 'true', 'SomeType', null),
]),
]]);
};
```
```diff
$someObject = new SomeExampleClass;
-$someObject->someMethod();
+$someObject->someMethod(true);
```
<br>
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassMethod\ArgumentAdderRector;
use Rector\Generic\ValueObject\ArgumentAdder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentAdderRector::class)
->call('configure', [[
ArgumentAdderRector::ADDED_ARGUMENTS => inline_value_objects([
new ArgumentAdder('SomeExampleClass', 'someMethod', 0, 'someArgument', 'true', 'SomeType', null),
]),
]]);
};
```
```diff
class MyCustomClass extends SomeExampleClass
{
- public function someMethod()
+ public function someMethod($value = true)
{
}
}
```
<br>
## ArgumentDefaultValueReplacerRector
2019-08-05 21:10:47 +00:00
Replaces defined map of arguments in defined methods and their calls.
2019-08-05 21:10:47 +00:00
:wrench: **configure it!**
2019-08-05 21:10:47 +00:00
- class: `Rector\Generic\Rector\ClassMethod\ArgumentDefaultValueReplacerRector`
2019-08-05 21:10:47 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassMethod\ArgumentDefaultValueReplacerRector;
use Rector\Generic\ValueObject\ArgumentDefaultValueReplacer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-08-05 21:10:47 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentDefaultValueReplacerRector::class)
->call('configure', [[
ArgumentDefaultValueReplacerRector::REPLACED_ARGUMENTS => inline_value_objects([
new ArgumentDefaultValueReplacer('SomeExampleClass', 'someMethod', 0, 'SomeClass::OLD_CONSTANT', 'false'),
]),
]]);
};
2019-08-05 21:10:47 +00:00
```
2019-08-05 21:10:47 +00:00
```diff
$someObject = new SomeClass;
-$someObject->someMethod(SomeClass::OLD_CONSTANT);
+$someObject->someMethod(false);'
```
<br>
## ArgumentFuncCallToMethodCallRector
Move help facade-like function calls to constructor injection
:wrench: **configure it!**
- class: `Rector\Transform\Rector\FuncCall\ArgumentFuncCallToMethodCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\FuncCall\ArgumentFuncCallToMethodCallRector;
use Rector\Transform\ValueObject\ArgumentFuncCallToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-27 08:16:16 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-07-27 08:16:16 +00:00
$services->set(ArgumentFuncCallToMethodCallRector::class)
->call('configure', [[
ArgumentFuncCallToMethodCallRector::FUNCTIONS_TO_METHOD_CALLS => inline_value_objects([
new ArgumentFuncCallToMethodCall('view', 'Illuminate\Contracts\View\Factory', null, 'make'),
]),
]]);
};
```
2020-07-27 08:16:16 +00:00
```diff
class SomeController
2020-07-27 08:16:16 +00:00
{
+ /**
+ * @var \Illuminate\Contracts\View\Factory
+ */
+ private $viewFactory;
+
+ public function __construct(\Illuminate\Contracts\View\Factory $viewFactory)
+ {
+ $this->viewFactory = $viewFactory;
+ }
+
public function action()
2020-07-27 08:16:16 +00:00
{
- $template = view('template.blade');
- $viewFactory = view();
+ $template = $this->viewFactory->make('template.blade');
+ $viewFactory = $this->viewFactory;
2020-07-27 08:16:16 +00:00
}
}
```
<br>
2020-07-27 08:16:16 +00:00
## ArgumentRemoverRector
Removes defined arguments in defined methods and their calls.
:wrench: **configure it!**
- class: `Rector\Generic\Rector\ClassMethod\ArgumentRemoverRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassMethod\ArgumentRemoverRector;
use Rector\Generic\ValueObject\ArgumentRemover;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ArgumentRemoverRector::class)
->call('configure', [[
ArgumentRemoverRector::REMOVED_ARGUMENTS => inline_value_objects([
new ArgumentRemover('ExampleClass', 'someMethod', 0, 'true'),
]),
]]);
};
```
```diff
$someObject = new SomeClass;
-$someObject->someMethod(true);
+$someObject->someMethod();'
```
<br>
## ArrayAccessGetControlToGetComponentMethodCallRector
2018-12-31 11:50:32 +00:00
Change magic arrays access get, to explicit `$this->getComponent(...)` method
2018-12-31 11:50:32 +00:00
- class: `Rector\NetteCodeQuality\Rector\Assign\ArrayAccessGetControlToGetComponentMethodCallRector`
2018-12-31 11:50:32 +00:00
```diff
use Nette\Application\UI\Presenter;
class SomeClass extends Presenter
2018-12-31 11:50:32 +00:00
{
public function some()
2019-05-29 13:40:20 +00:00
{
- $someControl = $this['whatever'];
+ $someControl = $this->getComponent('whatever');
2018-12-31 11:50:32 +00:00
}
}
```
<br>
2018-12-31 11:50:32 +00:00
## ArrayAccessSetControlToAddComponentMethodCallRector
2018-10-21 22:26:45 +00:00
Change magic arrays access set, to explicit `$this->setComponent(...)` method
2018-10-21 22:26:45 +00:00
- class: `Rector\NetteCodeQuality\Rector\Assign\ArrayAccessSetControlToAddComponentMethodCallRector`
2018-10-21 22:26:45 +00:00
```diff
use Nette\Application\UI\Control;
use Nette\Application\UI\Presenter;
class SomeClass extends Presenter
{
public function some()
{
$someControl = new Control();
- $this['whatever'] = $someControl;
+ $this->addComponent($someControl, 'whatever');
}
}
```
<br>
## ArrayArgumentInTestToDataProviderRector
Move array argument from tests into data provider [configurable]
:wrench: **configure it!**
- class: `Rector\PHPUnit\Rector\Class_\ArrayArgumentInTestToDataProviderRector`
2018-10-21 22:26:45 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\PHPUnit\Rector\Class_\ArrayArgumentInTestToDataProviderRector;
use Rector\PHPUnit\ValueObject\ArrayArgumentToDataProvider;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2018-10-21 22:26:45 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-03-31 12:25:39 +00:00
$services->set(ArrayArgumentInTestToDataProviderRector::class)
->call('configure', [[
ArrayArgumentInTestToDataProviderRector::ARRAY_ARGUMENTS_TO_DATA_PROVIDERS => inline_value_objects([
new ArrayArgumentToDataProvider('PHPUnit\Framework\TestCase', 'doTestMultiple', 'doTestSingle', 'number'),
]),
]]);
};
```
2019-03-31 12:25:39 +00:00
2019-03-31 12:25:39 +00:00
```diff
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
2019-03-31 12:25:39 +00:00
{
- public function test()
+ /**
+ * @dataProvider provideData()
+ */
+ public function test(int $number)
2019-03-31 12:25:39 +00:00
{
- $this->doTestMultiple([1, 2, 3]);
+ $this->doTestSingle($number);
+ }
+
+ public function provideData(): \Iterator
+ {
+ yield [1];
+ yield [2];
+ yield [3];
2019-03-31 12:25:39 +00:00
}
}
```
<br>
2019-03-31 12:25:39 +00:00
## ArrayKeyExistsOnPropertyRector
Change `array_key_exists()` on property to `property_exists()`
- class: `Rector\Php74\Rector\FuncCall\ArrayKeyExistsOnPropertyRector`
2018-10-21 22:26:45 +00:00
```diff
class SomeClass
{
public $value;
}
$someClass = new SomeClass;
-array_key_exists('value', $someClass);
+property_exists($someClass, 'value');
2018-10-21 22:26:45 +00:00
```
<br>
2018-10-21 22:26:45 +00:00
## ArrayKeyExistsTernaryThenValueToCoalescingRector
2019-02-18 15:51:24 +00:00
Change `array_key_exists()` ternary to coalesing
2019-02-18 15:51:24 +00:00
- class: `Rector\CodeQuality\Rector\Ternary\ArrayKeyExistsTernaryThenValueToCoalescingRector`
2019-02-18 15:51:24 +00:00
```diff
class SomeClass
{
public function run($values, $keyToMatch)
{
- $result = array_key_exists($keyToMatch, $values) ? $values[$keyToMatch] : null;
+ $result = $values[$keyToMatch] ?? null;
}
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
## ArrayKeyFirstLastRector
2019-05-29 13:40:20 +00:00
Make use of `array_key_first()` and `array_key_last()`
2019-05-29 13:40:20 +00:00
- class: `Rector\Php73\Rector\FuncCall\ArrayKeyFirstLastRector`
2019-05-29 13:40:20 +00:00
```diff
-reset($items);
-$firstKey = key($items);
+$firstKey = array_key_first($items);
2019-02-18 15:51:24 +00:00
```
<br>
```diff
-end($items);
-$lastKey = key($items);
+$lastKey = array_key_last($items);
```
<br>
## ArrayKeysAndInArrayToArrayKeyExistsRector
Replace `array_keys()` and `in_array()` to `array_key_exists()`
- class: `Rector\CodeQuality\Rector\FuncCall\ArrayKeysAndInArrayToArrayKeyExistsRector`
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
public function run($packageName, $values)
2018-12-31 11:50:32 +00:00
{
- $keys = array_keys($values);
- return in_array($packageName, $keys, true);
+ return array_key_exists($packageName, $values);
2018-12-31 11:50:32 +00:00
}
}
```
<br>
2018-12-31 11:50:32 +00:00
## ArrayMergeOfNonArraysToSimpleArrayRector
2018-10-21 22:26:45 +00:00
Change `array_merge` of non arrays to array directly
- class: `Rector\CodeQuality\Rector\FuncCall\ArrayMergeOfNonArraysToSimpleArrayRector`
2018-10-21 22:26:45 +00:00
```diff
class SomeClass
{
public function go()
{
$value = 5;
$value2 = 10;
- return array_merge([$value], [$value2]);
+ return [$value, $value2];
}
}
2018-10-21 22:26:45 +00:00
```
<br>
2018-10-23 18:58:57 +00:00
## ArraySpreadInsteadOfArrayMergeRector
2019-02-18 15:51:24 +00:00
Change `array_merge()` to spread operator, except values with possible string `key` values
2019-02-18 15:51:24 +00:00
- class: `Rector\Php74\Rector\FuncCall\ArraySpreadInsteadOfArrayMergeRector`
2019-02-18 15:51:24 +00:00
```diff
class SomeClass
{
public function run($iter1, $iter2)
{
- $values = array_merge(iterator_to_array($iter1), iterator_to_array($iter2));
+ $values = [...$iter1, ...$iter2];
// Or to generalize to all iterables
- $anotherValues = array_merge(
- is_array($iter1) ? $iter1 : iterator_to_array($iter1),
- is_array($iter2) ? $iter2 : iterator_to_array($iter2)
- );
+ $anotherValues = [...$iter1, ...$iter2];
}
}
2019-02-18 15:51:24 +00:00
```
<br>
2019-02-18 15:51:24 +00:00
## ArrayThisCallToThisMethodCallRector
2019-01-22 20:34:38 +00:00
Change `[$this, someMethod]` without any args to `$this->someMethod()`
2019-01-22 20:34:38 +00:00
- class: `Rector\CodeQuality\Rector\Array_\ArrayThisCallToThisMethodCallRector`
2019-01-22 20:34:38 +00:00
```diff
class SomeClass
{
public function run()
{
- $values = [$this, 'giveMeMore'];
+ $values = $this->giveMeMore();
}
public function giveMeMore()
{
return 'more';
}
}
2019-01-22 20:34:38 +00:00
```
<br>
2019-01-22 20:34:38 +00:00
## ArrayToFluentCallRector
2019-05-19 08:27:38 +00:00
Moves array options to fluent setter method calls.
2019-05-29 13:40:20 +00:00
:wrench: **configure it!**
2019-05-29 13:40:20 +00:00
- class: `Rector\CakePHP\Rector\MethodCall\ArrayToFluentCallRector`
2019-05-29 13:40:20 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\CakePHP\Rector\MethodCall\ArrayToFluentCallRector;
use Rector\CakePHP\ValueObject\ArrayToFluentCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-05-29 13:40:20 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-29 13:40:20 +00:00
$services->set(ArrayToFluentCallRector::class)
->call('configure', [[
ArrayToFluentCallRector::ARRAYS_TO_FLUENT_CALLS => inline_value_objects([
new ArrayToFluentCall('ArticlesTable', ['setForeignKey', 'setProperty']), ]
),
]]);
};
```
2019-05-29 13:40:20 +00:00
2019-05-19 08:27:38 +00:00
```diff
use Cake\ORM\Table;
final class ArticlesTable extends Table
2019-05-19 08:27:38 +00:00
{
public function initialize(array $config)
2019-05-19 08:27:38 +00:00
{
- $this->belongsTo('Authors', [
- 'foreignKey' => 'author_id',
- 'propertyName' => 'person'
- ]);
+ $this->belongsTo('Authors')
+ ->setForeignKey('author_id')
+ ->setProperty('person');
2019-05-19 08:27:38 +00:00
}
}
```
<br>
2019-05-19 08:27:38 +00:00
## ArrowFunctionToAnonymousFunctionRector
Replace arrow functions with anonymous functions
- class: `Rector\DowngradePhp74\Rector\ArrowFunction\ArrowFunctionToAnonymousFunctionRector`
```diff
class SomeClass
{
public function run()
{
$delimiter = ",";
- $callable = fn($matches) => $delimiter . strtolower($matches[1]);
+ $callable = function ($matches) use ($delimiter) {
+ return $delimiter . strtolower($matches[1]);
+ };
}
}
2019-05-29 13:40:20 +00:00
```
<br>
## AssertCompareToSpecificMethodRector
Turns vague php-only method in PHPUnit TestCase to more specific
- class: `Rector\PHPUnit\Rector\MethodCall\AssertCompareToSpecificMethodRector`
```diff
-$this->assertSame(10, count($anything), "message");
+$this->assertCount(10, $anything, "message");
```
<br>
2018-10-23 18:58:57 +00:00
```diff
-$this->assertNotEquals(get_class($value), stdClass::class);
+$this->assertNotInstanceOf(stdClass::class, $value);
2018-10-23 18:58:57 +00:00
```
<br>
2018-10-21 22:26:45 +00:00
## AssertComparisonToSpecificMethodRector
2019-05-01 23:56:58 +00:00
Turns comparison operations to their method name alternatives in PHPUnit TestCase
2019-05-01 23:56:58 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\AssertComparisonToSpecificMethodRector`
2019-05-01 23:56:58 +00:00
```diff
-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
2019-05-01 23:56:58 +00:00
```
<br>
```diff
-$this->assertFalse($foo >= $bar, "message");
+$this->assertLessThanOrEqual($bar, $foo, "message");
```
<br>
## AssertEqualsParameterToSpecificMethodsTypeRector
2019-08-05 21:10:47 +00:00
Change `assertEquals()/assertNotEquals()` method parameters to new specific alternatives
2019-08-05 21:10:47 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\AssertEqualsParameterToSpecificMethodsTypeRector`
2019-08-05 21:10:47 +00:00
```diff
final class SomeTest extends \PHPUnit\Framework\TestCase
2019-08-05 21:10:47 +00:00
{
public function test()
2019-08-05 21:10:47 +00:00
{
$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-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
## AssertEqualsToSameRector
2019-08-05 21:10:47 +00:00
Turns `assertEquals()` into stricter `assertSame()` for scalar values in PHPUnit TestCase
2019-08-05 21:10:47 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\AssertEqualsToSameRector`
2019-08-05 21:10:47 +00:00
```diff
-$this->assertEquals(2, $result, "message");
+$this->assertSame(2, $result, "message");
2019-08-05 21:10:47 +00:00
```
<br>
2018-12-25 19:55:16 +00:00
```diff
-$this->assertEquals($aString, $result, "message");
+$this->assertSame($aString, $result, "message");
```
<br>
## AssertFalseStrposToContainsRector
Turns `strpos`/`stripos` comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertFalseStrposToContainsRector`
```diff
-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
```
<br>
```diff
-$this->assertNotFalse(stripos($anything, "foo"), "message");
+$this->assertContains("foo", $anything, "message");
```
<br>
## AssertInstanceOfComparisonRector
Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertInstanceOfComparisonRector`
```diff
-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertInstanceOf("Foo", $foo, "message");
```
<br>
```diff
-$this->assertFalse($foo instanceof Foo, "message");
+$this->assertNotInstanceOf("Foo", $foo, "message");
```
<br>
2019-05-26 19:26:33 +00:00
## AssertIssetToSpecificMethodRector
2019-05-26 19:26:33 +00:00
Turns isset comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertIssetToSpecificMethodRector`
2019-05-26 19:26:33 +00:00
```diff
-$this->assertTrue(isset($anything->foo));
+$this->assertObjectHasAttribute("foo", $anything);
```
2019-05-29 13:40:20 +00:00
<br>
```diff
-$this->assertFalse(isset($anything["foo"]), "message");
+$this->assertArrayNotHasKey("foo", $anything, "message");
2019-05-26 19:26:33 +00:00
```
<br>
2019-05-26 19:26:33 +00:00
## AssertNotOperatorRector
Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertNotOperatorRector`
```diff
-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
```
<br>
```diff
-$this->assertFalse(!$foo, "message");
+$this->assertTrue($foo, "message");
```
<br>
## AssertPropertyExistsRector
Turns `property_exists` comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertPropertyExistsRector`
```diff
-$this->assertTrue(property_exists(new Class, "property"), "message");
+$this->assertClassHasAttribute("property", "Class", "message");
```
<br>
```diff
-$this->assertFalse(property_exists(new Class, "property"), "message");
+$this->assertClassNotHasAttribute("property", "Class", "message");
```
<br>
## AssertRegExpRector
Turns `preg_match` comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertRegExpRector`
```diff
-$this->assertSame(1, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertRegExp("/^Message for ".*"\.$/", $string, $message);
```
<br>
```diff
-$this->assertEquals(false, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertNotRegExp("/^Message for ".*"\.$/", $string, $message);
```
<br>
## AssertResourceToClosedResourceRector
Turns `assertIsNotResource()` into stricter `assertIsClosedResource()` for resource values in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertResourceToClosedResourceRector`
```diff
-$this->assertIsNotResource($aResource, "message");
+$this->assertIsClosedResource($aResource, "message");
```
<br>
## AssertSameBoolNullToSpecificMethodRector
Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertSameBoolNullToSpecificMethodRector`
```diff
-$this->assertSame(null, $anything);
+$this->assertNull($anything);
```
<br>
```diff
-$this->assertNotSame(false, $anything);
+$this->assertNotFalse($anything);
```
<br>
## AssertSameTrueFalseToAssertTrueFalseRector
Change `$this->assertSame(true,` ...) to `assertTrue()`
- class: `Rector\PHPUnit\Rector\MethodCall\AssertSameTrueFalseToAssertTrueFalseRector`
```diff
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
public function test()
{
$value = (bool) mt_rand(0, 1);
- $this->assertSame(true, $value);
+ $this->assertTrue($value);
}
}
```
<br>
## AssertTrueFalseInternalTypeToSpecificMethodRector
Turns true/false with internal type comparisons to their method name alternatives in PHPUnit TestCase
- class: `Rector\PHPUnit\Rector\MethodCall\AssertTrueFalseInternalTypeToSpecificMethodRector`
```diff
-$this->assertTrue(is_{internal_type}($anything), "message");
+$this->assertInternalType({internal_type}, $anything, "message");
```
<br>
```diff
-$this->assertFalse(is_{internal_type}($anything), "message");
+$this->assertNotInternalType({internal_type}, $anything, "message");
```
<br>
## AssertTrueFalseToSpecificMethodRector
2019-08-05 21:10:47 +00:00
Turns true/false comparisons to their method name alternatives in PHPUnit TestCase when possible
2019-08-05 21:10:47 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\AssertTrueFalseToSpecificMethodRector`
2019-08-05 21:10:47 +00:00
```diff
-$this->assertTrue(is_readable($readmeFile), "message");
+$this->assertIsReadable($readmeFile, "message");
2019-08-05 21:10:47 +00:00
```
<br>
2019-08-05 21:10:47 +00:00
## AssignArrayToStringRector
2019-05-01 23:56:58 +00:00
String cannot be turned into array by assignment anymore
2019-05-01 23:56:58 +00:00
- class: `Rector\Php71\Rector\Assign\AssignArrayToStringRector`
2019-05-01 23:56:58 +00:00
```diff
-$string = '';
+$string = [];
$string[] = 1;
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
## AutoInPhpSymfonyConfigRector
2019-10-15 14:46:31 +00:00
Make sure there is `public(),` `autowire(),` `autoconfigure()` calls on `defaults()` in Symfony configs
2019-10-15 14:46:31 +00:00
- class: `Rector\SymfonyPhpConfig\Rector\MethodCall\AutoInPhpSymfonyConfigRector`
2019-10-15 14:46:31 +00:00
```diff
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->defaults()
- ->autowire();
+ ->autowire()
+ ->public()
+ ->autoconfigure();
};
```
<br>
## AutoWireWithClassNameSuffixForMethodWithRequiredAnnotationRector
Use autowire + class name suffix for method with `@required` annotation
- class: `Rector\Symfony\Rector\ClassMethod\AutoWireWithClassNameSuffixForMethodWithRequiredAnnotationRector`
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
{
/** @required */
- public function foo()
+ public function autowireSomeClass()
2019-10-15 14:46:31 +00:00
{
}
}
```
<br>
## BarewordStringRector
Changes unquoted non-existing constants to strings
- class: `Rector\Php72\Rector\ConstFetch\BarewordStringRector`
```diff
-var_dump(VAR);
+var_dump("VAR");
```
<br>
## BinaryOpBetweenNumberAndStringRector
Change binary operation between some number + string to PHP 7.1 compatible version
- class: `Rector\Php71\Rector\BinaryOp\BinaryOpBetweenNumberAndStringRector`
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
{
public function run()
{
- $value = 5 + '';
- $value = 5.0 + 'hi';
+ $value = 5 + 0;
+ $value = 5.0 + 0
2019-10-15 14:46:31 +00:00
}
}
```
<br>
2019-10-15 14:46:31 +00:00
## BinarySwitchToIfElseRector
Changes switch with 2 options to if-else
- class: `Rector\CodingStyle\Rector\Switch_\BinarySwitchToIfElseRector`
```diff
-switch ($foo) {
- case 'my string':
- $result = 'ok';
- break;
-
- default:
- $result = 'not ok';
+if ($foo == 'my string') {
+ $result = 'ok;
+} else {
+ $result = 'not ok';
}
```
<br>
## BlameableBehaviorRector
Change Blameable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
- class: `Rector\DoctrineGedmoToKnplabs\Rector\Class_\BlameableBehaviorRector`
```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;
}
```
<br>
## BooleanNotIdenticalToNotIdenticalRector
2019-08-05 21:10:47 +00:00
Negated identical boolean compare to not identical compare (does not apply to non-bool values)
2019-08-05 21:10:47 +00:00
- class: `Rector\CodeQuality\Rector\Identical\BooleanNotIdenticalToNotIdenticalRector`
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
2019-08-05 21:10:47 +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-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
## BreakNotInLoopOrSwitchToReturnRector
2019-08-05 21:10:47 +00:00
Convert break outside for/foreach/switch context to return
2019-08-05 21:10:47 +00:00
- class: `Rector\Php70\Rector\Break_\BreakNotInLoopOrSwitchToReturnRector`
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
2019-08-05 21:10:47 +00:00
{
public function run()
{
if ($isphp5)
return 1;
else
return 2;
- break;
+ return;
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
## BuilderExpandToHelperExpandRector
Change `containerBuilder->expand()` to static call with parameters
- class: `Rector\Nette\Rector\MethodCall\BuilderExpandToHelperExpandRector`
```diff
use Nette\DI\CompilerExtension;
final class SomeClass extends CompilerExtension
{
public function loadConfiguration()
{
- $value = $this->getContainerBuilder()->expand('%value');
+ $value = \Nette\DI\Helpers::expand('%value', $this->getContainerBuilder()->parameters);
}
}
```
<br>
2020-07-24 11:46:57 +00:00
## CallUserFuncCallToVariadicRector
Replace call_user_func_call with variadic
2019-09-25 08:49:53 +00:00
- class: `Rector\CodingStyle\Rector\FuncCall\CallUserFuncCallToVariadicRector`
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
2019-09-25 08:49:53 +00:00
{
public function run()
{
- call_user_func_array('some_function', $items);
+ some_function(...$items);
2019-09-25 08:49:53 +00:00
}
}
```
<br>
2019-09-25 08:49:53 +00:00
## CallUserMethodRector
Changes `call_user_method()/call_user_method_array()` to `call_user_func()/call_user_func_array()`
- class: `Rector\Php70\Rector\FuncCall\CallUserMethodRector`
```diff
-call_user_method($method, $obj, "arg1", "arg2");
+call_user_func(array(&$obj, "method"), "arg1", "arg2");
```
<br>
## CallableThisArrayToAnonymousFunctionRector
Convert [$this, "method"] to proper anonymous function
- class: `Rector\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector`
```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;
}
}
```
<br>
## CamelCaseFunctionNamingToUnderscoreRector
Change CamelCase naming of functions to under_score naming
- class: `Rector\CodingStyle\Rector\Function_\CamelCaseFunctionNamingToUnderscoreRector`
```diff
-function someCamelCaseFunction()
+function some_camel_case_function()
{
}
-someCamelCaseFunction();
+some_camel_case_function();
```
<br>
## CascadeValidationFormBuilderRector
Change "cascade_validation" option to specific node attribute
- class: `Rector\Symfony\Rector\MethodCall\CascadeValidationFormBuilderRector`
```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();
}
2020-07-24 11:46:57 +00:00
protected function createFormBuilder()
{
return new FormBuilder();
}
}
```
<br>
2020-07-24 11:46:57 +00:00
## CatchExceptionNameMatchingTypeRector
Type and name of catch exception should match
- class: `Rector\CodingStyle\Rector\Catch_\CatchExceptionNameMatchingTypeRector`
```diff
class SomeClass
{
public function run()
{
try {
// ...
- } catch (SomeException $typoException) {
- $typoException->getMessage();
+ } catch (SomeException $someException) {
+ $someException->getMessage();
}
}
}
```
<br>
## CellStaticToCoordinateRector
2019-05-29 13:40:20 +00:00
Methods to manipulate coordinates that used to exists in PHPExcel_Cell to PhpOffice\PhpSpreadsheet\Cell\Coordinate
2019-05-29 13:40:20 +00:00
- class: `Rector\PHPOffice\Rector\StaticCall\CellStaticToCoordinateRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
- \PHPExcel_Cell::stringFromColumnIndex();
+ \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex();
2019-05-29 13:40:20 +00:00
}
}
```
<br>
2019-05-29 13:40:20 +00:00
## ChangeAndIfToEarlyReturnRector
2019-05-01 23:56:58 +00:00
Changes if && to early return
2019-05-01 23:56:58 +00:00
- class: `Rector\SOLID\Rector\If_\ChangeAndIfToEarlyReturnRector`
2019-05-01 23:56:58 +00:00
```diff
class SomeClass
{
public function canDrive(Car $car)
{
- if ($car->hasWheels && $car->hasFuel) {
- return true;
+ if (!$car->hasWheels) {
+ return false;
}
- return false;
+ if (!$car->hasFuel) {
+ return false;
+ }
2019-05-01 23:56:58 +00:00
+
+ return true;
}
2019-05-01 23:56:58 +00:00
}
```
<br>
2019-05-01 23:56:58 +00:00
## ChangeArrayPushToArrayAssignRector
Change `array_push()` to direct variable assign
- class: `Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector`
```diff
class SomeClass
{
public function run()
{
$items = [];
- array_push($items, $item);
+ $items[] = $item;
}
}
```
<br>
## ChangeBigIntEntityPropertyToIntTypeRector
Change database type "bigint" for @var/type declaration to string
- class: `Rector\DoctrineCodeQuality\Rector\Property\ChangeBigIntEntityPropertyToIntTypeRector`
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class SomeEntity
{
/**
- * @var int|null
+ * @var string|null
* @ORM\Column(type="bigint", nullable=true)
*/
private $bigNumber;
}
```
<br>
## ChangeCarbonSingularMethodCallToPluralRector
Change setter methods with args to their plural names on Carbon\Carbon
- class: `Rector\Carbon\Rector\MethodCall\ChangeCarbonSingularMethodCallToPluralRector`
```diff
use Carbon\Carbon;
2018-10-21 22:26:45 +00:00
final class SomeClass
{
public function run(Carbon $carbon, $value): void
{
- $carbon->addMinute($value);
+ $carbon->addMinutes($value);
}
}
```
<br>
## ChangeChartRendererRector
Change chart renderer
- class: `Rector\PHPOffice\Rector\StaticCall\ChangeChartRendererRector`
```diff
final class SomeClass
{
public function run(): void
{
- \PHPExcel_Settings::setChartRenderer($rendererName, $rendererLibraryPath);
+ \PHPExcel_Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class);
}
}
```
<br>
## ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector
Rename `type` option to `entry_type` in CollectionType
- class: `Rector\Symfony\Rector\MethodCall\ChangeCollectionTypeOptionNameFromTypeToEntryTypeRector`
```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>
## ChangeCollectionTypeOptionTypeFromStringToClassReferenceRector
Change type in CollectionType from alias string to class reference
- class: `Rector\Symfony\Rector\MethodCall\ChangeCollectionTypeOptionTypeFromStringToClassReferenceRector`
```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>
## ChangeConditionalGetConditionRector
Change argument `PHPExcel_Style_Conditional->getCondition()` to `getConditions()`
- class: `Rector\PHPOffice\Rector\MethodCall\ChangeConditionalGetConditionRector`
```diff
final class SomeClass
{
public function run(): void
{
$conditional = new \PHPExcel_Style_Conditional;
- $someCondition = $conditional->getCondition();
+ $someCondition = $conditional->getConditions()[0] ?? '';
}
}
2018-10-21 22:26:45 +00:00
```
<br>
2018-10-21 22:26:45 +00:00
## ChangeConditionalReturnedCellRector
2019-10-15 14:46:31 +00:00
Change conditional call to `getCell()`
2019-10-15 14:46:31 +00:00
- class: `Rector\PHPOffice\Rector\MethodCall\ChangeConditionalReturnedCellRector`
2019-10-15 14:46:31 +00:00
```diff
final class SomeClass
2019-10-15 14:46:31 +00:00
{
public function run(): void
2019-10-15 14:46:31 +00:00
{
$worksheet = new \PHPExcel_Worksheet();
- $cell = $worksheet->setCellValue('A1', 'value', true);
+ $cell = $worksheet->getCell('A1')->setValue('value');
2019-10-15 14:46:31 +00:00
}
}
```
<br>
2019-10-15 14:46:31 +00:00
## ChangeConditionalSetConditionRector
Change argument `PHPExcel_Style_Conditional->setCondition()` to `setConditions()`
- class: `Rector\PHPOffice\Rector\MethodCall\ChangeConditionalSetConditionRector`
```diff
final class SomeClass
{
public function run(): void
{
$conditional = new \PHPExcel_Style_Conditional;
- $someCondition = $conditional->setCondition(1);
+ $someCondition = $conditional->setConditions((array) 1);
}
}
```
<br>
## ChangeConstantVisibilityRector
Change visibility of constant from parent class.
2019-05-29 13:40:20 +00:00
:wrench: **configure it!**
2020-07-24 11:46:57 +00:00
- class: `Rector\Generic\Rector\ClassConst\ChangeConstantVisibilityRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassConst\ChangeConstantVisibilityRector;
use Rector\Generic\ValueObject\ClassConstantVisibilityChange;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(ChangeConstantVisibilityRector::class)
->call('configure', [[
ChangeConstantVisibilityRector::CLASS_CONSTANT_VISIBILITY_CHANGES => inline_value_objects([
new ClassConstantVisibilityChange('ParentObject', 'SOME_CONSTANT', 'protected'),
]),
]]);
2020-07-24 11:46:57 +00:00
};
2019-05-29 13:40:20 +00:00
```
```diff
class FrameworkClass
2019-05-29 13:40:20 +00:00
{
protected const SOME_CONSTANT = 1;
2019-05-29 13:40:20 +00:00
}
class MyClass extends FrameworkClass
{
- public const SOME_CONSTANT = 1;
+ protected const SOME_CONSTANT = 1;
}
```
<br>
## ChangeContractMethodSingleToManyRector
Change method that returns single value to multiple values
:wrench: **configure it!**
- class: `Rector\Generic\Rector\ClassMethod\ChangeContractMethodSingleToManyRector`
```php
use Rector\Generic\Rector\ClassMethod\ChangeContractMethodSingleToManyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-29 13:40:20 +00:00
$services->set(ChangeContractMethodSingleToManyRector::class)
->call('configure', [[
ChangeContractMethodSingleToManyRector::OLD_TO_NEW_METHOD_BY_TYPE => [
'SomeClass' => [
'getNode' => 'getNodes',
],
],
]]);
};
```
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
- public function getNode(): string
+ /**
+ * @return string[]
+ */
+ public function getNodes(): array
2019-05-29 13:40:20 +00:00
{
- return 'Echo_';
+ return ['Echo_'];
2019-05-29 13:40:20 +00:00
}
}
```
<br>
## ChangeControlArrayAccessToAnnotatedControlVariableRector
Change magic `$this["some_component"]` to variable assign with `@var` annotation
- class: `Rector\NetteCodeQuality\Rector\ArrayDimFetch\ChangeControlArrayAccessToAnnotatedControlVariableRector`
```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>
## ChangeDataTypeForValueRector
Change argument `DataType::dataTypeForValue()` to DefaultValueBinder
- class: `Rector\PHPOffice\Rector\StaticCall\ChangeDataTypeForValueRector`
```diff
final class SomeClass
{
public function run(): void
{
- $type = \PHPExcel_Cell_DataType::dataTypeForValue('value');
+ $type = \PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder::dataTypeForValue('value');
}
}
```
<br>
## ChangeDiffForHumansArgsRector
2019-06-06 13:01:53 +00:00
Change methods arguments of `diffForHumans()` on Carbon\Carbon
2019-06-06 13:01:53 +00:00
- class: `Rector\Carbon\Rector\MethodCall\ChangeDiffForHumansArgsRector`
2019-06-06 13:01:53 +00:00
```diff
use Carbon\Carbon;
final class SomeClass
2019-06-06 13:01:53 +00:00
{
public function run(Carbon $carbon): void
2019-06-06 13:01:53 +00:00
{
- $carbon->diffForHumans(null, true);
+ $carbon->diffForHumans(null, \Carbon\CarbonInterface::DIFF_ABSOLUTE);
- $carbon->diffForHumans(null, false);
+ $carbon->diffForHumans(null, \Carbon\CarbonInterface::DIFF_RELATIVE_AUTO);
2019-06-06 13:01:53 +00:00
}
}
```
<br>
2019-06-06 13:01:53 +00:00
## ChangeDuplicateStyleArrayToApplyFromArrayRector
Change method call `duplicateStyleArray()` to `getStyle()` + `applyFromArray()`
- class: `Rector\PHPOffice\Rector\MethodCall\ChangeDuplicateStyleArrayToApplyFromArrayRector`
```diff
final class SomeClass
{
public function run(): void
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->duplicateStyleArray($styles, $range, $advanced);
+ $worksheet->getStyle($range)->applyFromArray($styles, $advanced);
}
}
```
<br>
2018-12-25 19:55:16 +00:00
## ChangeFileLoaderInExtensionAndKernelRector
2018-12-25 19:55:16 +00:00
Change XML loader to YAML in Bundle Extension
2018-12-25 19:55:16 +00:00
:wrench: **configure it!**
- class: `Rector\Symfony\Rector\Class_\ChangeFileLoaderInExtensionAndKernelRector`
2018-12-25 19:55:16 +00:00
```php
use Rector\Symfony\Rector\Class_\ChangeFileLoaderInExtensionAndKernelRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2018-12-25 19:55:16 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangeFileLoaderInExtensionAndKernelRector::class)
->call('configure', [[
ChangeFileLoaderInExtensionAndKernelRector::FROM => 'xml',
ChangeFileLoaderInExtensionAndKernelRector::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>
## ChangeFormArrayAccessToAnnotatedControlVariableRector
2018-12-25 19:55:16 +00:00
Change array access magic on `$form` to explicit standalone typed variable
2018-12-25 19:55:16 +00:00
- class: `Rector\NetteCodeQuality\Rector\ArrayDimFetch\ChangeFormArrayAccessToAnnotatedControlVariableRector`
2018-12-25 19:55:16 +00:00
```diff
use Nette\Application\UI\Form;
class SomePresenter
2018-12-25 19:55:16 +00:00
{
2019-05-29 13:40:20 +00:00
public function run()
{
$form = new Form();
$this->addText('email', 'Email');
2019-05-29 13:40:20 +00:00
- $form['email']->value = 'hey@hi.hello';
+ /** @var \Nette\Forms\Controls\TextInput $emailControl */
+ $emailControl = $form['email'];
+ $emailControl->value = 'hey@hi.hello';
2019-05-29 13:40:20 +00:00
}
2018-12-25 19:55:16 +00:00
}
```
<br>
2018-12-25 19:55:16 +00:00
## ChangeGetIdTypeToUuidRector
2018-12-31 11:50:32 +00:00
Change return type of `getId()` to uuid interface
2018-12-31 11:50:32 +00:00
- class: `Rector\Doctrine\Rector\ClassMethod\ChangeGetIdTypeToUuidRector`
2018-12-31 11:50:32 +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;
}
}
```
<br>
## ChangeGetUuidMethodCallToGetIdRector
Change `getUuid()` method call to `getId()`
- class: `Rector\Doctrine\Rector\MethodCall\ChangeGetUuidMethodCallToGetIdRector`
```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;
}
}
```
<br>
## ChangeGlobalVariablesToPropertiesRector
2019-03-09 13:24:30 +00:00
Change global `$variables` to private properties
2019-03-09 13:24:30 +00:00
- class: `Rector\PhpDeglobalize\Rector\ClassMethod\ChangeGlobalVariablesToPropertiesRector`
2019-03-09 13:24:30 +00:00
```diff
class SomeClass
{
+ private $variable;
public function go()
{
- global $variable;
- $variable = 5;
+ $this->variable = 5;
}
2019-02-21 14:36:16 +00:00
public function run()
2019-02-21 14:36:16 +00:00
{
- global $variable;
- var_dump($variable);
+ var_dump($this->variable);
2019-02-21 14:36:16 +00:00
}
}
```
<br>
2019-02-21 14:36:16 +00:00
## ChangeIOFactoryArgumentRector
Change argument of `PHPExcel_IOFactory::createReader(),` `PHPExcel_IOFactory::createWriter()` and `PHPExcel_IOFactory::identify()`
- class: `Rector\PHPOffice\Rector\StaticCall\ChangeIOFactoryArgumentRector`
```diff
final class SomeClass
{
public function run(): void
{
- $writer = \PHPExcel_IOFactory::createWriter('CSV');
+ $writer = \PHPExcel_IOFactory::createWriter('Csv');
}
}
```
<br>
## ChangeIdenticalUuidToEqualsMethodCallRector
2019-02-18 15:51:24 +00:00
Change `$uuid` === 1 to `$uuid->equals(\Ramsey\Uuid\Uuid::fromString(1))`
2019-02-18 15:51:24 +00:00
- class: `Rector\Doctrine\Rector\Identical\ChangeIdenticalUuidToEqualsMethodCallRector`
2019-02-18 15:51:24 +00:00
```diff
class SomeClass
{
public function match($checkedId): int
{
$building = new Building();
2019-05-19 08:27:38 +00:00
- return $building->getId() === $checkedId;
+ return $building->getId()->equals(\Ramsey\Uuid\Uuid::fromString($checkedId));
}
}
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
## ChangeIfElseValueAssignToEarlyReturnRector
2019-08-05 21:10:47 +00:00
Change if/else value to early return
2019-08-05 21:10:47 +00:00
- class: `Rector\SOLID\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector`
2019-08-05 21:10:47 +00:00
```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)];
2019-08-05 21:10:47 +00:00
}
-
- return $docToken;
+ return null;
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
## ChangeLocalPropertyToVariableRector
Change local property used in single method to local variable
- class: `Rector\Privatization\Rector\Class_\ChangeLocalPropertyToVariableRector`
```diff
class SomeClass
{
- private $count;
public function run()
{
- $this->count = 5;
- return $this->count;
+ $count = 5;
+ return $count;
}
}
```
<br>
## ChangeMethodVisibilityRector
Change visibility of method from parent class.
:wrench: **configure it!**
- class: `Rector\Generic\Rector\ClassMethod\ChangeMethodVisibilityRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassMethod\ChangeMethodVisibilityRector;
use Rector\Generic\ValueObject\ChangeMethodVisibility;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-03-31 12:25:39 +00:00
$services->set(ChangeMethodVisibilityRector::class)
->call('configure', [[
ChangeMethodVisibilityRector::METHOD_VISIBILITIES => inline_value_objects([
new ChangeMethodVisibility('FrameworkClass', 'someMethod', 'protected'),
]),
]]);
};
```
2019-03-31 12:25:39 +00:00
2019-03-31 12:25:39 +00:00
```diff
class FrameworkClass
{
protected someMethod()
{
}
}
class MyClass extends FrameworkClass
{
- public someMethod()
+ protected someMethod()
{
}
}
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
## ChangeNestedForeachIfsToEarlyContinueRector
Change nested ifs to foreach with continue
- class: `Rector\SOLID\Rector\Foreach_\ChangeNestedForeachIfsToEarlyContinueRector`
```diff
class SomeClass
{
public function run()
{
$items = [];
foreach ($values as $value) {
- if ($value === 5) {
- if ($value2 === 10) {
- $items[] = 'maybe';
- }
+ if ($value !== 5) {
+ continue;
}
+ if ($value2 !== 10) {
+ continue;
+ }
+
+ $items[] = 'maybe';
}
}
}
```
<br>
## ChangeNestedIfsToEarlyReturnRector
2019-08-24 11:08:59 +00:00
Change nested ifs to early return
2019-08-24 11:08:59 +00:00
- class: `Rector\SOLID\Rector\If_\ChangeNestedIfsToEarlyReturnRector`
2019-08-24 11:08:59 +00:00
```diff
class SomeClass
2019-08-24 11:08:59 +00:00
{
public function run()
{
- if ($value === 5) {
- if ($value2 === 10) {
- return 'yes';
- }
+ if ($value !== 5) {
+ return 'no';
+ }
+
+ if ($value2 === 10) {
+ return 'yes';
}
return 'no';
}
2019-08-24 11:08:59 +00:00
}
```
<br>
2019-08-24 11:08:59 +00:00
## ChangeNetteEventNamesInGetSubscribedEventsRector
2018-12-25 19:55:16 +00:00
Change EventSubscriber from Kdyby to Contributte
2018-12-25 19:55:16 +00:00
- class: `Rector\NetteKdyby\Rector\ClassMethod\ChangeNetteEventNamesInGetSubscribedEventsRector`
2018-12-25 19:55:16 +00:00
```diff
+use Contributte\Events\Extra\Event\Application\ShutdownEvent;
use Kdyby\Events\Subscriber;
use Nette\Application\Application;
-use Nette\Application\UI\Presenter;
class GetApplesSubscriber implements Subscriber
2018-12-25 19:55:16 +00:00
{
- public function getSubscribedEvents()
+ public static function getSubscribedEvents()
2019-05-29 13:40:20 +00:00
{
return [
- Application::class . '::onShutdown',
+ ShutdownEvent::class => 'onShutdown',
];
}
- public function onShutdown(Presenter $presenter)
+ public function onShutdown(ShutdownEvent $shutdownEvent)
{
+ $presenter = $shutdownEvent->getPresenter();
$presenterName = $presenter->getName();
// ...
2019-05-29 13:40:20 +00:00
}
2018-12-25 19:55:16 +00:00
}
```
<br>
2018-12-25 19:55:16 +00:00
## ChangePdfWriterRector
2018-12-25 19:55:16 +00:00
Change init of PDF writer
2018-12-25 19:55:16 +00:00
- class: `Rector\PHPOffice\Rector\StaticCall\ChangePdfWriterRector`
2018-12-25 19:55:16 +00:00
```diff
final class SomeClass
2019-05-29 13:40:20 +00:00
{
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);
}
2019-05-29 13:40:20 +00:00
}
2018-12-25 19:55:16 +00:00
```
<br>
2018-12-25 19:55:16 +00:00
## ChangePropertyVisibilityRector
2019-08-17 13:06:02 +00:00
Change visibility of property from parent class.
2019-08-17 13:06:02 +00:00
:wrench: **configure it!**
- class: `Rector\Generic\Rector\Property\ChangePropertyVisibilityRector`
```php
use Rector\Generic\Rector\Property\ChangePropertyVisibilityRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangePropertyVisibilityRector::class)
->call('configure', [[
ChangePropertyVisibilityRector::PROPERTY_TO_VISIBILITY_BY_CLASS => [
'FrameworkClass' => [
'someProperty' => 'protected',
],
],
]]);
};
```
2019-08-17 13:06:02 +00:00
```diff
class FrameworkClass
2019-08-17 13:06:02 +00:00
{
protected $someProperty;
2019-08-17 13:06:02 +00:00
}
class MyClass extends FrameworkClass
2019-08-17 13:06:02 +00:00
{
- public $someProperty;
+ protected $someProperty;
2019-08-17 13:06:02 +00:00
}
```
<br>
2019-08-17 13:06:02 +00:00
## ChangeQuerySetParametersMethodParameterFromArrayToArrayCollectionRector
Change array to ArrayCollection in setParameters method of query builder
- class: `Rector\DoctrineCodeQuality\Rector\MethodCall\ChangeQuerySetParametersMethodParameterFromArrayToArrayCollectionRector`
```diff
+use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;
+use Doctrine\ORM\Query\Parameter;
class SomeRepository extends EntityRepository
{
public function getSomething()
{
return $this
->createQueryBuilder('sm')
->select('sm')
->where('sm.foo = :bar')
- ->setParameters([
- 'bar' => 'baz'
- ])
+ ->setParameters(new ArrayCollection([
+ new Parameter('bar', 'baz'),
+ ]))
->getQuery()
->getResult()
;
}
}
```
<br>
## ChangeQueryWhereDateValueWithCarbonRector
Add `parent::boot();` call to `boot()` class method in child of Illuminate\Database\Eloquent\Model
- class: `Rector\Laravel\Rector\MethodCall\ChangeQueryWhereDateValueWithCarbonRector`
```diff
use Illuminate\Database\Query\Builder;
final class SomeClass
{
public function run(Builder $query)
{
- $query->whereDate('created_at', '<', Carbon::now());
+ $dateTime = Carbon::now();
+ $query->whereDate('created_at', '<=', $dateTime);
+ $query->whereTime('created_at', '<=', $dateTime);
}
}
```
<br>
## ChangeReadOnlyPropertyWithDefaultValueToConstantRector
Change property with read only status with default value to constant
- class: `Rector\SOLID\Rector\Property\ChangeReadOnlyPropertyWithDefaultValueToConstantRector`
```diff
class SomeClass
{
/**
* @var string[]
*/
- private $magicMethods = [
+ private const MAGIC_METHODS = [
'__toString',
'__wakeup',
];
public function run()
{
- foreach ($this->magicMethods as $magicMethod) {
+ foreach (self::MAGIC_METHODS as $magicMethod) {
echo $magicMethod;
}
}
}
```
<br>
## ChangeReadOnlyVariableWithDefaultValueToConstantRector
2020-01-04 23:18:57 +00:00
Change variable with read only status with default value to constant
2020-01-04 23:18:57 +00:00
- class: `Rector\SOLID\Rector\Class_\ChangeReadOnlyVariableWithDefaultValueToConstantRector`
2020-01-04 23:18:57 +00:00
```diff
class SomeClass
2020-01-04 23:18:57 +00:00
{
+ /**
+ * @var string[]
+ */
+ private const REPLACEMENTS = [
+ 'PHPUnit\Framework\TestCase\Notice' => 'expectNotice',
+ 'PHPUnit\Framework\TestCase\Deprecated' => 'expectDeprecation',
+ ];
+
public function run()
2020-01-04 23:18:57 +00:00
{
- $replacements = [
- 'PHPUnit\Framework\TestCase\Notice' => 'expectNotice',
- 'PHPUnit\Framework\TestCase\Deprecated' => 'expectDeprecation',
- ];
2020-01-04 23:18:57 +00:00
-
- foreach ($replacements as $class => $method) {
+ foreach (self::REPLACEMENTS as $class => $method) {
}
}
2020-01-04 23:18:57 +00:00
}
```
<br>
2020-01-04 23:18:57 +00:00
## ChangeReflectionTypeToStringToGetNameRector
2019-08-05 21:10:47 +00:00
Change string calls on ReflectionType
2019-08-05 21:10:47 +00:00
- class: `Rector\Php74\Rector\MethodCall\ChangeReflectionTypeToStringToGetNameRector`
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
2019-08-05 21:10:47 +00:00
{
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();
}
2019-08-05 21:10:47 +00:00
}
```
<br>
2019-08-05 21:10:47 +00:00
## ChangeReturnTypeOfClassMethodWithGetIdRector
2019-05-19 08:27:38 +00:00
Change `getUuid()` method call to `getId()`
2019-05-19 08:27:38 +00:00
- class: `Rector\Doctrine\Rector\ClassMethod\ChangeReturnTypeOfClassMethodWithGetIdRector`
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
{
- public function getBuildingId(): int
+ public function getBuildingId(): \Ramsey\Uuid\UuidInterface
{
$building = new Building();
return $building->getId();
}
2019-05-19 08:27:38 +00:00
}
```
<br>
2019-05-19 08:27:38 +00:00
## ChangeSearchLocationToRegisterReaderRector
Change argument `addSearchLocation()` to `registerReader()`
- class: `Rector\PHPOffice\Rector\StaticCall\ChangeSearchLocationToRegisterReaderRector`
```diff
final class SomeClass
{
public function run(): void
{
- \PHPExcel_IOFactory::addSearchLocation($type, $location, $classname);
+ \PhpOffice\PhpSpreadsheet\IOFactory::registerReader($type, $classname);
}
}
```
<br>
## ChangeServiceArgumentsToMethodCallRector
Change `$service->arg(...)` to `$service->call(...)`
:wrench: **configure it!**
- class: `Rector\SymfonyPhpConfig\Rector\MethodCall\ChangeServiceArgumentsToMethodCallRector`
```php
use Rector\SymfonyPhpConfig\Rector\MethodCall\ChangeServiceArgumentsToMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ChangeServiceArgumentsToMethodCallRector::class)
->call('configure', [[
ChangeServiceArgumentsToMethodCallRector::CLASS_TYPE_TO_METHOD_NAME => [
'SomeClass' => 'configure',
],
]]);
};
```
```diff
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SomeClass::class)
- ->arg('$key', 'value');
+ ->call('configure', [[
+ '$key' => 'value
+ ]]);
}
```
<br>
## ChangeSetIdToUuidValueRector
2019-02-21 14:36:16 +00:00
Change set id to uuid values
2019-02-21 14:36:16 +00:00
- class: `Rector\Doctrine\Rector\MethodCall\ChangeSetIdToUuidValueRector`
2019-02-21 14:36:16 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
2019-05-29 13:40:20 +00:00
class SomeClass
2019-02-21 14:36:16 +00:00
{
public function run()
2019-02-21 14:36:16 +00:00
{
$buildingFirst = new Building();
- $buildingFirst->setId(1);
- $buildingFirst->setUuid(Uuid::fromString('a3bfab84-e207-4ddd-b96d-488151de9e96'));
+ $buildingFirst->setId(Uuid::fromString('a3bfab84-e207-4ddd-b96d-488151de9e96'));
2019-02-21 14:36:16 +00:00
}
}
/**
* @ORM\Entity
*/
class Building
{
}
2019-02-21 14:36:16 +00:00
```
<br>
2019-02-21 14:36:16 +00:00
## ChangeSetIdTypeToUuidRector
2019-02-21 14:36:16 +00:00
Change param type of `setId()` to uuid interface
2019-02-21 14:36:16 +00:00
- class: `Rector\Doctrine\Rector\ClassMethod\ChangeSetIdTypeToUuidRector`
2019-02-21 14:36:16 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SetId
2019-02-21 14:36:16 +00:00
{
private $id;
- public function setId(int $uuid): int
+ public function setId(\Ramsey\Uuid\UuidInterface $uuid): int
2019-02-21 14:36:16 +00:00
{
return $this->id = $uuid;
2019-02-21 14:36:16 +00:00
}
}
```
<br>
2019-02-21 14:36:16 +00:00
## ChangeSingletonToServiceRector
2019-03-31 12:25:39 +00:00
Change singleton class to normal class that can be registered as a service
2019-03-31 12:25:39 +00:00
- class: `Rector\Legacy\Rector\Class_\ChangeSingletonToServiceRector`
2019-03-31 12:25:39 +00:00
```diff
class SomeClass
2019-03-31 12:25:39 +00:00
{
- private static $instance;
-
- private function __construct()
+ public function __construct()
{
- }
-
- public static function getInstance()
2019-05-29 13:40:20 +00:00
- {
- if (null === static::$instance) {
- static::$instance = new static();
- }
-
- return static::$instance;
}
2019-03-31 12:25:39 +00:00
}
```
<br>
2019-03-31 12:25:39 +00:00
## ChangeSnakedFixtureNameToPascalRector
2018-12-25 19:55:16 +00:00
Changes `$fixtues` style from snake_case to PascalCase.
2018-12-25 19:55:16 +00:00
- class: `Rector\CakePHP\Rector\Property\ChangeSnakedFixtureNameToPascalRector`
2018-12-25 19:55:16 +00:00
```diff
class SomeTest
2019-05-29 13:40:20 +00:00
{
protected $fixtures = [
- 'app.posts',
- 'app.users',
- 'some_plugin.posts/special_posts',
+ 'app.Posts',
+ 'app.Users',
+ 'some_plugin.Posts/SpecialPosts',
];
2018-12-25 19:55:16 +00:00
```
<br>
2018-12-25 19:55:16 +00:00
## ChangeSwitchToMatchRector
Change `switch()` to `match()`
- class: `Rector\Php80\Rector\Switch_\ChangeSwitchToMatchRector`
```diff
class SomeClass
{
public function run()
{
- $statement = switch ($this->lexer->lookahead['type']) {
- case Lexer::T_SELECT:
- $statement = $this->SelectStatement();
- break;
-
- case Lexer::T_UPDATE:
- $statement = $this->UpdateStatement();
- break;
-
- case Lexer::T_DELETE:
- $statement = $this->DeleteStatement();
- break;
-
- default:
- $this->syntaxError('SELECT, UPDATE or DELETE');
- break;
- }
+ $statement = match ($this->lexer->lookahead['type']) {
+ Lexer::T_SELECT => $this->SelectStatement(),
+ Lexer::T_UPDATE => $this->UpdateStatement(),
+ Lexer::T_DELETE => $this->DeleteStatement(),
+ default => $this->syntaxError('SELECT, UPDATE or DELETE'),
+ };
}
}
```
<br>
## ClassConstantToSelfClassRector
2019-10-15 14:46:31 +00:00
Change `__CLASS__` to self::class
2019-10-15 14:46:31 +00:00
- class: `Rector\Php74\Rector\Class_\ClassConstantToSelfClassRector`
2019-10-15 14:46:31 +00:00
```diff
class SomeClass
{
public function callOnMe()
{
- var_dump(__CLASS__);
+ var_dump(self::class);
}
2019-10-15 14:46:31 +00:00
}
```
<br>
2019-10-15 14:46:31 +00:00
## ClassOnObjectRector
Change get_class($object) to faster `$object::class`
- class: `Rector\Php80\Rector\FuncCall\ClassOnObjectRector`
```diff
class SomeClass
{
public function run($object)
{
- return get_class($object);
+ return $object::class;
}
}
```
<br>
2019-12-27 17:50:00 +00:00
## ClassPropertyAssignToConstructorPromotionRector
2019-12-27 17:50:00 +00:00
Change simple property init and assign to constructor promotion
- class: `Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector`
2019-12-27 17:50:00 +00:00
```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,
+ ) {}
2019-12-27 17:50:00 +00:00
}
```
<br>
## ClassRenamingPostRector
Post Rector that renames classes
- class: `Rector\PostRector\Rector\ClassRenamingPostRector`
```diff
-$someClass = new SomeClass();
+$someClass = new AnotherClass();
```
<br>
## ClearReturnNewByReferenceRector
Remove reference from "$assign = &new Value;"
- class: `Rector\Php53\Rector\AssignRef\ClearReturnNewByReferenceRector`
```diff
-$assign = &new Value;
+$assign = new Value;
```
<br>
## ClosureToArrowFunctionRector
Change closure to arrow function
- class: `Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector`
```diff
class SomeClass
{
public function run($meetups)
{
- return array_filter($meetups, function (Meetup $meetup) {
- return is_object($meetup);
- });
+ return array_filter($meetups, fn(Meetup $meetup) => is_object($meetup));
}
}
```
<br>
## CombineIfRector
Merges nested if statements
- class: `Rector\CodeQuality\Rector\If_\CombineIfRector`
```diff
class SomeClass
{
public function run()
{
- if ($cond1) {
- if ($cond2) {
- return 'foo';
- }
+ if ($cond1 && $cond2) {
+ return 'foo';
}
}
}
```
<br>
## CombinedAssignRector
Simplify `$value` = `$value` + 5; assignments to shorter ones
- class: `Rector\CodeQuality\Rector\Assign\CombinedAssignRector`
```diff
-$value = $value + 5;
+$value += 5;
```
<br>
## CommonNotEqualRector
Use common != instead of less known <> with same meaning
- class: `Rector\CodeQuality\Rector\NotEqual\CommonNotEqualRector`
```diff
final class SomeClass
{
public function run($one, $two)
{
- return $one <> $two;
+ return $one != $two;
}
}
```
<br>
## CompactToVariablesRector
Change `compact()` call to own array
- class: `Rector\CodeQuality\Rector\FuncCall\CompactToVariablesRector`
```diff
class SomeClass
{
public function run()
{
$checkout = 'one';
$form = 'two';
- return compact('checkout', 'form');
+ return ['checkout' => $checkout, 'form' => $form];
}
}
```
<br>
## CompleteDynamicPropertiesRector
Add missing dynamic properties
- class: `Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector`
```diff
class SomeClass
{
+ /**
+ * @var int
+ */
+ public $value;
public function set()
{
$this->value = 5;
}
}
```
<br>
## CompleteImportForPartialAnnotationRector
2018-08-01 20:09:34 +00:00
In case you have accidentally removed use imports but code still contains partial use statements, this will save you
2019-12-22 18:38:09 +00:00
:wrench: **configure it!**
2019-12-22 18:38:09 +00:00
- class: `Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector`
2019-12-22 18:38:09 +00:00
2020-07-24 11:46:57 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector;
use Rector\Restoration\ValueObject\UseWithAlias;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(CompleteImportForPartialAnnotationRector::class)
->call('configure', [[
CompleteImportForPartialAnnotationRector::USE_IMPORTS_TO_RESTORE => inline_value_objects([
new UseWithAlias('Doctrine\ORM\Mapping', 'ORM'),
]),
]]);
2020-07-24 11:46:57 +00:00
};
2019-12-22 18:38:09 +00:00
```
```diff
+use Doctrine\ORM\Mapping as ORM;
+
2019-12-22 18:38:09 +00:00
class SomeClass
{
/**
* @ORM\Id
*/
public $id;
2019-12-22 18:38:09 +00:00
}
```
<br>
## CompleteMissingDependencyInNewRector
2019-12-22 18:38:09 +00:00
Complete missing constructor dependency instance by type
2019-09-21 22:14:49 +00:00
:wrench: **configure it!**
2019-09-21 22:14:49 +00:00
- class: `Rector\Restoration\Rector\New_\CompleteMissingDependencyInNewRector`
```php
use Rector\Restoration\Rector\New_\CompleteMissingDependencyInNewRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(CompleteMissingDependencyInNewRector::class)
->call('configure', [[
CompleteMissingDependencyInNewRector::CLASS_TO_INSTANTIATE_BY_TYPE => [
'RandomDependency' => 'RandomDependency',
],
]]);
};
```
2019-09-21 22:14:49 +00:00
```diff
final class SomeClass
{
public function run()
{
- $valueObject = new RandomValueObject();
+ $valueObject = new RandomValueObject(new RandomDependency());
}
}
class RandomValueObject
{
public function __construct(RandomDependency $randomDependency)
{
}
}
```
<br>
2019-09-21 22:14:49 +00:00
## CompleteVarDocTypePropertyRector
Complete property `@var` annotations or correct the old ones
- class: `Rector\TypeDeclaration\Rector\Property\CompleteVarDocTypePropertyRector`
```diff
final class SomeClass
{
+ /**
+ * @var EventDispatcher
+ */
private $eventDispatcher;
public function __construct(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
}
```
<br>
## ConsecutiveNullCompareReturnsToNullCoalesceQueueRector
Change multiple null compares to ?? queue
2018-08-01 20:09:34 +00:00
- class: `Rector\CodeQuality\Rector\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector`
```diff
class SomeClass
{
public function run()
{
- if (null !== $this->orderItem) {
- return $this->orderItem;
- }
-
- if (null !== $this->orderItemUnit) {
- return $this->orderItemUnit;
- }
-
- return null;
+ return $this->orderItem ?? $this->orderItemUnit;
}
}
```
<br>
## ConsistentImplodeRector
2019-09-19 09:27:29 +00:00
Changes various `implode` forms to consistent one
2019-09-19 09:27:29 +00:00
- class: `Rector\CodingStyle\Rector\FuncCall\ConsistentImplodeRector`
2019-09-19 09:27:29 +00:00
```diff
class SomeClass
{
public function run(array $items)
{
- $itemsAsStrings = implode($items);
- $itemsAsStrings = implode($items, '|');
+ $itemsAsStrings = implode('', $items);
+ $itemsAsStrings = implode('|', $items);
$itemsAsStrings = implode('|', $items);
}
}
```
<br>
2019-09-19 09:27:29 +00:00
## ConsistentPregDelimiterRector
2019-09-21 22:14:49 +00:00
Replace PREG delimiter with configured one
2019-09-21 22:14:49 +00:00
:wrench: **configure it!**
- class: `Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector`
```php
use Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-09-21 22:14:49 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-09-21 22:14:49 +00:00
$services->set(ConsistentPregDelimiterRector::class)
->call('configure', [[
ConsistentPregDelimiterRector::DELIMITER => '#',
]]);
};
```
2019-09-21 22:14:49 +00:00
2019-09-21 22:14:49 +00:00
```diff
class SomeClass
{
public function run()
{
- preg_match('~value~', $value);
- preg_match_all('~value~im', $value);
+ preg_match('#value#', $value);
+ preg_match_all('#value#im', $value);
2019-09-21 22:14:49 +00:00
}
}
```
<br>
2019-09-21 22:14:49 +00:00
## ConsoleExceptionToErrorEventConstantRector
2019-09-21 22:14:49 +00:00
Turns old event name with EXCEPTION to ERROR constant in Console in Symfony
2019-09-21 22:14:49 +00:00
- class: `Rector\Symfony\Rector\ClassConstFetch\ConsoleExceptionToErrorEventConstantRector`
2019-09-21 22:14:49 +00:00
```diff
-"console.exception"
+Symfony\Component\Console\ConsoleEvents::ERROR
```
2019-09-21 22:14:49 +00:00
<br>
```diff
-Symfony\Component\Console\ConsoleEvents::EXCEPTION
+Symfony\Component\Console\ConsoleEvents::ERROR
2019-09-21 22:14:49 +00:00
```
<br>
2019-09-21 22:14:49 +00:00
## ConsoleExecuteReturnIntRector
2019-09-21 22:14:49 +00:00
Returns int from Command::execute command
2019-09-21 22:14:49 +00:00
- class: `Rector\Symfony\Rector\ClassMethod\ConsoleExecuteReturnIntRector`
2019-09-21 22:14:49 +00:00
```diff
class SomeCommand extends Command
2019-09-21 22:14:49 +00:00
{
- public function execute(InputInterface $input, OutputInterface $output)
+ public function execute(InputInterface $input, OutputInterface $output): int
2019-09-21 22:14:49 +00:00
{
- return null;
+ return 0;
2019-09-21 22:14:49 +00:00
}
}
```
<br>
2019-09-21 22:14:49 +00:00
## ConstraintUrlOptionRector
2019-09-21 22:14:49 +00:00
Turns true value to `Url::CHECK_DNS_TYPE_ANY` in Validator in Symfony.
2019-09-21 22:14:49 +00:00
- class: `Rector\Symfony\Rector\ConstFetch\ConstraintUrlOptionRector`
2019-09-21 22:14:49 +00:00
```diff
-$constraint = new Url(["checkDNS" => true]);
+$constraint = new Url(["checkDNS" => Url::CHECK_DNS_TYPE_ANY]);
2019-09-21 22:14:49 +00:00
```
<br>
2019-09-21 22:14:49 +00:00
## ConstructClassMethodToSetUpTestCaseRector
2019-09-21 22:14:49 +00:00
Change `__construct()` method in tests of `PHPUnit\Framework\TestCase` to `setUp(),` to prevent dangerous override
2019-09-21 22:14:49 +00:00
- class: `Rector\PHPUnit\Rector\Class_\ConstructClassMethodToSetUpTestCaseRector`
2019-09-21 22:14:49 +00:00
```diff
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
private $someValue;
- public function __construct(?string $name = null, array $data = [], string $dataName = '')
+ protected function setUp()
{
+ parent::setUp();
+
$this->someValue = 1000;
- parent::__construct($name, $data, $dataName);
}
}
```
<br>
2019-09-21 22:14:49 +00:00
## ContainerBuilderCompileEnvArgumentRector
Turns old default value to parameter in `ContainerBuilder->build()` method in DI in Symfony
2018-08-01 20:09:34 +00:00
- class: `Rector\Symfony\Rector\MethodCall\ContainerBuilderCompileEnvArgumentRector`
2018-08-01 20:09:34 +00:00
```diff
use Symfony\Component\DependencyInjection\ContainerBuilder;
$containerBuilder = new ContainerBuilder();
-$containerBuilder->compile();
+$containerBuilder->compile(true);
```
<br>
## ContainerGetToConstructorInjectionRector
Turns fetching of dependencies via `$container->get()` in ContainerAware to constructor injection in Command and Controller in Symfony
:wrench: **configure it!**
- class: `Rector\Symfony\Rector\MethodCall\ContainerGetToConstructorInjectionRector`
```php
use Rector\Symfony\Rector\MethodCall\ContainerGetToConstructorInjectionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ContainerGetToConstructorInjectionRector::class)
->call('configure', [[
ContainerGetToConstructorInjectionRector::CONTAINER_AWARE_PARENT_TYPES => [
'ContainerAwareParentClassName',
'ContainerAwareParentCommandClassName',
'ThisClassCallsMethodInConstructorClassName',
],
]]);
};
```
2018-08-01 20:09:34 +00:00
```diff
-final class SomeCommand extends ContainerAwareCommand
+final class SomeCommand extends Command
{
+ public function __construct(SomeService $someService)
+ {
+ $this->someService = $someService;
+ }
+
public function someMethod()
{
// ...
- $this->getContainer()->get('some_service');
- $this->container->get('some_service');
+ $this->someService;
+ $this->someService;
}
}
```
<br>
## ContextGetByTypeToConstructorInjectionRector
Move dependency get via `$context->getByType()` to constructor injection
- class: `Rector\Nette\Rector\MethodCall\ContextGetByTypeToConstructorInjectionRector`
```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;
}
}
```
<br>
## ContinueToBreakInSwitchRector
2019-10-02 08:04:14 +00:00
Use break instead of continue in switch statements
2019-10-02 08:04:14 +00:00
- class: `Rector\Php52\Rector\Switch_\ContinueToBreakInSwitchRector`
2019-10-02 08:04:14 +00:00
```diff
function some_run($value)
2019-10-02 08:04:14 +00:00
{
switch ($value) {
case 1:
echo 'Hi';
- continue;
+ break;
case 2:
echo 'Hello';
break;
}
2019-10-02 08:04:14 +00:00
}
```
<br>
2019-10-02 08:04:14 +00:00
## ConvertAddUploadWithThirdArgumentTrueToAddMultiUploadRector
2019-09-21 22:14:49 +00:00
convert `addUpload()` with 3rd argument true to `addMultiUpload()`
2019-09-21 22:14:49 +00:00
- class: `Rector\Nette\Rector\MethodCall\ConvertAddUploadWithThirdArgumentTrueToAddMultiUploadRector`
2019-09-21 22:14:49 +00:00
```diff
$form = new Nette\Forms\Form();
-$form->addUpload('...', '...', true);
+$form->addMultiUpload('...', '...');
```
<br>
2019-09-21 22:14:49 +00:00
## CorrectDefaultTypesOnEntityPropertyRector
2019-09-21 22:14:49 +00:00
Change default value types to match Doctrine annotation type
2019-09-21 22:14:49 +00:00
- class: `Rector\DoctrineCodeQuality\Rector\Property\CorrectDefaultTypesOnEntityPropertyRector`
2019-09-21 22:14:49 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class User
{
/**
* @ORM\Column(name="is_old", type="boolean")
*/
- private $isOld = '0';
+ private $isOld = false;
}
```
<br>
2019-09-21 22:14:49 +00:00
## CountArrayToEmptyArrayComparisonRector
Change `count` array comparison to empty array comparison to improve performance
- class: `Rector\Performance\Rector\FuncCall\CountArrayToEmptyArrayComparisonRector`
```diff
-count($array) === 0;
-count($array) > 0;
-! count($array);
+$array === [];
+$array !== [];
+$array === [];
```
<br>
2019-10-02 08:04:14 +00:00
## CountOnNullRector
Changes `count()` on null to safe ternary check
- class: `Rector\Php71\Rector\FuncCall\CountOnNullRector`
```diff
$values = null;
-$count = count($values);
+$count = is_array($values) || $values instanceof Countable ? count($values) : 0;
```
<br>
## CreateFunctionToAnonymousFunctionRector
Use anonymous functions instead of deprecated `create_function()`
- class: `Rector\Php72\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector`
```diff
class ClassWithCreateFunction
{
public function run()
{
- $callable = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);");
+ $callable = function($matches) use ($delimiter) {
+ return $delimiter . strtolower($matches[1]);
+ };
}
}
```
<br>
## CreateMockToCreateStubRector
Replaces `createMock()` with `createStub()` when relevant
- class: `Rector\PHPUnit\Rector\MethodCall\CreateMockToCreateStubRector`
```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());
}
}
```
<br>
## DecoupleSaveMethodCallWithArgumentToAssignRector
Decouple `Phalcon\Mvc\Model::save()` with argument to `assign()`
- class: `Rector\Phalcon\Rector\MethodCall\DecoupleSaveMethodCallWithArgumentToAssignRector`
```diff
class SomeClass
{
public function run(\Phalcon\Mvc\Model $model, $data)
{
- $model->save($data);
+ $model->save();
+ $model->assign($data);
}
}
```
<br>
## DefluentReturnMethodCallRector
2019-10-02 08:04:14 +00:00
Turns return of fluent, to standalone call line and return of value
2019-10-02 08:04:14 +00:00
- class: `Rector\Defluent\Rector\Return_\DefluentReturnMethodCallRector`
2019-10-02 08:04:14 +00:00
```diff
$someClass = new SomeClass();
-return $someClass->someFunction();
+$someClass->someFunction();
+return $someClass;
2019-10-02 08:04:14 +00:00
```
<br>
2019-10-02 08:04:14 +00:00
## DelegateExceptionArgumentsRector
Takes `setExpectedException()` 2nd and next arguments to own methods in PHPUnit.
- class: `Rector\PHPUnit\Rector\MethodCall\DelegateExceptionArgumentsRector`
```diff
-$this->setExpectedException(Exception::class, "Message", "CODE");
+$this->setExpectedException(Exception::class);
+$this->expectExceptionMessage('Message');
+$this->expectExceptionCode('CODE');
```
<br>
## DeleteFactoryInterfaceRector
Interface factories are not needed in Symfony. Clear constructor injection is used instead
- class: `Rector\NetteToSymfony\Rector\Interface_\DeleteFactoryInterfaceRector`
```diff
-interface SomeControlFactoryInterface
-{
- public function create();
-}
```
<br>
## DirNameFileConstantToDirConstantRector
Convert dirname(__FILE__) to __DIR__
- class: `Rector\Php53\Rector\FuncCall\DirNameFileConstantToDirConstantRector`
```diff
class SomeClass
{
public function run()
{
- return dirname(__FILE__);
+ return __DIR__;
}
}
```
<br>
## DowngradeArrayMergeCallWithoutArgumentsRector
Add missing param to `array_merge` and `array_merge_recursive`
- class: `Rector\DowngradePhp74\Rector\FuncCall\DowngradeArrayMergeCallWithoutArgumentsRector`
```diff
class SomeClass
{
public function run()
{
- array_merge();
- array_merge_recursive();
+ array_merge([]);
+ array_merge_recursive([]);
}
}
```
<br>
## DowngradeArraySpreadRector
Replace array spread with `array_merge` function
- class: `Rector\DowngradePhp74\Rector\Array_\DowngradeArraySpreadRector`
```diff
class SomeClass
{
public function run()
{
$parts = ['apple', 'pear'];
- $fruits = ['banana', 'orange', ...$parts, 'watermelon'];
+ $fruits = array_merge(['banana', 'orange'], $parts, ['watermelon']);
}
public function runWithIterable()
{
- $fruits = ['banana', 'orange', ...new ArrayIterator(['durian', 'kiwi']), 'watermelon'];
+ $item0Unpacked = new ArrayIterator(['durian', 'kiwi']);
+ $fruits = array_merge(['banana', 'orange'], is_array($item0Unpacked) ? $item0Unpacked : iterator_to_array($item0Unpacked), ['watermelon']);
}
}
```
<br>
## DowngradeClassConstantVisibilityRector
Downgrade class constant visibility
:wrench: **configure it!**
- class: `Rector\DowngradePhp71\Rector\ClassConst\DowngradeClassConstantVisibilityRector`
```php
use Rector\DowngradePhp71\Rector\ClassConst\DowngradeClassConstantVisibilityRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeClassConstantVisibilityRector::class);
};
```
```diff
<?php
class SomeClass
{
- public const PUBLIC_CONST_B = 2;
- protected const PROTECTED_CONST = 3;
- private const PRIVATE_CONST = 4;
+ const PUBLIC_CONST_B = 2;
+ const PROTECTED_CONST = 3;
+ const PRIVATE_CONST = 4;
}
```
<br>
## DowngradeFlexibleHeredocSyntaxRector
Changes heredoc/nowdoc that contains closing word to safe wrapper name
- class: `Rector\DowngradePhp73\Rector\String_\DowngradeFlexibleHeredocSyntaxRector`
```diff
$query = <<<SQL
- SELECT *
- FROM `table`
- WHERE `column` = true;
- SQL;
+SELECT *
+FROM `table`
+WHERE `column` = true;
+SQL;
```
<br>
## DowngradeListReferenceAssignmentRector
Convert the list reference assignment to its equivalent PHP 7.2 code
- class: `Rector\DowngradePhp73\Rector\List_\DowngradeListReferenceAssignmentRector`
```diff
class SomeClass
{
public function run($string)
{
- $array = [1, 2, 3];
- list($a, &$b) = $array;
+ $array = [1, 2];
+ list($a) = $array;
+ $b =& $array[1];
- [&$c, $d, &$e] = $array;
+ [$c, $d, $e] = $array;
+ $c =& $array[0];
+ $e =& $array[2];
- list(&$a, &$b) = $array;
+ $a =& $array[0];
+ $b =& $array[1];
}
}
```
<br>
2019-12-26 10:21:09 +00:00
## DowngradeNullCoalescingOperatorRector
2020-01-08 00:05:45 +00:00
Remove null coalescing operator ??=
2020-01-08 00:05:45 +00:00
- class: `Rector\DowngradePhp74\Rector\Coalesce\DowngradeNullCoalescingOperatorRector`
2020-01-08 00:05:45 +00:00
```diff
$array = [];
-$array['user_id'] ??= 'value';
+$array['user_id'] = $array['user_id'] ?? 'value';
2020-01-08 00:05:45 +00:00
```
<br>
2020-01-08 00:05:45 +00:00
## DowngradeNullableTypeParamDeclarationRector
2020-01-08 00:05:45 +00:00
Remove the nullable type params, add `@param` tags instead
2020-01-08 00:05:45 +00:00
:wrench: **configure it!**
- class: `Rector\DowngradePhp71\Rector\FunctionLike\DowngradeNullableTypeParamDeclarationRector`
```php
use Rector\DowngradePhp71\Rector\FunctionLike\DowngradeNullableTypeParamDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeNullableTypeParamDeclarationRector::class)
->call('configure', [[
DowngradeNullableTypeParamDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
2020-01-08 00:05:45 +00:00
```diff
<?php
2020-01-08 00:05:45 +00:00
class SomeClass
2020-01-08 00:05:45 +00:00
{
- public function run(?string $input)
+ /**
+ * @param string|null $input
+ */
+ public function run($input)
{
// do something
}
2020-01-08 00:05:45 +00:00
}
```
<br>
2020-01-08 00:05:45 +00:00
## DowngradeNullableTypeReturnDeclarationRector
2019-12-26 10:21:09 +00:00
Remove returning nullable types, add a `@return` tag instead
2019-12-26 10:21:09 +00:00
:wrench: **configure it!**
2019-12-26 10:21:09 +00:00
- class: `Rector\DowngradePhp71\Rector\FunctionLike\DowngradeNullableTypeReturnDeclarationRector`
2019-12-26 10:21:09 +00:00
```php
use Rector\DowngradePhp71\Rector\FunctionLike\DowngradeNullableTypeReturnDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-12-26 10:21:09 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-01-08 00:05:45 +00:00
$services->set(DowngradeNullableTypeReturnDeclarationRector::class)
->call('configure', [[
DowngradeNullableTypeReturnDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
2020-01-08 00:05:45 +00:00
2020-01-08 00:05:45 +00:00
```diff
<?php
2020-01-08 00:05:45 +00:00
class SomeClass
2020-01-08 00:05:45 +00:00
{
- public function getResponseOrNothing(bool $flag): ?string
+ /**
+ * @return string|null
+ */
+ public function getResponseOrNothing(bool $flag)
{
if ($flag) {
return 'Hello world';
}
return null;
}
2020-01-08 00:05:45 +00:00
}
```
<br>
2020-01-08 00:05:45 +00:00
## DowngradeNumericLiteralSeparatorRector
2019-12-26 10:21:09 +00:00
Remove "_" as thousands separator in numbers
2019-12-26 10:21:09 +00:00
- class: `Rector\DowngradePhp74\Rector\LNumber\DowngradeNumericLiteralSeparatorRector`
2019-12-26 10:21:09 +00:00
```diff
class SomeClass
2019-12-26 10:21:09 +00:00
{
public function run()
{
- $int = 1_000;
- $float = 1_000_500.001;
+ $int = 1000;
+ $float = 1000500.001;
}
2019-12-26 10:21:09 +00:00
}
```
<br>
2019-12-27 17:50:00 +00:00
## DowngradeParamMixedTypeDeclarationRector
2019-12-27 17:50:00 +00:00
Remove the 'mixed' param type, add a `@param` tag instead
2019-12-27 17:50:00 +00:00
:wrench: **configure it!**
2019-12-27 17:50:00 +00:00
- class: `Rector\DowngradePhp80\Rector\FunctionLike\DowngradeParamMixedTypeDeclarationRector`
2019-12-27 17:50:00 +00:00
```php
use Rector\DowngradePhp80\Rector\FunctionLike\DowngradeParamMixedTypeDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-12-27 17:50:00 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-12-26 10:21:09 +00:00
$services->set(DowngradeParamMixedTypeDeclarationRector::class)
->call('configure', [[
DowngradeParamMixedTypeDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
2019-12-26 10:21:09 +00:00
2019-12-26 10:21:09 +00:00
```diff
<?php
2019-12-26 10:21:09 +00:00
class SomeClass
2019-12-26 10:21:09 +00:00
{
- public function someFunction(mixed $anything)
+ /**
+ * @param mixed $anything
+ */
+ public function someFunction($anything)
{
}
2019-12-26 10:21:09 +00:00
}
```
<br>
2019-12-26 10:21:09 +00:00
## DowngradeParamObjectTypeDeclarationRector
Remove the 'object' param type, add a `@param` tag instead
:wrench: **configure it!**
- class: `Rector\DowngradePhp72\Rector\FunctionLike\DowngradeParamObjectTypeDeclarationRector`
```php
use Rector\DowngradePhp72\Rector\FunctionLike\DowngradeParamObjectTypeDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeParamObjectTypeDeclarationRector::class)
->call('configure', [[
DowngradeParamObjectTypeDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
<?php
class SomeClass
{
- public function someFunction(object $someObject)
+ /**
+ * @param object $someObject
+ */
+ public function someFunction($someObject)
{
}
}
```
<br>
## DowngradeReturnMixedTypeDeclarationRector
Remove the 'mixed' function type, add a `@return` tag instead
:wrench: **configure it!**
- class: `Rector\DowngradePhp80\Rector\FunctionLike\DowngradeReturnMixedTypeDeclarationRector`
```php
use Rector\DowngradePhp80\Rector\FunctionLike\DowngradeReturnMixedTypeDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeReturnMixedTypeDeclarationRector::class)
->call('configure', [[
DowngradeReturnMixedTypeDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
<?php
class SomeClass
{
- public function getAnything(bool $flag): mixed
+ /**
+ * @return mixed
+ */
+ public function getAnything(bool $flag)
{
if ($flag) {
return 1;
}
return 'Hello world'
}
}
```
<br>
## DowngradeReturnObjectTypeDeclarationRector
Remove the 'object' function type, add a `@return` tag instead
:wrench: **configure it!**
- class: `Rector\DowngradePhp72\Rector\FunctionLike\DowngradeReturnObjectTypeDeclarationRector`
```php
use Rector\DowngradePhp72\Rector\FunctionLike\DowngradeReturnObjectTypeDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeReturnObjectTypeDeclarationRector::class)
->call('configure', [[
DowngradeReturnObjectTypeDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
<?php
class SomeClass
{
- public function getSomeObject(): object
+ /**
+ * @return object
+ */
+ public function getSomeObject()
{
return new SomeObject();
}
}
```
<br>
## DowngradeReturnStaticTypeDeclarationRector
Remove the 'static' function type, add a `@return` tag instead
:wrench: **configure it!**
- class: `Rector\DowngradePhp80\Rector\FunctionLike\DowngradeReturnStaticTypeDeclarationRector`
```php
use Rector\DowngradePhp80\Rector\FunctionLike\DowngradeReturnStaticTypeDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeReturnStaticTypeDeclarationRector::class)
->call('configure', [[
DowngradeReturnStaticTypeDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
<?php
class SomeClass
{
- public function getStatic(): static
+ /**
+ * @return static
+ */
+ public function getStatic()
{
return new static();
}
}
```
<br>
## DowngradeStripTagsCallWithArrayRector
Convert 2nd param to `strip_tags` from array to string
- class: `Rector\DowngradePhp74\Rector\FuncCall\DowngradeStripTagsCallWithArrayRector`
```diff
class SomeClass
{
public function run($string)
{
// Arrays: change to string
- strip_tags($string, ['a', 'p']);
+ strip_tags($string, '<' . implode('><', ['a', 'p']) . '>');
// Variables/consts/properties: if array, change to string
$tags = ['a', 'p'];
- strip_tags($string, $tags);
+ strip_tags($string, $tags !== null && is_array($tags) ? '<' . implode('><', $tags) . '>' : $tags);
// Default case (eg: function call): externalize to var, then if array, change to string
- strip_tags($string, getTags());
+ $expr = getTags();
+ strip_tags($string, is_array($expr) ? '<' . implode('><', $expr) . '>' : $expr);
}
}
```
<br>
## DowngradeTypedPropertyRector
Changes property type definition from type definitions to `@var` annotations.
:wrench: **configure it!**
- class: `Rector\DowngradePhp74\Rector\Property\DowngradeTypedPropertyRector`
```php
use Rector\DowngradePhp74\Rector\Property\DowngradeTypedPropertyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeTypedPropertyRector::class)
->call('configure', [[
DowngradeTypedPropertyRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
class SomeClass
{
- private string $property;
+ /**
+ * @var string
+ */
+ private $property;
}
```
<br>
## DowngradeUnionTypeParamDeclarationRector
Remove the union type params, add `@param` tags instead
:wrench: **configure it!**
- class: `Rector\DowngradePhp80\Rector\FunctionLike\DowngradeUnionTypeParamDeclarationRector`
```php
use Rector\DowngradePhp80\Rector\FunctionLike\DowngradeUnionTypeParamDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeUnionTypeParamDeclarationRector::class)
->call('configure', [[
DowngradeUnionTypeParamDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
<?php
class SomeClass
{
- public function echoInput(string|int $input)
+ /**
+ * @param string|int $input
+ */
+ public function echoInput($input)
{
echo $input;
}
}
```
<br>
## DowngradeUnionTypeReturnDeclarationRector
Remove returning union types, add a `@return` tag instead
:wrench: **configure it!**
- class: `Rector\DowngradePhp80\Rector\FunctionLike\DowngradeUnionTypeReturnDeclarationRector`
```php
use Rector\DowngradePhp80\Rector\FunctionLike\DowngradeUnionTypeReturnDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeUnionTypeReturnDeclarationRector::class)
->call('configure', [[
DowngradeUnionTypeReturnDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
<?php
class SomeClass
{
- public function getSomeObject(bool $flag): string|int
+ /**
+ * @return string|int
+ */
+ public function getSomeObject(bool $flag)
{
if ($flag) {
return 1;
}
return 'Hello world';
}
}
```
<br>
## DowngradeUnionTypeTypedPropertyRector
Removes union type property type definition, adding `@var` annotations instead.
:wrench: **configure it!**
- class: `Rector\DowngradePhp80\Rector\Property\DowngradeUnionTypeTypedPropertyRector`
```php
use Rector\DowngradePhp80\Rector\Property\DowngradeUnionTypeTypedPropertyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeUnionTypeTypedPropertyRector::class)
->call('configure', [[
DowngradeUnionTypeTypedPropertyRector::ADD_DOC_BLOCK => true,
]]);
};
```
```diff
class SomeClass
{
- private string|int $property;
+ /**
+ * @var string|int
+ */
+ private $property;
}
```
<br>
## DowngradeVoidTypeReturnDeclarationRector
2020-10-09 20:01:37 +00:00
Remove the 'void' function type, add a `@return` tag instead
2020-10-09 20:01:37 +00:00
:wrench: **configure it!**
- class: `Rector\DowngradePhp71\Rector\FunctionLike\DowngradeVoidTypeReturnDeclarationRector`
```php
use Rector\DowngradePhp71\Rector\FunctionLike\DowngradeVoidTypeReturnDeclarationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeVoidTypeReturnDeclarationRector::class)
->call('configure', [[
DowngradeVoidTypeReturnDeclarationRector::ADD_DOC_BLOCK => true,
]]);
};
```
2020-10-09 20:01:37 +00:00
```diff
<?php
2020-10-09 20:01:37 +00:00
class SomeClass
{
- public function run(): void
+ /**
+ * @return void
+ */
+ public function run()
2020-10-09 20:01:37 +00:00
{
// do something
2020-10-09 20:01:37 +00:00
}
}
```
<br>
2020-10-09 20:01:37 +00:00
## EmptyListRector
`list()` cannot be empty
- class: `Rector\Php70\Rector\List_\EmptyListRector`
```diff
-'list() = $values;'
+'list($unusedGenerated) = $values;'
```
<br>
## EncapsedStringsToSprintfRector
2020-10-07 13:41:19 +00:00
Convert enscaped {$string} to more readable `sprintf`
2020-10-07 13:41:19 +00:00
- class: `Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector`
2020-10-07 13:41:19 +00:00
```diff
final class SomeClass
2020-10-07 13:41:19 +00:00
{
public function run(string $format)
2020-10-07 13:41:19 +00:00
{
- return "Unsupported format {$format}";
+ return sprintf('Unsupported format %s', $format);
2020-10-07 13:41:19 +00:00
}
}
```
<br>
2020-10-07 13:41:19 +00:00
## EndsWithFunctionToNetteUtilsStringsRector
2020-10-07 13:41:19 +00:00
Use `Nette\Utils\Strings::endsWith()` over bare string-functions
2020-10-07 13:41:19 +00:00
- class: `Rector\Nette\Rector\Identical\EndsWithFunctionToNetteUtilsStringsRector`
2020-10-07 13:41:19 +00:00
```diff
class SomeClass
{
public function end($needle)
2020-10-07 13:41:19 +00:00
{
$content = 'Hi, my name is Tom';
2020-10-07 13:41:19 +00:00
- $yes = substr($content, -strlen($needle)) === $needle;
+ $yes = \Nette\Utils\Strings::endsWith($content, $needle);
2020-10-07 13:41:19 +00:00
}
}
```
<br>
## EntityAliasToClassConstantReferenceRector
Replaces doctrine alias with class.
:wrench: **configure it!**
- class: `Rector\Doctrine\Rector\MethodCall\EntityAliasToClassConstantReferenceRector`
```php
use Rector\Doctrine\Rector\MethodCall\EntityAliasToClassConstantReferenceRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(EntityAliasToClassConstantReferenceRector::class)
->call('configure', [[
EntityAliasToClassConstantReferenceRector::ALIASES_TO_NAMESPACES => [
App::class => 'App\Entity',
],
]]);
};
```
```diff
$entityManager = new Doctrine\ORM\EntityManager();
-$entityManager->getRepository("AppBundle:Post");
+$entityManager->getRepository(\App\Entity\Post::class);
```
<br>
## EregToPregMatchRector
Changes ereg*() to preg*() calls
- class: `Rector\Php70\Rector\FuncCall\EregToPregMatchRector`
```diff
-ereg("hi")
+preg_match("#hi#");
```
<br>
## EventListenerToEventSubscriberRector
Change Symfony Event listener class to Event Subscriber based on configuration in service.yaml file
- class: `Rector\SymfonyCodeQuality\Rector\Class_\EventListenerToEventSubscriberRector`
```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' }
+}
```
<br>
## ExceptionAnnotationRector
Changes ``@expectedException` annotations to `expectException*()` methods
- class: `Rector\PHPUnit\Rector\ClassMethod\ExceptionAnnotationRector`
```diff
-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
public function test()
{
+ $this->expectException('Exception');
+ $this->expectExceptionMessage('Message');
// tested code
}
```
<br>
## ExceptionHandlerTypehintRector
Changes property `@var` annotations from annotation to type.
- class: `Rector\Php70\Rector\FunctionLike\ExceptionHandlerTypehintRector`
```diff
-function handler(Exception $exception) { ... }
+function handler(Throwable $exception) { ... }
set_exception_handler('handler');
```
<br>
## ExplicitBoolCompareRector
Make if conditions more explicit
- class: `Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector`
```diff
final class SomeController
{
public function run($items)
{
- if (!count($items)) {
+ if (count($items) === 0) {
return 'no items';
}
}
}
```
<br>
## ExplicitPhpErrorApiRector
Use explicit API for expecting PHP errors, warnings, and notices
- class: `Rector\PHPUnit\Rector\MethodCall\ExplicitPhpErrorApiRector`
```diff
final class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
- $this->expectException(\PHPUnit\Framework\TestCase\Deprecated::class);
- $this->expectException(\PHPUnit\Framework\TestCase\Error::class);
- $this->expectException(\PHPUnit\Framework\TestCase\Notice::class);
- $this->expectException(\PHPUnit\Framework\TestCase\Warning::class);
+ $this->expectDeprecation();
+ $this->expectError();
+ $this->expectNotice();
+ $this->expectWarning();
}
}
```
<br>
## ExportToReflectionFunctionRector
Change `export()` to ReflectionFunction alternatives
- class: `Rector\Php74\Rector\StaticCall\ExportToReflectionFunctionRector`
```diff
-$reflectionFunction = ReflectionFunction::export('foo');
-$reflectionFunctionAsString = ReflectionFunction::export('foo', true);
+$reflectionFunction = new ReflectionFunction('foo');
+$reflectionFunctionAsString = (string) new ReflectionFunction('foo');
```
<br>
## FilePutContentsToFileSystemWriteRector
Change `file_put_contents()` to `FileSystem::write()`
- class: `Rector\Nette\Rector\FuncCall\FilePutContentsToFileSystemWriteRector`
```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);
}
}
```
<br>
## FilterVarToAddSlashesRector
Change `filter_var()` with slash escaping to `addslashes()`
- class: `Rector\Php74\Rector\FuncCall\FilterVarToAddSlashesRector`
```diff
$var= "Satya's here!";
-filter_var($var, FILTER_SANITIZE_MAGIC_QUOTES);
+addslashes($var);
```
<br>
## FinalizeClassesWithoutChildrenRector
Finalize every class that has no children
- class: `Rector\SOLID\Rector\Class_\FinalizeClassesWithoutChildrenRector`
```diff
-class FirstClass
+final class FirstClass
{
}
class SecondClass
{
}
-class ThirdClass extends SecondClass
+final class ThirdClass extends SecondClass
{
}
```
<br>
## FixClassCaseSensitivityNameRector
Change miss-typed case sensitivity name to correct one
- class: `Rector\CodeQuality\Rector\Name\FixClassCaseSensitivityNameRector`
```diff
final class SomeClass
{
public function run()
{
- $anotherClass = new anotherclass;
+ $anotherClass = new AnotherClass;
}
}
final class AnotherClass
{
}
```
<br>
## FlashWithCssClassesToExtraCallRector
Add `$cssClasses` in Flash to separated method call
- class: `Rector\Phalcon\Rector\Assign\FlashWithCssClassesToExtraCallRector`
```diff
class SomeClass
{
public function run()
{
$cssClasses = [];
- $flash = new Phalcon\Flash($cssClasses);
+ $flash = new Phalcon\Flash();
+ $flash->setCssClasses($cssClasses);
}
}
```
<br>
## FluentChainMethodCallToNormalMethodCallRector
Turns fluent interface calls to classic ones.
- class: `Rector\Defluent\Rector\MethodCall\FluentChainMethodCallToNormalMethodCallRector`
```diff
$someClass = new SomeClass();
-$someClass->someFunction()
- ->otherFunction();
+$someClass->someFunction();
+$someClass->otherFunction();
```
<br>
## FollowRequireByDirRector
include/require should be followed by absolute path
- class: `Rector\CodingStyle\Rector\Include_\FollowRequireByDirRector`
```diff
class SomeClass
{
public function run()
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
}
}
```
<br>
## ForRepeatedCountToOwnVariableRector
Change `count()` in for function to own variable
- class: `Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector`
```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];
}
}
}
```
<br>
## ForToForeachRector
Change `for()` to `foreach()` where useful
- class: `Rector\CodeQuality\Rector\For_\ForToForeachRector`
```diff
class SomeClass
{
public function run($tokens)
{
- for ($i = 0, $c = count($tokens); $i < $c; ++$i) {
- if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'fn') {
+ foreach ($tokens as $i => $token) {
+ if ($token[0] === T_STRING && $token[1] === 'fn') {
$previousNonSpaceToken = $this->getPreviousNonSpaceToken($tokens, $i);
if ($previousNonSpaceToken !== null && $previousNonSpaceToken[0] === T_OBJECT_OPERATOR) {
continue;
}
$tokens[$i][0] = self::T_FN;
}
}
}
}
```
<br>
## ForeachItemsAssignToEmptyArrayToAssignRector
Change `foreach()` items assign to empty array to direct assign
- class: `Rector\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector`
```diff
class SomeClass
{
public function run($items)
{
$collectedItems = [];
- foreach ($items as $item) {
- $collectedItems[] = $item;
- }
+ $collectedItems = $items;
}
}
```
<br>
2020-07-24 11:46:57 +00:00
## ForeachToInArrayRector
2020-07-24 11:46:57 +00:00
Simplify `foreach` loops into `in_array` when possible
2020-07-24 11:46:57 +00:00
- class: `Rector\CodeQuality\Rector\Foreach_\ForeachToInArrayRector`
2020-07-24 11:46:57 +00:00
```diff
-foreach ($items as $item) {
- if ($item === 'something') {
- return true;
- }
-}
-
-return false;
+in_array("something", $items, true);
```
<br>
2020-07-24 11:46:57 +00:00
## FormControlToControllerAndFormTypeRector
Change Form that extends Control to Controller and decoupled FormType
2020-07-24 11:46:57 +00:00
- class: `Rector\NetteToSymfony\Rector\Class_\FormControlToControllerAndFormTypeRector`
2020-07-24 11:46:57 +00:00
```diff
-use Nette\Application\UI\Form;
-use Nette\Application\UI\Control;
-
-class SomeForm extends Control
+class SomeFormController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
2020-07-24 11:46:57 +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'];
- }
-
- public function processForm(Form $form)
- {
- // process me
+ if ($form->isSuccess() && $form->isValid()) {
+ // process me
+ }
}
2020-07-24 11:46:57 +00:00
}
```
Extra 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): void
{
$formBuilder->add('name', TextType::class, [
'label' => 'Your name',
]);
}
}
```
<br>
## FormIsValidRector
Adds `$form->isSubmitted()` validation to all `$form->isValid()` calls in Form in Symfony
- class: `Rector\Symfony\Rector\MethodCall\FormIsValidRector`
```diff
-if ($form->isValid()) {
+if ($form->isSubmitted() && $form->isValid()) {
}
```
<br>
## FormTypeGetParentRector
Turns string Form Type references to their `CONSTANT` alternatives in `getParent()` and `getExtendedType()` methods in Form in Symfony
- class: `Rector\Symfony\Rector\ClassMethod\FormTypeGetParentRector`
```diff
use Symfony\Component\Form\AbstractType;
class SomeType extends AbstractType
{
public function getParent()
{
- return 'collection';
+ return \Symfony\Component\Form\Extension\Core\Type\CollectionType::class;
}
}
```
<br>
```diff
use Symfony\Component\Form\AbstractTypeExtension;
class SomeExtension extends AbstractTypeExtension
{
public function getExtendedType()
{
- return 'collection';
+ return \Symfony\Component\Form\Extension\Core\Type\CollectionType::class;
}
}
```
<br>
## FormTypeInstanceToClassConstRector
2019-03-09 13:24:30 +00:00
Changes createForm(new FormType), add(new FormType) to ones with "FormType::class"
2019-03-09 13:24:30 +00:00
- class: `Rector\Symfony\Rector\MethodCall\FormTypeInstanceToClassConstRector`
2019-03-09 13:24:30 +00:00
```diff
class SomeController
{
public function action()
{
- $form = $this->createForm(new TeamType, $entity);
+ $form = $this->createForm(TeamType::class, $entity);
}
}
```
<br>
## FormerNullableArgumentToScalarTypedRector
2019-09-19 09:27:29 +00:00
Change null in argument, that is now not nullable anymore
2019-09-19 09:27:29 +00:00
- class: `Rector\Generic\Rector\MethodCall\FormerNullableArgumentToScalarTypedRector`
2019-09-19 09:27:29 +00:00
```diff
final class SomeClass
{
public function run()
{
- $this->setValue(null);
+ $this->setValue('');
}
2019-09-19 09:27:29 +00:00
public function setValue(string $value)
{
}
}
```
<br>
## FromHttpRequestGetHeaderToHeadersGetRector
Changes `getHeader()` to `$request->headers->get()`
- class: `Rector\NetteToSymfony\Rector\MethodCall\FromHttpRequestGetHeaderToHeadersGetRector`
```diff
use Nette\Request;
2019-03-09 13:24:30 +00:00
final class SomeController
{
public static function someAction(Request $request)
{
- $header = $this->httpRequest->getHeader('x');
+ $header = $request->headers->get('x');
}
}
```
<br>
2019-03-09 13:24:30 +00:00
## FromRequestGetParameterToAttributesGetRector
Changes `"getParameter()"` to `"attributes->get()"` from Nette to Symfony
2019-03-09 13:24:30 +00:00
- class: `Rector\NetteToSymfony\Rector\MethodCall\FromRequestGetParameterToAttributesGetRector`
2019-03-09 13:24:30 +00:00
```diff
use Nette\Request;
final class SomeController
2019-03-09 13:24:30 +00:00
{
public static function someAction(Request $request)
2019-03-09 13:24:30 +00:00
{
- $value = $request->getParameter('abz');
+ $value = $request->attribute->get('abz');
2019-03-09 13:24:30 +00:00
}
}
```
<br>
2019-03-09 13:24:30 +00:00
## FuncCallToMethodCallRector
2019-03-09 13:24:30 +00:00
Turns defined function calls to local method calls.
2019-03-09 13:24:30 +00:00
:wrench: **configure it!**
2019-03-09 13:24:30 +00:00
- class: `Rector\Transform\Rector\FuncCall\FuncCallToMethodCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\FuncCall\FuncCallToMethodCallRector;
use Rector\Transform\ValueObject\FuncNameToMethodCallName;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-14 21:23:06 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(FuncCallToMethodCallRector::class)
->call('configure', [[
FuncCallToMethodCallRector::FUNC_CALL_TO_CLASS_METHOD_CALL => inline_value_objects([
new FuncNameToMethodCallName('view', 'Namespaced\SomeRenderer', 'render'),
]),
]]);
};
2020-07-14 21:23:06 +00:00
```
```diff
class SomeClass
{
+ /**
+ * @var \Namespaced\SomeRenderer
+ */
+ private $someRenderer;
+
+ public function __construct(\Namespaced\SomeRenderer $someRenderer)
+ {
+ $this->someRenderer = $someRenderer;
+ }
+
public function run()
{
- view('...');
+ $this->someRenderer->view('...');
}
}
```
<br>
## FuncCallToNewRector
Change configured function calls to new Instance
:wrench: **configure it!**
- class: `Rector\Generic\Rector\FuncCall\FuncCallToNewRector`
```php
use Rector\Generic\Rector\FuncCall\FuncCallToNewRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(FuncCallToNewRector::class)
->call('configure', [[
FuncCallToNewRector::FUNCTION_TO_NEW => [
'collection' => ['Collection'],
],
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $array = collection([]);
+ $array = new \Collection([]);
}
}
```
<br>
## FuncCallToStaticCallRector
Turns defined function call to static method call.
:wrench: **configure it!**
2020-07-24 11:46:57 +00:00
- class: `Rector\Generic\Rector\FuncCall\FuncCallToStaticCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\FuncCall\FuncCallToStaticCallRector;
use Rector\Transform\ValueObject\FuncCallToStaticCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(FuncCallToStaticCallRector::class)
->call('configure', [[
FuncCallToStaticCallRector::FUNC_CALLS_TO_STATIC_CALLS => inline_value_objects([
new FuncCallToStaticCall('view', 'SomeStaticClass', 'render'),
]),
]]);
2020-07-24 11:46:57 +00:00
};
```
```diff
-view("...", []);
+SomeClass::render("...", []);
```
<br>
## FunctionCallToConstantRector
Changes use of function calls to use constants
:wrench: **configure it!**
2020-07-24 11:46:57 +00:00
- class: `Rector\CodingStyle\Rector\FuncCall\FunctionCallToConstantRector`
```php
use Rector\CodingStyle\Rector\FuncCall\FunctionCallToConstantRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(FunctionCallToConstantRector::class)
->call('configure', [[
FunctionCallToConstantRector::FUNCTIONS_TO_CONSTANTS => [
'php_sapi_name' => 'PHP_SAPI',
],
]]);
2020-07-24 11:46:57 +00:00
};
```
```diff
class SomeClass
{
public function run()
{
- $value = php_sapi_name();
+ $value = PHP_SAPI;
}
}
```
<br>
2020-07-24 11:46:57 +00:00
```php
use Rector\CodingStyle\Rector\FuncCall\FunctionCallToConstantRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(FunctionCallToConstantRector::class)
->call('configure', [[
FunctionCallToConstantRector::FUNCTIONS_TO_CONSTANTS => [
'pi' => 'M_PI',
],
]]);
2020-07-24 11:46:57 +00:00
};
```
```diff
class SomeClass
{
public function run()
{
- $value = pi();
+ $value = M_PI;
}
}
```
<br>
## FunctionToStaticMethodRector
Change functions to static calls, so composer can autoload them
- class: `Rector\Legacy\Rector\FileWithoutNamespace\FunctionToStaticMethodRector`
```diff
-function some_function()
+class SomeUtilsClass
{
+ public static function someFunction()
+ {
+ }
}
-some_function('lol');
+SomeUtilsClass::someFunction('lol');
```
<br>
## GetAndSetToMethodCallRector
Turns defined `__get`/`__set` to specific method calls.
:wrench: **configure it!**
- class: `Rector\MagicDisclosure\Rector\Assign\GetAndSetToMethodCallRector`
2020-07-24 11:46:57 +00:00
```php
use Rector\MagicDisclosure\Rector\Assign\GetAndSetToMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(GetAndSetToMethodCallRector::class)
->call('configure', [[
GetAndSetToMethodCallRector::TYPE_TO_METHOD_CALLS => [
'SomeContainer' => [
'set' => 'addService',
],
],
]]);
};
```
```diff
$container = new SomeContainer;
-$container->someService = $someService;
+$container->setService("someService", $someService);
```
<br>
```php
use Rector\MagicDisclosure\Rector\Assign\GetAndSetToMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(GetAndSetToMethodCallRector::class)
->call('configure', [[
GetAndSetToMethodCallRector::TYPE_TO_METHOD_CALLS => [
'SomeContainer' => [
'get' => 'getService',
],
],
]]);
2020-07-24 11:46:57 +00:00
};
```
```diff
$container = new SomeContainer;
-$someService = $container->someService;
+$someService = $container->getService("someService");
```
<br>
## GetCalledClassToStaticClassRector
Change `get_called_class()` to static::class
- class: `Rector\Php74\Rector\FuncCall\GetCalledClassToStaticClassRector`
```diff
class SomeClass
{
public function callOnMe()
{
- var_dump(get_called_class());
+ var_dump(static::class);
}
}
```
<br>
## GetClassOnNullRector
Null is no more allowed in `get_class()`
- class: `Rector\Php72\Rector\FuncCall\GetClassOnNullRector`
```diff
final class SomeClass
{
public function getItem()
{
$value = null;
- return get_class($value);
+ return $value !== null ? get_class($value) : self::class;
}
}
```
<br>
## GetClassToInstanceOfRector
2020-07-24 11:46:57 +00:00
Changes comparison with `get_class` to instanceof
- class: `Rector\CodeQuality\Rector\Identical\GetClassToInstanceOfRector`
```diff
-if (EventsListener::class === get_class($event->job)) { }
+if ($event->job instanceof EventsListener) { }
```
<br>
## GetConfigWithDefaultsArgumentToArrayMergeInCompilerExtensionRector
Change `$this->getConfig($defaults)` to `array_merge`
- class: `Rector\Nette\Rector\MethodCall\GetConfigWithDefaultsArgumentToArrayMergeInCompilerExtensionRector`
```diff
use Nette\DI\CompilerExtension;
final class SomeExtension extends CompilerExtension
{
private $defaults = [
'key' => 'value'
];
public function loadConfiguration()
{
- $config = $this->getConfig($this->defaults);
+ $config = array_merge($this->defaults, $this->getConfig());
}
}
```
<br>
## GetDebugTypeRector
Change ternary type resolve to `get_debug_type()`
- class: `Rector\Php80\Rector\Ternary\GetDebugTypeRector`
```diff
class SomeClass
{
public function run($value)
{
- return is_object($value) ? get_class($value) : gettype($value);
+ return get_debug_type($value);
}
}
```
<br>
## GetDefaultStyleToGetParentRector
Methods to (new `Worksheet())->getDefaultStyle()` to `getParent()->getDefaultStyle()`
- class: `Rector\PHPOffice\Rector\MethodCall\GetDefaultStyleToGetParentRector`
```diff
class SomeClass
{
public function run()
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->getDefaultStyle();
+ $worksheet->getParent()->getDefaultStyle();
}
}
```
<br>
## GetMockBuilderGetMockToCreateMockRector
Remove `getMockBuilder()` to `createMock()`
- class: `Rector\PHPUnit\Rector\MethodCall\GetMockBuilderGetMockToCreateMockRector`
```diff
class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
- $applicationMock = $this->getMockBuilder('SomeClass')
- ->disableOriginalConstructor()
- ->getMock();
+ $applicationMock = $this->createMock('SomeClass');
}
}
```
<br>
## GetMockRector
Turns getMock*() methods to `createMock()`
- class: `Rector\PHPUnit\Rector\StaticCall\GetMockRector`
```diff
-$this->getMock("Class");
+$this->createMock("Class");
```
<br>
```diff
-$this->getMockWithoutInvokingTheOriginalConstructor("Class");
+$this->createMock("Class");
```
2020-05-14 10:26:57 +00:00
<br>
2020-05-14 10:26:57 +00:00
## GetParameterToConstructorInjectionRector
2020-05-14 10:26:57 +00:00
Turns fetching of parameters via `getParameter()` in ContainerAware to constructor injection in Command and Controller in Symfony
- class: `Rector\Symfony\Rector\MethodCall\GetParameterToConstructorInjectionRector`
```diff
-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
{
+ private $someParameter;
+
+ public function __construct($someParameter)
+ {
+ $this->someParameter = $someParameter;
+ }
+
public function someMethod()
{
- $this->getParameter('someParameter');
+ $this->someParameter;
}
}
```
<br>
## GetRequestRector
Turns fetching of dependencies via `$this->get()` to constructor injection in Command and Controller in Symfony
2020-05-14 10:26:57 +00:00
- class: `Rector\Symfony\Rector\ClassMethod\GetRequestRector`
2020-05-14 10:26:57 +00:00
```diff
+use Symfony\Component\HttpFoundation\Request;
+
class SomeController
2020-05-14 10:26:57 +00:00
{
- public function someAction()
+ public function someAction(Request $request)
{
- $this->getRequest()->...();
+ $request->...();
}
2020-05-14 10:26:57 +00:00
}
```
<br>
2020-05-14 10:26:57 +00:00
## GetToConstructorInjectionRector
2020-05-14 10:26:57 +00:00
Turns fetching of dependencies via `$this->get()` to constructor injection in Command and Controller in Symfony
:wrench: **configure it!**
- class: `Rector\Symfony\Rector\MethodCall\GetToConstructorInjectionRector`
```php
use Rector\Symfony\Rector\MethodCall\GetToConstructorInjectionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(GetToConstructorInjectionRector::class)
->call('configure', [[
GetToConstructorInjectionRector::GET_METHOD_AWARE_TYPES => ['SymfonyControllerClassName', 'GetTraitClassName'],
]]);
};
```
2020-05-14 10:26:57 +00:00
```diff
-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
2020-05-14 10:26:57 +00:00
{
+ public function __construct(SomeService $someService)
+ {
+ $this->someService = $someService;
+ }
+
public function someMethod()
{
- // ...
- $this->get('some_service');
+ $this->someService;
}
2020-05-14 10:26:57 +00:00
}
```
<br>
## IfToSpaceshipRector
Changes if/else to spaceship <=> where useful
- class: `Rector\Php70\Rector\If_\IfToSpaceshipRector`
```diff
class SomeClass
{
public function run()
{
usort($languages, function ($a, $b) {
- if ($a[0] === $b[0]) {
- return 0;
- }
-
- return ($a[0] < $b[0]) ? 1 : -1;
+ return $b[0] <=> $a[0];
});
}
}
```
<br>
## ImplicitShortClassNameUseStatementRector
Collect implicit class names and add imports
- class: `Rector\CakePHP\Rector\FileWithoutNamespace\ImplicitShortClassNameUseStatementRector`
```diff
use App\Foo\Plugin;
+use Cake\TestSuite\Fixture\TestFixture;
class LocationsFixture extends TestFixture implements Plugin
{
}
```
<br>
## ImproveDoctrineCollectionDocTypeInEntityRector
2019-02-21 14:36:16 +00:00
Improve @var, `@param` and `@return` types for Doctrine collections to make them useful both for PHPStan and PHPStorm
2019-02-21 14:36:16 +00:00
- class: `Rector\DoctrineCodeQuality\Rector\Property\ImproveDoctrineCollectionDocTypeInEntityRector`
2019-02-21 14:36:16 +00:00
```diff
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
2019-02-21 14:36:16 +00:00
/**
* @ORM\Entity
*/
class SomeClass
{
/**
* @ORM\OneToMany(targetEntity=Training::class, mappedBy="trainer")
- * @var Collection|Trainer[]
+ * @var Collection<int, Training>|Trainer[]
*/
private $trainings = [];
}
```
<br>
## InArgFluentChainMethodCallToStandaloneMethodCallRector
Turns fluent interface calls to classic ones.
- class: `Rector\Defluent\Rector\MethodCall\InArgFluentChainMethodCallToStandaloneMethodCallRector`
```diff
class UsedAsParameter
{
public function someFunction(FluentClass $someClass)
{
- $this->processFluentClass($someClass->someFunction()->otherFunction());
+ $someClass->someFunction();
+ $someClass->otherFunction();
+ $this->processFluentClass($someClass);
}
public function processFluentClass(FluentClass $someClass)
{
}
-}
+}
```
<br>
## InArrayAndArrayKeysToArrayKeyExistsRector
Simplify `in_array` and `array_keys` functions combination into `array_key_exists` when `array_keys` has one argument only
- class: `Rector\CodeQuality\Rector\FuncCall\InArrayAndArrayKeysToArrayKeyExistsRector`
```diff
-in_array("key", array_keys($array), true);
+array_key_exists("key", $array);
```
<br>
2020-06-30 08:46:05 +00:00
## IncreaseColumnIndexRector
Column index changed from 0 to 1 - run only ONCE! changes current value without memory
2020-06-30 08:46:05 +00:00
- class: `Rector\PHPOffice\Rector\MethodCall\IncreaseColumnIndexRector`
2020-06-30 08:46:05 +00:00
```diff
final class SomeClass
2020-06-30 08:46:05 +00:00
{
public function run(): void
{
$worksheet = new \PHPExcel_Worksheet();
- $worksheet->setCellValueByColumnAndRow(0, 3, '1150');
+ $worksheet->setCellValueByColumnAndRow(1, 3, '1150');
}
2020-06-30 08:46:05 +00:00
}
```
<br>
2020-06-30 08:46:05 +00:00
## InferParamFromClassMethodReturnRector
Change `@param` doc based on another method return type
:wrench: **configure it!**
- class: `Rector\Restoration\Rector\ClassMethod\InferParamFromClassMethodReturnRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Restoration\Rector\ClassMethod\InferParamFromClassMethodReturnRector;
use Rector\Restoration\ValueObject\InferParamFromClassMethodReturn;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(InferParamFromClassMethodReturnRector::class)
->call('configure', [[
InferParamFromClassMethodReturnRector::INFER_PARAMS_FROM_CLASS_METHOD_RETURNS => inline_value_objects([
new InferParamFromClassMethodReturn('SomeClass', 'process', 'getNodeTypes'),
]),
]]);
};
```
```diff
class SomeClass
{
public function getNodeTypes(): array
{
return [String_::class];
}
2019-04-02 13:35:35 +00:00
+ /**
+ * @param String_ $node
+ */
public function process(Node $node)
{
}
}
```
<br>
2019-11-12 07:01:15 +00:00
## InitializeDefaultEntityCollectionRector
Initialize collection property in Entity constructor
2019-11-12 07:01:15 +00:00
- class: `Rector\DoctrineCodeQuality\Rector\Class_\InitializeDefaultEntityCollectionRector`
2019-11-12 07:01:15 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeClass
2019-11-12 07:01:15 +00:00
{
/**
* @ORM\OneToMany(targetEntity="MarketingEvent")
*/
private $marketingEvents = [];
+
+ public function __construct()
+ {
+ $this->marketingEvents = new ArrayCollection();
+ }
2019-11-12 07:01:15 +00:00
}
```
<br>
## InjectAnnotationClassRector
Changes properties with specified annotations class to constructor injection
:wrench: **configure it!**
- class: `Rector\Generic\Rector\Property\InjectAnnotationClassRector`
```php
use Rector\Generic\Rector\Property\InjectAnnotationClassRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(InjectAnnotationClassRector::class)
->call('configure', [[
InjectAnnotationClassRector::ANNOTATION_CLASSES => ['DI\Annotation\Inject', 'JMS\DiExtraBundle\Annotation\Inject'],
]]);
};
```
```diff
use JMS\DiExtraBundle\Annotation as DI;
class SomeController
{
/**
- * @DI\Inject("entity.manager")
+ * @var EntityManager
*/
private $entityManager;
+
+ public function __construct(EntityManager $entityManager)
+ {
+ $this->entityManager = entityManager;
+ }
}
```
<br>
## InlineIfToExplicitIfRector
2019-04-02 13:35:35 +00:00
Change inline if to explicit if
2019-04-02 13:35:35 +00:00
- class: `Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector`
2019-04-02 13:35:35 +00:00
```diff
class SomeClass
{
public function run()
{
$userId = null;
- is_null($userId) && $userId = 5;
+ if (is_null($userId)) {
+ $userId = 5;
+ }
}
}
```
<br>
## IntvalToTypeCastRector
Change `intval()` to faster and readable (int) `$value`
- class: `Rector\CodeQuality\Rector\FuncCall\IntvalToTypeCastRector`
```diff
class SomeClass
{
public function run($value)
{
- return intval($value);
+ return (int) $value;
}
}
2019-04-02 13:35:35 +00:00
```
<br>
2019-04-02 13:35:35 +00:00
## IsAWithStringWithThirdArgumentRector
2019-04-02 13:35:35 +00:00
Complete missing 3rd argument in case `is_a()` function in case of strings
- class: `Rector\CodeQuality\Rector\FuncCall\IsAWithStringWithThirdArgumentRector`
```diff
class SomeClass
{
public function __construct(string $value)
{
- return is_a($value, 'stdClass');
+ return is_a($value, 'stdClass', true);
}
}
```
<br>
## IsCountableRector
Changes `is_array` + Countable check to `is_countable`
- class: `Rector\Php73\Rector\BinaryOp\IsCountableRector`
2019-04-02 13:35:35 +00:00
```diff
-is_array($foo) || $foo instanceof Countable;
+is_countable($foo);
2019-04-02 13:35:35 +00:00
```
<br>
2019-04-02 13:35:35 +00:00
## IsIterableRector
2019-04-02 13:35:35 +00:00
Changes `is_array` + Traversable check to `is_iterable`
- class: `Rector\Php71\Rector\BinaryOp\IsIterableRector`
```diff
-is_array($foo) || $foo instanceof Traversable;
+is_iterable($foo);
```
<br>
## IsObjectOnIncompleteClassRector
Incomplete class returns inverted bool on `is_object()`
- class: `Rector\Php72\Rector\FuncCall\IsObjectOnIncompleteClassRector`
2019-04-02 13:35:35 +00:00
```diff
$incompleteObject = new __PHP_Incomplete_Class;
-$isObject = is_object($incompleteObject);
+$isObject = ! is_object($incompleteObject);
2019-04-02 13:35:35 +00:00
```
<br>
2019-04-02 13:35:35 +00:00
## IssetOnPropertyObjectToPropertyExistsRector
Change isset on property object to `property_exists()`
- class: `Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector`
```diff
class SomeClass
{
private $x;
public function run(): void
{
- isset($this->x);
+ property_exists($this, 'x') && $this->x !== null;
}
}
```
<br>
## JoinStringConcatRector
Joins concat of 2 strings, unless the lenght is too long
- class: `Rector\CodeQuality\Rector\Concat\JoinStringConcatRector`
```diff
class SomeClass
{
public function run()
{
- $name = 'Hi' . ' Tom';
+ $name = 'Hi Tom';
}
}
```
<br>
## JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector
2019-12-26 18:35:02 +00:00
Changes `json_encode()/json_decode()` to safer and more verbose `Nette\Utils\Json::encode()/decode()` calls
- class: `Rector\Nette\Rector\FuncCall\JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector`
2019-12-26 18:35:02 +00:00
```diff
class SomeClass
2019-12-26 18:35:02 +00:00
{
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);
}
}
```
<br>
## JsonThrowOnErrorRector
Adds JSON_THROW_ON_ERROR to `json_encode()` and `json_decode()` to throw JsonException on error
- class: `Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector`
```diff
-json_encode($content);
-json_decode($json);
+json_encode($content, JSON_THROW_ON_ERROR);
+json_decode($json, null, null, JSON_THROW_ON_ERROR);
```
<br>
## ListEachRector
`each()` function is deprecated, use `key()` and `current()` instead
- class: `Rector\Php72\Rector\Assign\ListEachRector`
```diff
-list($key, $callback) = each($callbacks);
+$key = key($callbacks);
+$callback = current($callbacks);
+next($callbacks);
```
<br>
## ListSplitStringRector
`list()` cannot split string directly anymore, use `str_split()`
- class: `Rector\Php70\Rector\Assign\ListSplitStringRector`
```diff
-list($foo) = "string";
+list($foo) = str_split("string");
```
<br>
2020-05-29 10:41:25 +00:00
## ListSwapArrayOrderRector
2020-05-29 10:41:25 +00:00
`list()` assigns variables in reverse order - relevant in array assign
2020-05-29 10:41:25 +00:00
- class: `Rector\Php70\Rector\Assign\ListSwapArrayOrderRector`
2020-05-29 10:41:25 +00:00
```diff
-list($a[], $a[]) = [1, 2];
+list($a[], $a[]) = array_reverse([1, 2]);
```
<br>
2020-05-29 10:41:25 +00:00
## ListToArrayDestructRector
Remove & from new &X
2020-05-29 10:41:25 +00:00
- class: `Rector\Php71\Rector\List_\ListToArrayDestructRector`
```diff
class SomeClass
{
public function run()
2020-05-29 10:41:25 +00:00
{
- list($id1, $name1) = $data;
+ [$id1, $name1] = $data;
- foreach ($data as list($id, $name)) {
+ foreach ($data as [$id, $name]) {
}
2020-05-29 10:41:25 +00:00
}
}
```
<br>
## LocallyCalledStaticMethodToNonStaticRector
2020-05-29 10:41:25 +00:00
Change static method and local-only calls to non-static
2020-05-29 10:41:25 +00:00
- class: `Rector\RemovingStatic\Rector\ClassMethod\LocallyCalledStaticMethodToNonStaticRector`
2020-05-29 10:41:25 +00:00
```diff
class SomeClass
{
public function run()
{
- self::someStatic();
+ $this->someStatic();
}
2020-05-29 10:41:25 +00:00
- private static function someStatic()
+ private function someStatic()
{
}
}
```
<br>
2020-05-29 10:41:25 +00:00
## LoggableBehaviorRector
Change Loggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
- class: `Rector\DoctrineGedmoToKnplabs\Rector\Class_\LoggableBehaviorRector`
```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;
}
```
<br>
## LogicalToBooleanRector
Change OR, AND to ||, && with more common understanding
- class: `Rector\CodeQuality\Rector\LogicalAnd\LogicalToBooleanRector`
```diff
-if ($f = false or true) {
+if (($f = false) || true) {
return $f;
}
```
<br>
## MagicHtmlCallToAppendAttributeRector
Change magic `addClass()` etc. calls on Html to explicit methods
- class: `Rector\Nette\Rector\MethodCall\MagicHtmlCallToAppendAttributeRector`
```diff
use Nette\Utils\Html;
final class SomeClass
{
public function run()
{
$html = Html::el();
- $html->setClass('first');
+ $html->appendAttribute('class', 'first');
}
}
```
<br>
## MakeBoolPropertyRespectIsHasWasMethodNamingRector
2019-03-16 20:31:46 +00:00
Renames property to respect is/has/was method naming
- class: `Rector\Naming\Rector\Property\MakeBoolPropertyRespectIsHasWasMethodNamingRector`
```diff
class SomeClass
{
- private $full = false;
+ private $isFull = false;
public function isFull()
{
- return $this->full;
+ return $this->isFull;
}
+
}
```
<br>
## MakeCommandLazyRector
Make Symfony commands lazy
- class: `Rector\Symfony\Rector\Class_\MakeCommandLazyRector`
```diff
use Symfony\Component\Console\Command\Command
class SunshineCommand extends Command
{
+ protected static $defaultName = 'sunshine';
public function configure()
{
- $this->setName('sunshine');
}
}
```
<br>
## MakeDispatchFirstArgumentEventRector
2019-02-02 16:22:15 +00:00
Make event object a first argument of `dispatch()` method, event name as second
- class: `Rector\Symfony\Rector\MethodCall\MakeDispatchFirstArgumentEventRector`
2019-02-02 16:22:15 +00:00
```diff
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class SomeClass
{
public function run(EventDispatcherInterface $eventDispatcher)
{
- $eventDispatcher->dispatch('event_name', new Event());
+ $eventDispatcher->dispatch(new Event(), 'event_name');
}
}
```
<br>
2019-02-02 16:22:15 +00:00
## MakeEntityDateTimePropertyDateTimeInterfaceRector
Make maker bundle generate DateTime property accept DateTimeInterface too
- class: `Rector\DoctrineCodeQuality\Rector\ClassMethod\MakeEntityDateTimePropertyDateTimeInterfaceRector`
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class User
{
/**
- * @var DateTime|null
+ * @var DateTimeInterface|null
*/
private $bornAt;
public function setBornAt(DateTimeInterface $bornAt)
{
$this->bornAt = $bornAt;
}
}
```
<br>
2019-12-22 18:38:09 +00:00
## MakeEntitySetterNullabilityInSyncWithPropertyRector
Make nullability in setter class method with respect to property
- class: `Rector\DoctrineCodeQuality\Rector\ClassMethod\MakeEntitySetterNullabilityInSyncWithPropertyRector`
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class Product
{
/**
* @ORM\ManyToOne(targetEntity="AnotherEntity")
*/
private $anotherEntity;
- public function setAnotherEntity(?AnotherEntity $anotherEntity)
+ public function setAnotherEntity(AnotherEntity $anotherEntity)
{
$this->anotherEntity = $anotherEntity;
}
}
```
<br>
## MakeGetComponentAssignAnnotatedRector
Add doc type for magic `$control->getComponent(...)` assign
- class: `Rector\NetteCodeQuality\Rector\Assign\MakeGetComponentAssignAnnotatedRector`
```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>
## MakeGetterClassMethodNameStartWithGetRector
Change getter method names to start with get/provide
- class: `Rector\Naming\Rector\ClassMethod\MakeGetterClassMethodNameStartWithGetRector`
```diff
class SomeClass
{
/**
* @var string
*/
private $name;
- public function name(): string
+ public function getName(): string
{
return $this->name;
}
}
```
<br>
## MakeInheritedMethodVisibilitySameAsParentRector
Make method visibility same as parent one
- class: `Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector`
```diff
class ChildClass extends ParentClass
{
- public function run()
+ protected function run()
{
}
}
class ParentClass
{
protected function run()
{
}
}
```
<br>
## MakeIsserClassMethodNameStartWithIsRector
2019-02-18 15:51:24 +00:00
Change is method names to start with is/has/was
2019-02-18 15:51:24 +00:00
- class: `Rector\Naming\Rector\ClassMethod\MakeIsserClassMethodNameStartWithIsRector`
2019-02-18 15:51:24 +00:00
```diff
class SomeClass
2019-02-18 15:51:24 +00:00
{
/**
* @var bool
*/
private $isActive = false;
- public function getIsActive()
+ public function isActive()
{
return $this->isActive;
}
2019-02-18 15:51:24 +00:00
}
```
<br>
2019-02-18 15:51:24 +00:00
## MakeTypedPropertyNullableIfCheckedRector
2019-02-18 15:51:24 +00:00
Make typed property nullable if checked
2019-02-18 15:51:24 +00:00
- class: `Rector\Restoration\Rector\Property\MakeTypedPropertyNullableIfCheckedRector`
2019-02-18 15:51:24 +00:00
```diff
final class SomeClass
2019-02-18 15:51:24 +00:00
{
- private AnotherClass $anotherClass;
+ private ?AnotherClass $anotherClass = null;
public function run()
2019-02-18 15:51:24 +00:00
{
if ($this->anotherClass === null) {
$this->anotherClass = new AnotherClass;
}
2019-02-18 15:51:24 +00:00
}
}
```
<br>
2019-02-18 15:51:24 +00:00
## MakeUnusedClassesWithChildrenAbstractRector
2019-03-31 12:25:39 +00:00
Classes that have no children nor are used, should have abstract
2019-03-31 12:25:39 +00:00
- class: `Rector\SOLID\Rector\Class_\MakeUnusedClassesWithChildrenAbstractRector`
2019-03-31 12:25:39 +00:00
```diff
class SomeClass extends PossibleAbstractClass
{
}
2019-03-31 12:25:39 +00:00
-class PossibleAbstractClass
+abstract class PossibleAbstractClass
2019-03-31 12:25:39 +00:00
{
}
```
<br>
## ManagerRegistryGetManagerToEntityManagerRector
Changes ManagerRegistry intermediate calls directly to EntityManager calls
- class: `Rector\Doctrine\Rector\Class_\ManagerRegistryGetManagerToEntityManagerRector`
```diff
-use Doctrine\Common\Persistence\ManagerRegistry;
+use Doctrine\ORM\EntityManagerInterface;
class CustomRepository
{
/**
- * @var ManagerRegistry
+ * @var EntityManagerInterface
*/
- private $managerRegistry;
+ private $entityManager;
- public function __construct(ManagerRegistry $managerRegistry)
+ public function __construct(EntityManagerInterface $entityManager)
{
- $this->managerRegistry = $managerRegistry;
+ $this->entityManager = $entityManager;
}
public function run()
{
- $entityManager = $this->managerRegistry->getManager();
- $someRepository = $entityManager->getRepository('Some');
+ $someRepository = $this->entityManager->getRepository('Some');
}
}
```
<br>
## ManualJsonStringToJsonEncodeArrayRector
Add extra space before new assign set
- class: `Rector\CodingStyle\Rector\Assign\ManualJsonStringToJsonEncodeArrayRector`
```diff
final class SomeClass
{
public function run()
{
- $someJsonAsString = '{"role_name":"admin","numberz":{"id":"10"}}';
+ $data = [
+ 'role_name' => 'admin',
+ 'numberz' => ['id' => 10]
+ ];
+
+ $someJsonAsString = Nette\Utils\Json::encode($data);
}
}
```
<br>
## MbStrrposEncodingArgumentPositionRector
Change `mb_strrpos()` encoding argument position
- class: `Rector\Php74\Rector\FuncCall\MbStrrposEncodingArgumentPositionRector`
```diff
-mb_strrpos($text, "abc", "UTF-8");
+mb_strrpos($text, "abc", 0, "UTF-8");
```
<br>
## MergeInterfacesRector
Merges old interface to a new one, that already has its methods
:wrench: **configure it!**
- class: `Rector\Generic\Rector\Class_\MergeInterfacesRector`
```php
use Rector\Generic\Rector\Class_\MergeInterfacesRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(MergeInterfacesRector::class)
->call('configure', [[
MergeInterfacesRector::OLD_TO_NEW_INTERFACES => [
'SomeOldInterface' => SomeInterface::class,
],
]]);
};
```
```diff
-class SomeClass implements SomeInterface, SomeOldInterface
+class SomeClass implements SomeInterface
{
}
```
2020-07-24 11:46:57 +00:00
<br>
## MergeMethodAnnotationToRouteAnnotationRector
2020-07-24 11:46:57 +00:00
Merge removed `@Method` annotation to `@Route` one
- class: `Rector\Symfony\Rector\ClassMethod\MergeMethodAnnotationToRouteAnnotationRector`
```diff
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends Controller
{
/**
- * @Route("/show/{id}")
- * @Method({"GET", "HEAD"})
+ * @Route("/show/{id}", methods={"GET","HEAD"})
*/
public function show($id)
{
}
}
```
<br>
## MethodCallOnSetterMethodCallToStandaloneAssignRector
Change method call on setter to standalone assign before the setter
- class: `Rector\Defluent\Rector\MethodCall\MethodCallOnSetterMethodCallToStandaloneAssignRector`
```diff
class SomeClass
{
public function some()
{
- $this->anotherMethod(new AnotherClass())
- ->someFunction();
+ $anotherClass = new AnotherClass();
+ $anotherClass->someFunction();
+ $this->anotherMethod($anotherClass);
}
public function anotherMethod(AnotherClass $anotherClass)
{
}
}
```
<br>
## MethodCallRemoverRector
Turns `"$this->something()->anything()"` to `"$this->anything()"`
:wrench: **configure it!**
- class: `Rector\Generic\Rector\MethodCall\MethodCallRemoverRector`
```php
use Rector\Generic\Rector\MethodCall\MethodCallRemoverRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(MethodCallRemoverRector::class)
->call('configure', [[
MethodCallRemoverRector::METHOD_CALL_REMOVER_ARGUMENT => [
'$methodCallRemoverArgument' => [
'Car' => 'something',
],
],
]]);
};
```
```diff
$someObject = new Car;
-$someObject->something()->anything();
+$someObject->anything();
```
<br>
## MethodCallToAnotherMethodCallWithArgumentsRector
Turns old method call with specific types to new one with arguments
:wrench: **configure it!**
- class: `Rector\Transform\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Renaming\ValueObject\MethodCallRenameWithArrayKey;
use Rector\Transform\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(MethodCallToAnotherMethodCallWithArgumentsRector::class)
->call('configure', [[
MethodCallToAnotherMethodCallWithArgumentsRector::METHOD_CALL_RENAMES_WITH_ADDED_ARGUMENTS => inline_value_objects([
new MethodCallRenameWithArrayKey('Nette\DI\ServiceDefinition', 'setInject', 'addTag', 'inject'),
]),
]]);
};
```
```diff
$serviceDefinition = new Nette\DI\ServiceDefinition;
-$serviceDefinition->setInject();
+$serviceDefinition->addTag('inject');
```
<br>
## MethodCallToPropertyFetchRector
Turns method call `"$this->something()"` to property fetch "$this->something"
:wrench: **configure it!**
- class: `Rector\Transform\Rector\MethodCall\MethodCallToPropertyFetchRector`
```php
use Rector\Transform\Rector\MethodCall\MethodCallToPropertyFetchRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(MethodCallToPropertyFetchRector::class)
->call('configure', [[
MethodCallToPropertyFetchRector::METHOD_CALL_TO_PROPERTY_FETCHES => [
'someMethod' => 'someProperty',
],
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $this->someMethod();
+ $this->someProperty;
}
}
```
<br>
## MethodCallToReturnRector
Wrap method call to return
:wrench: **configure it!**
- class: `Rector\Generic\Rector\Expression\MethodCallToReturnRector`
```php
use Rector\Generic\Rector\Expression\MethodCallToReturnRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MethodCallToReturnRector::class)
->call('configure', [[
MethodCallToReturnRector::METHOD_CALL_WRAPS => [
'SomeClass' => ['deny'],
],
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- $this->deny();
+ return $this->deny();
}
public function deny()
{
return 1;
}
}
```
<br>
## MethodCallToStaticCallRector
Change method call to desired static call
:wrench: **configure it!**
- class: `Rector\Transform\Rector\MethodCall\MethodCallToStaticCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\MethodCall\MethodCallToStaticCallRector;
use Rector\Transform\ValueObject\MethodCallToStaticCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MethodCallToStaticCallRector::class)
->call('configure', [[
MethodCallToStaticCallRector::METHOD_CALLS_TO_STATIC_CALLS => inline_value_objects([
new MethodCallToStaticCall('AnotherDependency', 'process', 'StaticCaller', 'anotherMethod'),
]),
]]);
};
```
```diff
final class SomeClass
{
private $anotherDependency;
public function __construct(AnotherDependency $anotherDependency)
{
$this->anotherDependency = $anotherDependency;
}
public function loadConfiguration()
{
- return $this->anotherDependency->process('value');
+ return StaticCaller::anotherMethod('value');
}
}
```
<br>
## MinutesToSecondsInCacheRector
Change minutes argument to seconds in Illuminate\Contracts\Cache\Store and Illuminate\Support\Facades\Cache
- class: `Rector\Laravel\Rector\StaticCall\MinutesToSecondsInCacheRector`
```diff
class SomeClass
{
public function run()
{
- Illuminate\Support\Facades\Cache::put('key', 'value', 60);
+ Illuminate\Support\Facades\Cache::put('key', 'value', 60 * 60);
}
}
```
<br>
## MissingClassConstantReferenceToStringRector
Convert missing class reference to string
- class: `Rector\Restoration\Rector\ClassConstFetch\MissingClassConstantReferenceToStringRector`
```diff
class SomeClass
{
public function run()
{
- return NonExistingClass::class;
+ return 'NonExistingClass';
}
}
```
<br>
## MockVariableToPropertyFetchRector
Migrate PhpSpec behavior to PHPUnit test
- class: `Rector\PhpSpecToPHPUnit\Rector\Variable\MockVariableToPropertyFetchRector`
```diff
-
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
```
<br>
## MockeryCloseRemoveRector
Removes mockery close from test classes
- class: `Rector\MockeryToProphecy\Rector\StaticCall\MockeryCloseRemoveRector`
```diff
public function tearDown() : void
{
- \Mockery::close();
}
```
<br>
## MockeryCreateMockToProphizeRector
Changes mockery mock creation to Prophesize
- class: `Rector\MockeryToProphecy\Rector\ClassMethod\MockeryCreateMockToProphizeRector`
```diff
-$mock = \Mockery::mock(\'MyClass\');
+ $mock = $this->prophesize(\'MyClass\');
+
$service = new Service();
-$service->injectDependency($mock);
+$service->injectDependency($mock->reveal());
```
<br>
## MockeryTearDownRector
Add `Mockery::close()` in `tearDown()` method if not yet
- class: `Rector\MockistaToMockery\Rector\Class_\MockeryTearDownRector`
```diff
use PHPUnit\Framework\TestCase;
class SomeTest extends TestCase
{
+ protected function tearDown(): void
+ {
+ Mockery::close();
+ }
public function test()
{
$mockUser = mock(User::class);
}
}
```
<br>
## MockistaMockToMockeryMockRector
Change functions to static calls, so composer can autoload them
- class: `Rector\MockistaToMockery\Rector\ClassMethod\MockistaMockToMockeryMockRector`
```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);
}
}
```
<br>
## ModalToGetSetRector
Changes combined set/get `value()` to specific `getValue()` or `setValue(x)`.
:wrench: **configure it!**
- class: `Rector\CakePHP\Rector\MethodCall\ModalToGetSetRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\CakePHP\Rector\MethodCall\ModalToGetSetRector;
use Rector\CakePHP\ValueObject\ModalToGetSet;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ModalToGetSetRector::class)
->call('configure', [[
ModalToGetSetRector::UNPREFIXED_METHODS_TO_GET_SET => inline_value_objects([
new ModalToGetSet('InstanceConfigTrait', 'config', 'getConfig', 'setConfig', 1, null),
]),
]]);
};
```
```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']);
```
<br>
## MoveCurrentDateTimeDefaultInEntityToConstructorRector
Move default value for entity property to constructor, the safest place
- class: `Rector\DoctrineCodeQuality\Rector\Class_\MoveCurrentDateTimeDefaultInEntityToConstructorRector`
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class User
{
/**
* @var DateTimeInterface
*
- * @ORM\Column(type="datetime", nullable=false, options={"default"="now()"})
+ * @ORM\Column(type="datetime", nullable=false)
*/
- private $when = 'now()';
+ private $when;
+
+ public function __construct()
+ {
+ $this->when = new \DateTime();
+ }
}
```
<br>
## MoveEntitiesToEntityDirectoryRector
Move entities to Entity namespace
- class: `Rector\Autodiscovery\Rector\FileNode\MoveEntitiesToEntityDirectoryRector`
```diff
-// file: app/Controller/Product.php
+// file: app/Entity/Product.php
-namespace App\Controller;
+namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Product
{
}
```
<br>
## MoveFinalGetUserToCheckRequirementsClassMethodRector
Presenter method `getUser()` is now final, move logic to `checkRequirements()`
- class: `Rector\Nette\Rector\Class_\MoveFinalGetUserToCheckRequirementsClassMethodRector`
```diff
use Nette\Application\UI\Presenter;
class SomeControl extends Presenter
{
- public function getUser()
+ public function checkRequirements()
{
- $user = parent::getUser();
+ $user = $this->getUser();
$user->getStorage()->setNamespace('admin_session');
- return $user;
+
+ parent::checkRequirements();
}
}
```
<br>
## MoveInjectToExistingConstructorRector
Move `@inject` properties to constructor, if there already is one
- class: `Rector\NetteCodeQuality\Rector\Class_\MoveInjectToExistingConstructorRector`
```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>
## MoveInterfacesToContractNamespaceDirectoryRector
Move interface to "Contract" namespace
- class: `Rector\Autodiscovery\Rector\FileNode\MoveInterfacesToContractNamespaceDirectoryRector`
```diff
-// file: app/Exception/Rule.php
+// file: app/Contract/Rule.php
-namespace App\Exception;
+namespace App\Contract;
interface Rule
{
}
```
<br>
## MoveOutMethodCallInsideIfConditionRector
Move out method call inside If condition
- class: `Rector\CodeQuality\Rector\If_\MoveOutMethodCallInsideIfConditionRector`
```diff
-if ($obj->run($arg) === 1) {
+$objRun = $obj->run($arg);
+if ($objRun === 1) {
}
```
<br>
## MoveRepositoryFromParentToConstructorRector
Turns parent EntityRepository class to constructor dependency
- class: `Rector\DoctrineCodeQuality\Rector\Class_\MoveRepositoryFromParentToConstructorRector`
```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);
+ }
}
```
<br>
## MoveServicesBySuffixToDirectoryRector
Move classes by their suffix to their own group/directory
:wrench: **configure it!**
- class: `Rector\Autodiscovery\Rector\FileNode\MoveServicesBySuffixToDirectoryRector`
```php
use Rector\Autodiscovery\Rector\FileNode\MoveServicesBySuffixToDirectoryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(MoveServicesBySuffixToDirectoryRector::class)
->call('configure', [[
MoveServicesBySuffixToDirectoryRector::GROUP_NAMES_BY_SUFFIX => ['Repository'],
]]);
};
```
2019-08-05 21:10:47 +00:00
```diff
-// file: app/Entity/ProductRepository.php
+// file: app/Repository/ProductRepository.php
2019-08-05 21:10:47 +00:00
-namespace App/Entity;
+namespace App/Repository;
2019-08-05 21:10:47 +00:00
class ProductRepository
2019-08-05 21:10:47 +00:00
{
}
```
<br>
2019-10-15 14:46:31 +00:00
## MoveValueObjectsToValueObjectDirectoryRector
2019-10-15 14:46:31 +00:00
Move value object to ValueObject namespace/directory
2019-10-15 14:46:31 +00:00
:wrench: **configure it!**
- class: `Rector\Autodiscovery\Rector\FileNode\MoveValueObjectsToValueObjectDirectoryRector`
2019-10-15 14:46:31 +00:00
```php
use Rector\Autodiscovery\Rector\FileNode\MoveValueObjectsToValueObjectDirectoryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-10-15 14:46:31 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-04-01 00:05:51 +00:00
$services->set(MoveValueObjectsToValueObjectDirectoryRector::class)
->call('configure', [[
MoveValueObjectsToValueObjectDirectoryRector::TYPES => [
'ValueObjectInterfaceClassName',
],
MoveValueObjectsToValueObjectDirectoryRector::SUFFIXES => [
'Search',
],
MoveValueObjectsToValueObjectDirectoryRector::ENABLE_VALUE_OBJECT_GUESSING => true,
]]);
};
```
2020-04-01 00:05:51 +00:00
2020-04-01 00:05:51 +00:00
```diff
-// app/Exception/Name.php
+// app/ValueObject/Name.php
class Name
2020-04-01 00:05:51 +00:00
{
private $name;
public function __construct(string $name)
2020-04-01 00:05:51 +00:00
{
$this->name = $name;
}
public function getName()
{
return $this->name;
2020-04-01 00:05:51 +00:00
}
}
```
<br>
2020-04-01 00:05:51 +00:00
## MoveVariableDeclarationNearReferenceRector
Move variable declaration near its reference
- class: `Rector\SOLID\Rector\Assign\MoveVariableDeclarationNearReferenceRector`
```diff
-$var = 1;
if ($condition === null) {
+ $var = 1;
return $var;
}
```
<br>
## MultiDirnameRector
2020-08-03 22:21:59 +00:00
Changes multiple `dirname()` calls to one with nesting level
2020-08-03 22:21:59 +00:00
- class: `Rector\Php70\Rector\FuncCall\MultiDirnameRector`
2020-08-03 22:21:59 +00:00
```diff
-dirname(dirname($path));
+dirname($path, 2);
2020-08-03 22:21:59 +00:00
```
<br>
2020-08-03 22:21:59 +00:00
## MultiExceptionCatchRector
Changes multi catch of same exception to single one | separated.
- class: `Rector\Php71\Rector\TryCatch\MultiExceptionCatchRector`
```diff
try {
- // Some code...
-} catch (ExceptionType1 $exception) {
- $sameCode;
-} catch (ExceptionType2 $exception) {
- $sameCode;
+ // Some code...
+} catch (ExceptionType1 | ExceptionType2 $exception) {
+ $sameCode;
}
```
<br>
## MultiParentingToAbstractDependencyRector
2020-07-24 11:46:57 +00:00
Move dependency passed to all children to parent as `@inject/@required` dependency
:wrench: **configure it!**
- class: `Rector\SOLID\Rector\Class_\MultiParentingToAbstractDependencyRector`
```php
use Rector\SOLID\Rector\Class_\MultiParentingToAbstractDependencyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-10-21 22:26:45 +00:00
$services->set(MultiParentingToAbstractDependencyRector::class)
->call('configure', [[
MultiParentingToAbstractDependencyRector::FRAMEWORK => 'nette',
]]);
};
```
2018-10-21 22:26:45 +00:00
```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);
- }
}
2018-12-14 19:35:35 +00:00
```
<br>
2018-12-14 19:35:35 +00:00
## MultipleClassFileToPsr4ClassesRector
Change multiple classes in one file to standalone PSR-4 classes.
- class: `Rector\PSR4\Rector\Namespace_\MultipleClassFileToPsr4ClassesRector`
```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
{
}
```
<br>
## MysqlAssignToMysqliRector
2020-10-09 20:01:37 +00:00
Converts more complex mysql functions to mysqli
2020-10-09 20:01:37 +00:00
- class: `Rector\MysqlToMysqli\Rector\Assign\MysqlAssignToMysqliRector`
2020-10-09 20:01:37 +00:00
```diff
-$data = mysql_db_name($result, $row);
+mysqli_data_seek($result, $row);
+$fetch = mysql_fetch_row($result);
+$data = $fetch[0];
2020-10-09 20:01:37 +00:00
```
<br>
2020-10-09 20:01:37 +00:00
## MysqlFuncCallToMysqliRector
2018-12-14 19:35:35 +00:00
Converts more complex mysql functions to mysqli
2019-05-29 13:40:20 +00:00
- class: `Rector\MysqlToMysqli\Rector\FuncCall\MysqlFuncCallToMysqliRector`
2019-05-29 13:40:20 +00:00
```diff
-mysql_drop_db($database);
+mysqli_query('DROP DATABASE ' . $database);
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
## MysqlPConnectToMysqliConnectRector
2019-05-29 13:40:20 +00:00
Replace `mysql_pconnect()` with `mysqli_connect()` with host p: prefix
2018-12-14 19:35:35 +00:00
- class: `Rector\MysqlToMysqli\Rector\FuncCall\MysqlPConnectToMysqliConnectRector`
2018-12-14 19:35:35 +00:00
```diff
final class SomeClass
2018-12-14 19:35:35 +00:00
{
public function run($host, $username, $password)
2018-12-14 19:35:35 +00:00
{
- return mysql_pconnect($host, $username, $password);
+ return mysqli_connect('p:' . $host, $username, $password);
2019-03-16 20:31:46 +00:00
}
}
```
<br>
2019-03-16 20:31:46 +00:00
## MysqlQueryMysqlErrorWithLinkRector
2019-05-29 13:40:20 +00:00
Add mysql_query and mysql_error with connection
2019-05-29 13:40:20 +00:00
- class: `Rector\MysqlToMysqli\Rector\FuncCall\MysqlQueryMysqlErrorWithLinkRector`
2019-05-29 13:40:20 +00:00
```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);
}
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
## NameImportingPostRector
2019-03-16 20:31:46 +00:00
Imports fully qualified class names in parameter types, return types, extended classes, implemented, interfaces and even docblocks
2019-03-16 20:31:46 +00:00
- class: `Rector\PostRector\Rector\NameImportingPostRector`
2018-08-01 20:09:34 +00:00
```diff
-$someClass = new \Some\FullyQualified\SomeClass();
+use Some\FullyQualified\SomeClass;
+
+$someClass = new SomeClass();
2018-07-31 12:50:39 +00:00
```
<br>
## NetteAssertToPHPUnitAssertRector
2018-07-31 12:50:39 +00:00
Migrate Nette/Assert calls to PHPUnit
2018-07-31 12:50:39 +00:00
- class: `Rector\NetteTesterToPHPUnit\Rector\StaticCall\NetteAssertToPHPUnitAssertRector`
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
use Tester\Assert;
2018-10-12 23:15:00 +00:00
function someStaticFunctions()
{
- Assert::true(10 == 5);
+ \PHPUnit\Framework\Assert::assertTrue(10 == 5);
}
2018-10-12 23:15:00 +00:00
```
<br>
2018-07-31 12:50:39 +00:00
## NetteControlToSymfonyControllerRector
2020-07-29 08:33:10 +00:00
Migrate Nette Component to Symfony Controller
2020-07-29 08:33:10 +00:00
- class: `Rector\NetteToSymfony\Rector\Class_\NetteControlToSymfonyControllerRector`
2020-07-29 08:33:10 +00:00
```diff
-use Nette\Application\UI\Control;
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+use Symfony\Component\HttpFoundation\Response;
2020-07-29 08:33:10 +00:00
-class SomeControl extends Control
+class SomeController extends AbstractController
2020-07-29 08:33:10 +00:00
{
- public function render()
- {
- $this->template->param = 'some value';
- $this->template->render(__DIR__ . '/poll.latte');
- }
+ public function some(): Response
+ {
+ return $this->render(__DIR__ . '/poll.latte', ['param' => 'some value']);
+ }
2020-07-29 08:33:10 +00:00
}
```
<br>
2020-07-29 08:33:10 +00:00
## NetteFormToSymfonyFormRector
2018-10-12 23:15:00 +00:00
Migrate Nette\Forms in Presenter to Symfony
- class: `Rector\NetteToSymfony\Rector\MethodCall\NetteFormToSymfonyFormRector`
```diff
use Nette\Application\UI;
class SomePresenter extends UI\Presenter
{
public function someAction()
{
- $form = new UI\Form;
- $form->addText('name', 'Name:');
- $form->addPassword('password', 'Password:');
- $form->addSubmit('login', 'Sign up');
+ $form = $this->createFormBuilder();
+ $form->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class, [
+ 'label' => 'Name:'
+ ]);
+ $form->add('password', \Symfony\Component\Form\Extension\Core\Type\PasswordType::class, [
+ 'label' => 'Password:'
+ ]);
+ $form->add('login', \Symfony\Component\Form\Extension\Core\Type\SubmitType::class, [
+ 'label' => 'Sign up'
+ ]);
}
}
```
<br>
## NetteTesterClassToPHPUnitClassRector
Migrate Nette Tester test case to PHPUnit
- class: `Rector\NetteTesterToPHPUnit\Rector\Class_\NetteTesterClassToPHPUnitClassRector`
```diff
namespace KdybyTests\Doctrine;
use Tester\TestCase;
use Tester\Assert;
-require_once __DIR__ . '/../bootstrap.php';
-
-class ExtensionTest extends TestCase
+class ExtensionTest extends \PHPUnit\Framework\TestCase
{
public function testFunctionality()
{
- Assert::true($default instanceof Kdyby\Doctrine\EntityManager);
- Assert::true(5);
- Assert::same($container->getService('kdyby.doctrine.default.entityManager'), $default);
+ $this->assertInstanceOf(\Kdyby\Doctrine\EntityManager::cllass, $default);
+ $this->assertTrue(5);
+ $this->same($container->getService('kdyby.doctrine.default.entityManager'), $default);
}
-}
-
-(new \ExtensionTest())->run();
+}
```
<br>
## NewApplicationToToFactoryWithDefaultContainerRector
Change new application to default factory with application
2018-10-12 23:15:00 +00:00
- class: `Rector\Phalcon\Rector\Assign\NewApplicationToToFactoryWithDefaultContainerRector`
2018-10-12 23:15:00 +00:00
```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"]);
}
}
```
2018-10-12 23:15:00 +00:00
<br>
2018-10-21 22:26:45 +00:00
## NewFluentChainMethodCallToNonFluentRector
Turns fluent interface calls to classic ones.
- class: `Rector\Defluent\Rector\MethodCall\NewFluentChainMethodCallToNonFluentRector`
2018-10-12 23:15:00 +00:00
```diff
-(new SomeClass())->someFunction()
- ->otherFunction();
+$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
2018-10-12 23:15:00 +00:00
```
<br>
## NewObjectToFactoryCreateRector
2018-10-12 23:15:00 +00:00
Replaces creating object instances with "new" keyword with factory method.
2018-10-12 23:15:00 +00:00
:wrench: **configure it!**
2018-10-12 23:15:00 +00:00
- class: `Rector\Generic\Rector\New_\NewObjectToFactoryCreateRector`
2018-10-12 23:15:00 +00:00
```php
use Rector\Generic\Rector\New_\NewObjectToFactoryCreateRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewObjectToFactoryCreateRector::class)
->call('configure', [[
NewObjectToFactoryCreateRector::OBJECT_TO_FACTORY_METHOD => [
'MyClass' => [
'class' => 'MyClassFactory',
'method' => 'create',
],
],
]]);
};
2018-10-12 23:15:00 +00:00
```
2018-10-12 23:15:00 +00:00
```diff
class SomeClass
{
+ /**
+ * @var \MyClassFactory
+ */
+ private $myClassFactory;
+
public function example() {
- new MyClass($argument);
+ $this->myClassFactory->create($argument);
}
}
2018-10-12 23:15:00 +00:00
```
<br>
2018-10-12 23:15:00 +00:00
## NewStaticToNewSelfRector
Change unsafe new `static()` to new `self()`
2018-10-12 23:15:00 +00:00
- class: `Rector\CodeQuality\Rector\New_\NewStaticToNewSelfRector`
2018-10-12 23:15:00 +00:00
```diff
class SomeClass
{
public function build()
{
- return new static();
+ return new self();
}
}
```
<br>
## NewToStaticCallRector
Change new Object to static call
:wrench: **configure it!**
- class: `Rector\Transform\Rector\New_\NewToStaticCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\New_\NewToStaticCallRector;
use Rector\Transform\ValueObject\NewToStaticCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewToStaticCallRector::class)
->call('configure', [[
NewToStaticCallRector::TYPE_TO_STATIC_CALLS => inline_value_objects([new NewToStaticCall('Cookie', 'Cookie', 'create')]),
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- new Cookie($name);
+ Cookie::create($name);
}
}
2018-10-12 23:15:00 +00:00
```
<br>
2020-03-23 16:13:04 +00:00
## NewUniqueObjectToEntityFactoryRector
2020-03-23 16:13:04 +00:00
Convert new X to new factories
2020-03-23 16:13:04 +00:00
:wrench: **configure it!**
2020-03-23 16:13:04 +00:00
- class: `Rector\RemovingStatic\Rector\Class_\NewUniqueObjectToEntityFactoryRector`
2020-03-23 16:13:04 +00:00
```php
use Rector\RemovingStatic\Rector\Class_\NewUniqueObjectToEntityFactoryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-03-23 16:13:04 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-10-12 23:15:00 +00:00
$services->set(NewUniqueObjectToEntityFactoryRector::class)
->call('configure', [[
NewUniqueObjectToEntityFactoryRector::TYPES_TO_SERVICES => ['ClassName'],
]]);
};
```
2018-10-12 23:15:00 +00:00
2019-05-29 13:40:20 +00:00
```diff
-<?php
-
class SomeClass
{
+ public function __construct(AnotherClassFactory $anotherClassFactory)
+ {
+ $this->anotherClassFactory = $anotherClassFactory;
+ }
+
public function run()
{
- return new AnotherClass;
+ return $this->anotherClassFactory->create();
}
}
2019-10-15 14:46:31 +00:00
class AnotherClass
2019-10-15 14:46:31 +00:00
{
public function someFun()
{
return StaticClass::staticMethod();
}
2019-10-15 14:46:31 +00:00
}
```
<br>
2019-10-15 14:46:31 +00:00
## NewlineBeforeNewAssignSetRector
2018-10-12 23:15:00 +00:00
Add extra space before new assign set
2018-10-12 23:15:00 +00:00
- class: `Rector\CodingStyle\Rector\ClassMethod\NewlineBeforeNewAssignSetRector`
2019-05-29 13:40:20 +00:00
```diff
final class SomeClass
{
public function run()
{
$value = new Value;
$value->setValue(5);
+
$value2 = new Value;
$value2->setValue(1);
}
}
```
<br>
## NodeAddingPostRector
Post Rector that adds nodes
- class: `Rector\PostRector\Rector\NodeAddingPostRector`
```diff
+$string = new String_(...);
$value = 1000;
```
<br>
## NodeRemovingRector
2018-10-12 23:15:00 +00:00
PostRector that removes nodes
2018-10-12 23:15:00 +00:00
- class: `Rector\PostRector\Rector\NodeRemovingRector`
2018-10-12 23:15:00 +00:00
```diff
-$value = 1000;
-$string = new String_(...);
+$value = 1000;
2018-10-12 23:15:00 +00:00
```
<br>
2018-10-23 18:58:57 +00:00
## NodeToReplacePostRector
2019-10-15 14:46:31 +00:00
Post Rector that replaces one nodes with another
2019-10-15 14:46:31 +00:00
- class: `Rector\PostRector\Rector\NodeToReplacePostRector`
2019-10-15 14:46:31 +00:00
```diff
-$string = new String_(...);
+$value = 1000;
2019-10-15 14:46:31 +00:00
```
<br>
## NonVariableToVariableOnFunctionCallRector
Transform non variable like arguments to variable where a function or method expects an argument passed by reference
- class: `Rector\Php70\Rector\FuncCall\NonVariableToVariableOnFunctionCallRector`
```diff
-reset(a());
+$a = a(); reset($a);
```
<br>
2019-05-29 13:40:20 +00:00
## NormalToFluentRector
2019-05-29 13:40:20 +00:00
Turns fluent interface calls to classic ones.
2019-05-29 13:40:20 +00:00
:wrench: **configure it!**
2019-05-29 13:40:20 +00:00
- class: `Rector\Generic\Rector\ClassMethod\NormalToFluentRector`
2019-03-31 12:25:39 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassMethod\NormalToFluentRector;
use Rector\Generic\ValueObject\NormalToFluent;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-05-29 13:40:20 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-29 13:40:20 +00:00
$services->set(NormalToFluentRector::class)
->call('configure', [[
NormalToFluentRector::CALLS_TO_FLUENT => inline_value_objects([
new NormalToFluent('SomeClass', ['someFunction', 'otherFunction']), ]
),
]]);
};
```
2019-05-29 13:40:20 +00:00
2019-05-29 13:40:20 +00:00
```diff
$someObject = new SomeClass();
-$someObject->someFunction();
-$someObject->otherFunction();
+$someObject->someFunction()
+ ->otherFunction();
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
## NormalizeNamespaceByPSR4ComposerAutoloadRector
Adds namespace to namespace-less files or correct namespace to match PSR-4 in `composer.json` autoload section. Run with combination with `Rector\PSR4\Rector\Namespace_\MultipleClassFileToPsr4ClassesRector`
- class: `Rector\PSR4\Rector\FileWithoutNamespace\NormalizeNamespaceByPSR4ComposerAutoloadRector`
- with `composer.json`:
```json
{
"autoload": {
"psr-4": {
"App\\CustomNamespace\\": "src"
}
}
}
```
```diff
// src/SomeClass.php
+namespace App\CustomNamespace;
+
class SomeClass
{
}
2018-10-12 23:15:00 +00:00
```
<br>
## NullCoalescingOperatorRector
2019-01-22 20:34:38 +00:00
Use null coalescing operator ??=
2019-01-22 20:34:38 +00:00
- class: `Rector\Php74\Rector\Assign\NullCoalescingOperatorRector`
2019-01-22 20:34:38 +00:00
```diff
$array = [];
-$array['user_id'] = $array['user_id'] ?? 'value';
+$array['user_id'] ??= 'value';
2019-01-22 20:34:38 +00:00
```
<br>
2019-01-22 20:34:38 +00:00
## NullableCompareToNullRector
Changes negate of empty comparison of nullable value to explicit === or !== compare
- class: `Rector\CodingStyle\Rector\If_\NullableCompareToNullRector`
```diff
/** @var stdClass|null $value */
-if ($value) {
+if ($value !== null) {
}
-if (!$value) {
+if ($value === null) {
}
```
<br>
## NullsafeOperatorRector
2018-12-14 19:35:35 +00:00
Change if null check with nullsafe operator ?-> with full short circuiting
2018-12-14 19:35:35 +00:00
- class: `Rector\Php80\Rector\If_\NullsafeOperatorRector`
2018-12-14 19:35:35 +00:00
```diff
class SomeClass
{
public function f($o)
{
- $o2 = $o->mayFail1();
- if ($o2 === null) {
- return null;
- }
-
- return $o2->mayFail2();
+ return $o->mayFail1()?->mayFail2();
}
}
2018-12-14 19:35:35 +00:00
```
<br>
2018-10-12 23:15:00 +00:00
## OptionNameRector
2018-10-12 23:15:00 +00:00
Turns old option names to new ones in FormTypes in Form in Symfony
2018-10-12 23:15:00 +00:00
- class: `Rector\Symfony\Rector\MethodCall\OptionNameRector`
2019-05-29 13:40:20 +00:00
```diff
$builder = new FormBuilder;
-$builder->add("...", ["precision" => "...", "virtual" => "..."];
+$builder->add("...", ["scale" => "...", "inherit_data" => "..."];
2018-10-12 23:15:00 +00:00
```
<br>
2018-10-12 23:15:00 +00:00
## OrderClassConstantsByIntegerValueRector
Order class constant order by their integer value
2018-10-12 23:15:00 +00:00
- class: `Rector\Order\Rector\Class_\OrderClassConstantsByIntegerValueRector`
2018-10-12 23:15:00 +00:00
```diff
class SomeClass
{
const MODE_ON = 0;
+ const MODE_MAYBE = 1;
+
const MODE_OFF = 2;
-
- const MODE_MAYBE = 1;
}
2018-10-12 23:15:00 +00:00
```
<br>
## OrderConstantsByVisibilityRector
Orders constants by visibility
- class: `Rector\Order\Rector\Class_\OrderConstantsByVisibilityRector`
```diff
final class SomeClass
{
+ public const PUBLIC_CONST = 'public';
+ protected const PROTECTED_CONST = 'protected';
private const PRIVATE_CONST = 'private';
- protected const PROTECTED_CONST = 'protected';
- public const PUBLIC_CONST = 'public';
}
```
<br>
## OrderConstructorDependenciesByTypeAlphabeticallyRector
2018-07-31 12:50:39 +00:00
Order __constructor dependencies by type A-Z
:wrench: **configure it!**
- class: `Rector\Order\Rector\ClassMethod\OrderConstructorDependenciesByTypeAlphabeticallyRector`
```php
use Rector\Order\Rector\ClassMethod\OrderConstructorDependenciesByTypeAlphabeticallyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(OrderConstructorDependenciesByTypeAlphabeticallyRector::class)
->call('configure', [[
OrderConstructorDependenciesByTypeAlphabeticallyRector::SKIP_PATTERNS => ['Cla*ame', 'Ano?herClassName'],
]]);
};
```
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
public function __construct(
+ LatteAndTwigFinder $latteAndTwigFinder,
LatteToTwigConverter $latteToTwigConverter,
- SymfonyStyle $symfonyStyle,
- LatteAndTwigFinder $latteAndTwigFinder,
- SmartFileSystem $smartFileSystem
+ SmartFileSystem $smartFileSystem,
+ SymfonyStyle $symfonyStyle
) {
}
}
2018-07-31 12:50:39 +00:00
```
<br>
## OrderFirstLevelClassStatementsRector
Orders first level Class statements
- class: `Rector\Order\Rector\Class_\OrderFirstLevelClassStatementsRector`
```diff
final class SomeClass
{
+ use TraitName;
+ private const CONST_NAME = 'constant_value';
+ protected $propertyName;
public function functionName();
- protected $propertyName;
- private const CONST_NAME = 'constant_value';
- use TraitName;
}
```
<br>
## OrderMethodsByVisibilityRector
Orders method by visibility
- class: `Rector\Order\Rector\Class_\OrderMethodsByVisibilityRector`
```diff
class SomeClass
{
+ public function publicFunctionName();
protected function protectedFunctionName();
private function privateFunctionName();
- public function publicFunctionName();
}
```
<br>
2019-11-06 23:52:19 +00:00
## OrderPrivateMethodsByUseRector
2019-11-06 23:52:19 +00:00
Order private methods in order of their use
2019-11-06 23:52:19 +00:00
- class: `Rector\Order\Rector\Class_\OrderPrivateMethodsByUseRector`
2019-11-06 23:52:19 +00:00
```diff
class SomeClass
{
public function run()
2019-11-06 23:52:19 +00:00
{
$this->call1();
$this->call2();
2019-11-06 23:52:19 +00:00
}
- private function call2()
+ private function call1()
2019-11-06 23:52:19 +00:00
{
}
2019-08-05 21:10:47 +00:00
- private function call1()
+ private function call2()
2019-08-05 21:10:47 +00:00
{
}
}
```
<br>
## OrderPropertiesByVisibilityRector
Orders properties by visibility
- class: `Rector\Order\Rector\Class_\OrderPropertiesByVisibilityRector`
```diff
final class SomeClass
{
+ public $publicProperty;
protected $protectedProperty;
private $privateProperty;
- public $publicProperty;
}
```
<br>
## OrderPropertyByComplexityRector
Order properties by complexity, from the simplest like scalars to the most complex, like union or collections
- class: `Rector\Order\Rector\Class_\OrderPropertyByComplexityRector`
```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;
}
```
<br>
## OrderPublicInterfaceMethodRector
Order public methods required by interface in custom orderer
:wrench: **configure it!**
- class: `Rector\Order\Rector\Class_\OrderPublicInterfaceMethodRector`
```php
use Rector\Order\Rector\Class_\OrderPublicInterfaceMethodRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(OrderPublicInterfaceMethodRector::class)
->call('configure', [[
OrderPublicInterfaceMethodRector::METHOD_ORDER_BY_INTERFACES => [
'FoodRecipeInterface' => ['getDescription', 'process'],
],
]]);
};
```
2019-12-18 09:53:46 +00:00
```diff
class SomeClass implements FoodRecipeInterface
{
- public function process()
+ public function getDescription()
{
}
-
- public function getDescription()
+ public function process()
2019-12-18 09:53:46 +00:00
{
}
}
```
<br>
2019-12-18 09:53:46 +00:00
## PHPStormVarAnnotationRector
2019-12-18 09:53:46 +00:00
Change various `@var` annotation formats to one PHPStorm understands
2019-12-18 09:53:46 +00:00
- class: `Rector\PHPStan\Rector\Assign\PHPStormVarAnnotationRector`
2019-12-18 09:53:46 +00:00
```diff
-$config = 5;
-/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+$config = 5;
2019-12-18 09:53:46 +00:00
```
<br>
2019-12-18 09:53:46 +00:00
## PHPUnitStaticToKernelTestCaseGetRector
Convert static calls in PHPUnit test cases, to `get()` from the container of KernelTestCase
2019-01-22 20:34:38 +00:00
:wrench: **configure it!**
2019-01-22 20:34:38 +00:00
- class: `Rector\RemovingStatic\Rector\Class_\PHPUnitStaticToKernelTestCaseGetRector`
2019-01-22 20:34:38 +00:00
```php
use Rector\RemovingStatic\Rector\Class_\PHPUnitStaticToKernelTestCaseGetRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-01-22 20:34:38 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-08-24 11:08:59 +00:00
$services->set(PHPUnitStaticToKernelTestCaseGetRector::class)
->call('configure', [[
PHPUnitStaticToKernelTestCaseGetRector::STATIC_CLASS_TYPES => ['EntityFactory'],
]]);
};
```
2019-08-24 11:08:59 +00:00
2019-08-24 11:08:59 +00:00
```diff
-<?php
+use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
-use PHPUnit\Framework\TestCase;
+final class SomeTestCase extends KernelTestCase
+{
+ /**
+ * @var EntityFactory
+ */
+ private $entityFactory;
-final class SomeTestCase extends TestCase
-{
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->entityFactory = self::$container->get(EntityFactory::class);
+ }
+
public function test()
{
- $product = EntityFactory::create('product');
+ $product = $this->entityFactory->create('product');
}
2019-08-24 11:08:59 +00:00
}
```
<br>
2019-08-24 11:08:59 +00:00
## ParamTypeDeclarationRector
2020-05-31 15:26:08 +00:00
Change `@param` types to type declarations if not a BC-break
2020-05-31 15:26:08 +00:00
- class: `Rector\TypeDeclaration\Rector\FunctionLike\ParamTypeDeclarationRector`
2020-05-31 15:26:08 +00:00
```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)
{
}
}
```
<br>
## ParentClassToTraitsRector
2020-05-31 15:45:51 +00:00
Replaces parent class to specific traits
2020-05-31 15:45:51 +00:00
:wrench: **configure it!**
2020-05-31 15:45:51 +00:00
- class: `Rector\Generic\Rector\Class_\ParentClassToTraitsRector`
2020-05-31 15:45:51 +00:00
```php
use Rector\Generic\Rector\Class_\ParentClassToTraitsRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-05-31 15:45:51 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-07-31 12:50:39 +00:00
$services->set(ParentClassToTraitsRector::class)
->call('configure', [[
ParentClassToTraitsRector::PARENT_CLASS_TO_TRAITS => [
'Nette\Object' => ['Nette\SmartObject'],
],
]]);
};
```
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
-class SomeClass extends Nette\Object
+class SomeClass
2019-09-25 08:49:53 +00:00
{
+ use Nette\SmartObject;
2018-10-12 23:15:00 +00:00
}
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
## ParseFileRector
2018-12-31 11:50:32 +00:00
session > use_strict_mode is true by default and can be removed
2018-12-31 11:50:32 +00:00
- class: `Rector\Symfony\Rector\StaticCall\ParseFileRector`
```diff
-session > use_strict_mode: true
+session:
```
<br>
## ParseStrWithResultArgumentRector
Use `$result` argument in `parse_str()` function
- class: `Rector\Php72\Rector\FuncCall\ParseStrWithResultArgumentRector`
```diff
-parse_str($this->query);
-$data = get_defined_vars();
+parse_str($this->query, $result);
+$data = $result;
```
<br>
2019-02-21 14:36:16 +00:00
## PassFactoryToUniqueObjectRector
2019-02-21 14:36:16 +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
:wrench: **configure it!**
2019-02-21 14:36:16 +00:00
- class: `Rector\RemovingStatic\Rector\Class_\PassFactoryToUniqueObjectRector`
2019-05-01 23:56:58 +00:00
```php
use Rector\RemovingStatic\Rector\Class_\PassFactoryToUniqueObjectRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-05-01 23:56:58 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PassFactoryToUniqueObjectRector::class)
->call('configure', [[
PassFactoryToUniqueObjectRector::TYPES_TO_SERVICES => ['StaticClass'],
]]);
};
```
```diff
-<?php
-
class SomeClass
{
+ public function __construct(AnotherClassFactory $anotherClassFactory)
+ {
+ $this->anotherClassFactory = $anotherClassFactory;
+ }
+
public function run()
{
- return new AnotherClass;
+ return $this->anotherClassFactory->create();
}
}
2019-09-25 08:49:53 +00:00
class AnotherClass
{
+ public function __construct(StaticClass $staticClass)
+ {
+ $this->staticClass = $staticClass;
+ }
+
public function someFun()
{
- return StaticClass::staticMethod();
+ return $this->staticClass->staticMethod();
+ }
+}
+
+final class AnotherClassFactory
+{
+ /**
+ * @var StaticClass
+ */
+ private $staticClass;
+
+ public function __construct(StaticClass $staticClass)
+ {
+ $this->staticClass = $staticClass;
+ }
+
+ public function create(): AnotherClass
+ {
+ return new AnotherClass($this->staticClass);
}
}
```
<br>
## Php4ConstructorRector
Changes PHP 4 style constructor to __construct.
2019-09-25 08:49:53 +00:00
- class: `Rector\Php70\Rector\ClassMethod\Php4ConstructorRector`
```diff
2019-09-25 08:49:53 +00:00
class SomeClass
{
- public function SomeClass()
+ public function __construct()
2019-09-25 08:49:53 +00:00
{
}
}
```
<br>
## PhpSpecClassToPHPUnitClassRector
2019-02-21 14:36:16 +00:00
Migrate PhpSpec behavior to PHPUnit test
- class: `Rector\PhpSpecToPHPUnit\Rector\Class_\PhpSpecClassToPHPUnitClassRector`
2019-02-21 14:36:16 +00:00
```diff
-
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
```
<br>
## PhpSpecMethodToPHPUnitMethodRector
2019-05-29 13:40:20 +00:00
Migrate PhpSpec behavior to PHPUnit test
2019-05-29 13:40:20 +00:00
- class: `Rector\PhpSpecToPHPUnit\Rector\ClassMethod\PhpSpecMethodToPHPUnitMethodRector`
```diff
-
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
```
<br>
## PhpSpecMocksToPHPUnitMocksRector
Migrate PhpSpec behavior to PHPUnit test
- class: `Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecMocksToPHPUnitMocksRector`
```diff
-
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
```
<br>
## PhpSpecPromisesToPHPUnitAssertRector
Migrate PhpSpec behavior to PHPUnit test
- class: `Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecPromisesToPHPUnitAssertRector`
2019-03-09 13:24:30 +00:00
```diff
-
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod): void
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
2019-03-09 13:24:30 +00:00
```
<br>
2019-03-09 13:24:30 +00:00
## PowToExpRector
Changes pow(val, val2) to ** `(exp)` parameter
- class: `Rector\Php56\Rector\FuncCall\PowToExpRector`
```diff
-pow(1, 2);
+1**2;
```
<br>
## PreferThisOrSelfMethodCallRector
2018-12-31 11:50:32 +00:00
Changes `$this->...` to self:: or vise versa for specific types
2018-12-31 11:50:32 +00:00
:wrench: **configure it!**
2018-12-31 11:50:32 +00:00
- class: `Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector`
```php
use PHPUnit\Framework\TestCase;
use Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-09-25 08:49:53 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-09-25 08:49:53 +00:00
$services->set(PreferThisOrSelfMethodCallRector::class)
->call('configure', [[
PreferThisOrSelfMethodCallRector::TYPE_TO_PREFERENCE => [
TestCase::class => 'self',
],
]]);
};
```
2019-09-25 08:49:53 +00:00
2019-09-25 08:49:53 +00:00
```diff
class SomeClass extends \PHPUnit\Framework\TestCase
2019-09-25 08:49:53 +00:00
{
public function run()
{
- $this->assertEquals('a', 'a');
+ self::assertEquals('a', 'a');
}
}
2018-12-31 11:50:32 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
## PregFunctionToNetteUtilsStringsRector
Use `Nette\Utils\Strings` over bare `preg_split()` and `preg_replace()` functions
- class: `Rector\Nette\Rector\FuncCall\PregFunctionToNetteUtilsStringsRector`
```diff
+use Nette\Utils\Strings;
+
class SomeClass
{
public function run()
{
$content = 'Hi my name is Tom';
- $splitted = preg_split('#Hi#', $content);
+ $splitted = \Nette\Utils\Strings::split($content, '#Hi#');
}
}
```
<br>
## PregMatchFunctionToNetteUtilsStringsRector
2019-09-25 08:49:53 +00:00
Use `Nette\Utils\Strings` over bare `preg_match()` and `preg_match_all()` functions
2019-09-25 08:49:53 +00:00
- class: `Rector\Nette\Rector\FuncCall\PregMatchFunctionToNetteUtilsStringsRector`
2019-09-25 08:49:53 +00:00
```diff
+use Nette\Utils\Strings;
+
class SomeClass
{
public function run()
{
$content = 'Hi my name is Tom';
- preg_match('#Hi#', $content, $matches);
+ $matches = Strings::match($content, '#Hi#');
}
}
2018-10-21 22:26:45 +00:00
```
<br>
2018-10-21 22:26:45 +00:00
## PregReplaceEModifierRector
2018-10-21 22:26:45 +00:00
The /e modifier is no longer supported, use `preg_replace_callback` instead
2018-10-21 22:26:45 +00:00
- class: `Rector\Php55\Rector\FuncCall\PregReplaceEModifierRector`
2018-10-21 22:26:45 +00:00
2018-10-23 18:58:57 +00:00
```diff
class SomeClass
{
public function run()
{
- $comment = preg_replace('~\b(\w)(\w+)~e', '"$1".strtolower("$2")', $comment);
+ $comment = preg_replace_callback('~\b(\w)(\w+)~', function ($matches) {
+ return($matches[1].strtolower($matches[2]));
+ }, , $comment);
}
}
2018-10-23 18:58:57 +00:00
```
2018-10-21 22:26:45 +00:00
<br>
2018-10-21 22:26:45 +00:00
## PreslashSimpleFunctionRector
Add pre-slash to short named functions to improve performance
- class: `Rector\Performance\Rector\FuncCall\PreslashSimpleFunctionRector`
```diff
class SomeClass
{
public function shorten($value)
{
- return trim($value);
+ return \trim($value);
}
}
```
<br>
## PrivatizeFinalClassMethodRector
Change protected class method to private if possible
- class: `Rector\Privatization\Rector\ClassMethod\PrivatizeFinalClassMethodRector`
```diff
final class SomeClass
{
- protected function someMethod()
+ private function someMethod()
{
}
}
```
<br>
## PrivatizeFinalClassPropertyRector
2019-02-21 14:36:16 +00:00
Change property to private if possible
2019-02-21 14:36:16 +00:00
- class: `Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector`
2019-02-21 14:36:16 +00:00
```diff
final class SomeClass
{
- protected $value;
+ private $value;
}
```
<br>
## PrivatizeLocalClassConstantRector
Finalize every class constant that is used only locally
- class: `Rector\Privatization\Rector\ClassConst\PrivatizeLocalClassConstantRector`
```diff
class ClassWithConstantUsedOnlyHere
{
- const LOCAL_ONLY = true;
+ private const LOCAL_ONLY = true;
public function isLocalOnly()
{
return self::LOCAL_ONLY;
}
}
```
<br>
## PrivatizeLocalGetterToPropertyRector
Privatize getter of local property to property
- class: `Rector\Privatization\Rector\MethodCall\PrivatizeLocalGetterToPropertyRector`
```diff
class SomeClass
{
private $some;
public function run()
{
- return $this->getSome() + 5;
+ return $this->some + 5;
}
private function getSome()
{
return $this->some;
}
}
2019-02-21 14:36:16 +00:00
```
<br>
2019-02-21 14:36:16 +00:00
## PrivatizeLocalOnlyMethodRector
2018-12-31 11:50:32 +00:00
Privatize local-only use methods
2018-12-31 11:50:32 +00:00
- class: `Rector\Privatization\Rector\ClassMethod\PrivatizeLocalOnlyMethodRector`
2018-12-31 11:50:32 +00:00
```diff
class SomeClass
{
/**
* @api
*/
public function run()
{
return $this->useMe();
}
- public function useMe()
+ private function useMe()
{
}
}
2018-12-31 11:50:32 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
## PrivatizeLocalPropertyToPrivatePropertyRector
Privatize local-only property to private property
- class: `Rector\Privatization\Rector\Property\PrivatizeLocalPropertyToPrivatePropertyRector`
```diff
class SomeClass
{
- public $value;
+ private $value;
public function run()
{
return $this->value;
}
}
```
<br>
## ProcessBuilderGetProcessRector
2019-05-29 13:40:20 +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
- class: `Rector\Symfony\Rector\MethodCall\ProcessBuilderGetProcessRector`
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();
```
<br>
## ProcessBuilderInstanceRector
2019-05-29 13:40:20 +00:00
Turns `ProcessBuilder::instance()` to new ProcessBuilder in Process in Symfony. Part of multi-step Rector.
2019-05-29 13:40:20 +00:00
- class: `Rector\Symfony\Rector\StaticCall\ProcessBuilderInstanceRector`
2019-09-25 08:49:53 +00:00
```diff
-$processBuilder = Symfony\Component\Process\ProcessBuilder::instance($args);
+$processBuilder = new Symfony\Component\Process\ProcessBuilder($args);
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
## PropertyAddingPostRector
2019-05-19 08:27:38 +00:00
Post Rector that adds properties
2019-05-19 08:27:38 +00:00
- class: `Rector\PostRector\Rector\PropertyAddingPostRector`
2019-05-19 08:27:38 +00:00
```diff
class SomeClass
{
+ public $someProperty;
}
2019-05-19 08:27:38 +00:00
```
<br>
## PropertyAssignToMethodCallRector
2019-05-19 08:27:38 +00:00
Turns property assign of specific type and property name to method call
2018-10-23 18:58:57 +00:00
:wrench: **configure it!**
- class: `Rector\Transform\Rector\Assign\PropertyAssignToMethodCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\Assign\PropertyAssignToMethodCallRector;
use Rector\Transform\ValueObject\PropertyAssignToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PropertyAssignToMethodCallRector::class)
->call('configure', [[
PropertyAssignToMethodCallRector::PROPERTY_ASSIGNS_TO_METHODS_CALLS => inline_value_objects([
new PropertyAssignToMethodCall('SomeClass', 'oldProperty', 'newMethodCall'),
]),
]]);
};
```
2018-10-21 22:26:45 +00:00
```diff
$someObject = new SomeClass;
-$someObject->oldProperty = false;
+$someObject->newMethodCall(false);
2018-08-01 20:09:34 +00:00
```
2018-07-31 12:50:39 +00:00
<br>
## PropertyToMethodRector
Replaces properties assign calls be defined methods.
:wrench: **configure it!**
- class: `Rector\Transform\Rector\Assign\PropertyToMethodRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\Assign\PropertyToMethodRector;
use Rector\Transform\ValueObject\PropertyToMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PropertyToMethodRector::class)
->call('configure', [[
PropertyToMethodRector::PROPERTIES_TO_METHOD_CALLS => inline_value_objects([
new PropertyToMethod('SomeObject', 'property', 'getProperty', [], 'setProperty'),
]),
]]);
};
```
```diff
-$result = $object->property;
-$object->property = $value;
+$result = $object->getProperty();
+$object->setProperty($value);
```
<br>
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\Assign\PropertyToMethodRector;
use Rector\Transform\ValueObject\PropertyToMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2018-07-31 12:50:39 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-07-31 12:50:39 +00:00
$services->set(PropertyToMethodRector::class)
->call('configure', [[
PropertyToMethodRector::PROPERTIES_TO_METHOD_CALLS => inline_value_objects([
new PropertyToMethod('SomeObject', 'property', 'getConfig', ['someArg'], null),
]),
]]);
};
2018-07-31 12:50:39 +00:00
```
```diff
-$result = $object->property;
+$result = $object->getProperty('someArg');
```
<br>
## PropertyTypeDeclarationRector
Add `@var` to properties that are missing it
2018-07-31 12:50:39 +00:00
- class: `Rector\TypeDeclaration\Rector\Property\PropertyTypeDeclarationRector`
2018-07-31 12:50:39 +00:00
```diff
class SomeClass
{
+ /**
+ * @var int
+ */
private $value;
public function run()
{
$this->value = 123;
}
}
2018-08-01 20:09:34 +00:00
```
<br>
2018-10-12 23:15:00 +00:00
## PseudoNamespaceToNamespaceRector
2018-07-31 12:50:39 +00:00
Replaces defined Pseudo_Namespaces by Namespace\Ones.
:wrench: **configure it!**
2019-03-09 13:24:30 +00:00
- class: `Rector\Renaming\Rector\FileWithoutNamespace\PseudoNamespaceToNamespaceRector`
2019-09-25 08:49:53 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\ValueObject\PseudoNamespaceToNamespace;
use Rector\Renaming\Rector\FileWithoutNamespace\PseudoNamespaceToNamespaceRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-03-09 13:24:30 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(PseudoNamespaceToNamespaceRector::class)
->call('configure', [[
PseudoNamespaceToNamespaceRector::NAMESPACE_PREFIXES_WITH_EXCLUDED_CLASSES => inline_value_objects([
new PseudoNamespaceToNamespace('Some_', ['Some_Class_To_Keep']), ]
),
]]);
};
2019-03-09 13:24:30 +00:00
```
2018-12-31 11:50:32 +00:00
```diff
-/** @var Some_Chicken $someService */
-$someService = new Some_Chicken;
+/** @var Some\Chicken $someService */
+$someService = new Some\Chicken;
$someClassToKeep = new Some_Class_To_Keep;
2018-12-31 11:50:32 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
## PublicConstantVisibilityRector
2018-10-12 23:15:00 +00:00
Add explicit public constant visibility.
- class: `Rector\Php71\Rector\ClassConst\PublicConstantVisibilityRector`
2018-10-12 23:15:00 +00:00
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
- const HEY = 'you';
+ public const HEY = 'you';
}
2018-05-05 12:48:33 +00:00
```
<br>
## RandomFunctionRector
2019-05-01 23:56:58 +00:00
Changes rand, `srand` and `getrandmax` by new mt_* alternatives.
2019-05-01 23:56:58 +00:00
- class: `Rector\Php70\Rector\FuncCall\RandomFunctionRector`
2019-05-01 23:56:58 +00:00
```diff
-rand();
+mt_rand();
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
## ReadOnlyOptionToAttributeRector
Change "read_only" option in form to attribute
- class: `Rector\Symfony\Rector\MethodCall\ReadOnlyOptionToAttributeRector`
```diff
use Symfony\Component\Form\FormBuilderInterface;
function buildForm(FormBuilderInterface $builder, array $options)
{
- $builder->add('cuid', TextType::class, ['read_only' => true]);
+ $builder->add('cuid', TextType::class, ['attr' => ['read_only' => true]]);
}
```
<br>
## RealToFloatTypeCastRector
Change deprecated (real) to (float)
- class: `Rector\Php74\Rector\Double\RealToFloatTypeCastRector`
```diff
class SomeClass
{
public function run()
{
- $number = (real) 5;
+ $number = (float) 5;
$number = (float) 5;
$number = (double) 5;
}
}
```
<br>
## RecastingRemovalRector
2019-05-24 20:30:15 +00:00
Removes recasting of the same type
2019-05-24 20:30:15 +00:00
- class: `Rector\PHPStan\Rector\Cast\RecastingRemovalRector`
2019-05-24 20:30:15 +00:00
```diff
$string = '';
-$string = (string) $string;
+$string = $string;
$array = [];
-$array = (array) $array;
+$array = $array;
```
<br>
## Redirect301ToPermanentRedirectRector
Change "redirect" call with 301 to "permanentRedirect"
- class: `Rector\Laravel\Rector\StaticCall\Redirect301ToPermanentRedirectRector`
```diff
class SomeClass
{
public function run()
{
- Illuminate\Routing\Route::redirect('/foo', '/bar', 301);
+ Illuminate\Routing\Route::permanentRedirect('/foo', '/bar');
}
2019-09-25 08:49:53 +00:00
}
```
<br>
## RedirectToRouteRector
Turns redirect to route to short helper method in Controller in Symfony
- class: `Rector\Symfony\Rector\MethodCall\RedirectToRouteRector`
```diff
-$this->redirect($this->generateUrl("homepage"));
+$this->redirectToRoute("homepage");
```
<br>
## ReduceMultipleDefaultSwitchRector
Remove first default switch, that is ignored
- class: `Rector\Php70\Rector\Switch_\ReduceMultipleDefaultSwitchRector`
```diff
switch ($expr) {
default:
- echo "Hello World";
-
- default:
echo "Goodbye Moon!";
break;
}
```
<br>
## RegexDashEscapeRector
2018-08-01 20:09:34 +00:00
Escape - in some cases
2019-09-25 08:49:53 +00:00
- class: `Rector\Php73\Rector\FuncCall\RegexDashEscapeRector`
2018-08-01 20:09:34 +00:00
```diff
-preg_match("#[\w-()]#", 'some text');
+preg_match("#[\w\-()]#", 'some text');
```
2019-09-25 08:49:53 +00:00
<br>
## RemoveAlwaysElseRector
Split if statement, when if condition always break execution flow
- class: `Rector\SOLID\Rector\If_\RemoveAlwaysElseRector`
```diff
class SomeClass
{
public function run($value)
{
if ($value) {
throw new \InvalidStateException;
- } else {
- return 10;
}
+
+ return 10;
}
}
2018-08-01 20:09:34 +00:00
```
<br>
## RemoveAlwaysTrueConditionSetInConstructorRector
2019-05-01 23:56:58 +00:00
If conditions is always true, perform the content right away
- class: `Rector\CodeQuality\Rector\FunctionLike\RemoveAlwaysTrueConditionSetInConstructorRector`
2019-05-01 23:56:58 +00:00
```diff
final class SomeClass
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function go()
{
- if ($this->value) {
- return 'yes';
- }
+ return 'yes';
}
}
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
## RemoveAlwaysTrueIfConditionRector
2018-12-31 19:29:12 +00:00
Remove if condition that is always true
- class: `Rector\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector`
```diff
final class SomeClass
{
public function go()
{
- if (1 === 1) {
- return 'yes';
- }
+ return 'yes';
return 'no';
}
}
2018-08-01 20:09:34 +00:00
```
<br>
2018-12-31 11:50:32 +00:00
## RemoveAndTrueRector
2019-02-21 14:36:16 +00:00
Remove and true that has no added value
2019-02-21 14:36:16 +00:00
- class: `Rector\DeadCode\Rector\BooleanAnd\RemoveAndTrueRector`
2019-02-21 14:36:16 +00:00
```diff
class SomeClass
{
public function run()
{
- return true && 5 === 1;
+ return 5 === 1;
}
}
```
<br>
## RemoveAnnotationRector
Remove annotation by names
:wrench: **configure it!**
2020-01-21 14:55:01 +00:00
- class: `Rector\Generic\Rector\ClassLike\RemoveAnnotationRector`
```php
use Rector\Generic\Rector\ClassLike\RemoveAnnotationRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveAnnotationRector::class)
->call('configure', [[
RemoveAnnotationRector::ANNOTATIONS_TO_REMOVE => ['method'],
]]);
};
```
2020-01-21 14:55:01 +00:00
```diff
-/**
- * @method getName()
- */
final class SomeClass
{
}
2020-01-21 14:55:01 +00:00
```
<br>
2020-01-21 14:55:01 +00:00
## RemoveAssignOfVoidReturnFunctionRector
2019-05-29 13:40:20 +00:00
Remove assign of void function/method to variable
- class: `Rector\DeadCode\Rector\Assign\RemoveAssignOfVoidReturnFunctionRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
- $value = $this->getOne();
+ $this->getOne();
}
private function getOne(): void
{
}
}
2019-02-21 14:36:16 +00:00
```
<br>
2019-02-21 14:36:16 +00:00
## RemoveCodeAfterReturnRector
2018-12-31 19:29:12 +00:00
Remove dead code after return statement
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\FunctionLike\RemoveCodeAfterReturnRector`
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
{
public function run(int $a)
2019-09-25 08:49:53 +00:00
{
return $a;
- $a++;
2019-09-25 08:49:53 +00:00
}
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
## RemoveConcatAutocastRector
2019-05-29 13:40:20 +00:00
Remove (string) casting when it comes to concat, that does this by default
2019-05-29 13:40:20 +00:00
- class: `Rector\DeadCode\Rector\Concat\RemoveConcatAutocastRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeConcatingClass
{
public function run($value)
{
- return 'hi ' . (string) $value;
+ return 'hi ' . $value;
}
2019-09-25 08:49:53 +00:00
}
2018-12-31 19:29:12 +00:00
```
<br>
2018-12-31 19:29:12 +00:00
## RemoveDataProviderTestPrefixRector
2018-08-01 20:09:34 +00:00
Data provider methods cannot start with "test" prefix
2018-10-12 23:15:00 +00:00
- class: `Rector\PHPUnit\Rector\Class_\RemoveDataProviderTestPrefixRector`
2018-08-01 20:09:34 +00:00
```diff
class SomeClass extends PHPUnit\Framework\TestCase
{
/**
- * @dataProvider testProvideData()
+ * @dataProvider provideData()
*/
public function test()
{
$nothing = 5;
}
2018-08-01 20:09:34 +00:00
- public function testProvideData()
+ public function provideData()
{
return ['123'];
}
}
```
<br>
## RemoveDeadConstructorRector
2019-11-06 23:52:19 +00:00
Remove empty constructor
- class: `Rector\DeadCode\Rector\ClassMethod\RemoveDeadConstructorRector`
2019-11-06 23:52:19 +00:00
```diff
class SomeClass
2019-11-06 23:52:19 +00:00
{
- public function __construct()
- {
- }
2019-11-06 23:52:19 +00:00
}
```
<br>
2019-11-06 23:52:19 +00:00
## RemoveDeadIfForeachForRector
2018-08-01 20:09:34 +00:00
Remove if, foreach and for that does not do anything
2018-10-12 23:15:00 +00:00
- class: `Rector\DeadCode\Rector\For_\RemoveDeadIfForeachForRector`
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
public function run($someObject)
{
$value = 5;
- if ($value) {
- }
-
if ($someObject->run()) {
- }
-
- foreach ($values as $value) {
}
return $value;
}
}
2018-08-01 20:09:34 +00:00
```
<br>
2018-12-31 19:29:12 +00:00
## RemoveDeadRecursiveClassMethodRector
2018-12-31 19:29:12 +00:00
Remove unused public method that only calls itself recursively
- class: `Rector\DeadCode\Rector\ClassMethod\RemoveDeadRecursiveClassMethodRector`
```diff
class SomeClass
{
- public function run()
- {
- return $this->run();
- }
}
```
<br>
## RemoveDeadReturnRector
Remove last return in the functions, since does not do anything
- class: `Rector\DeadCode\Rector\FunctionLike\RemoveDeadReturnRector`
2018-12-31 19:29:12 +00:00
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run()
{
$shallWeDoThis = true;
if ($shallWeDoThis) {
return;
}
-
- return;
}
2019-05-29 13:40:20 +00:00
}
```
<br>
2019-05-29 13:40:20 +00:00
## RemoveDeadStmtRector
2019-05-29 13:40:20 +00:00
Removes dead code statements
2019-05-29 13:40:20 +00:00
- class: `Rector\DeadCode\Rector\Expression\RemoveDeadStmtRector`
2019-05-29 13:40:20 +00:00
```diff
-$value = 5;
-$value;
+$value = 5;
```
2018-12-31 19:29:12 +00:00
<br>
2019-05-29 13:40:20 +00:00
## RemoveDeadTryCatchRector
2019-05-29 13:40:20 +00:00
Remove dead try/catch
2019-05-29 13:40:20 +00:00
- class: `Rector\DeadCode\Rector\TryCatch\RemoveDeadTryCatchRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
- try {
- // some code
- }
- catch (Throwable $throwable) {
- throw $throwable;
- }
+ // some code
}
}
2018-12-31 19:29:12 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
## RemoveDeadZeroAndOneOperationRector
2019-03-31 12:25:39 +00:00
Remove operation with 1 and 0, that have no effect on the value
2019-03-31 12:25:39 +00:00
- class: `Rector\DeadCode\Rector\Plus\RemoveDeadZeroAndOneOperationRector`
```diff
class SomeClass
2019-03-31 12:25:39 +00:00
{
public function run()
{
- $value = 5 * 1;
- $value = 5 + 0;
+ $value = 5;
+ $value = 5;
}
2019-03-31 12:25:39 +00:00
}
```
<br>
2019-03-31 12:25:39 +00:00
## RemoveDefaultArgumentValueRector
2019-03-31 12:25:39 +00:00
Remove argument value, if it is the same as default value
2019-03-31 12:25:39 +00:00
- class: `Rector\DeadCode\Rector\MethodCall\RemoveDefaultArgumentValueRector`
2019-03-31 12:25:39 +00:00
```diff
class SomeClass
{
public function run()
{
- $this->runWithDefault([]);
- $card = self::runWithStaticDefault([]);
+ $this->runWithDefault();
+ $card = self::runWithStaticDefault();
}
2019-09-25 08:49:53 +00:00
public function runWithDefault($items = [])
{
return $items;
}
2019-09-25 08:49:53 +00:00
public function runStaticWithDefault($cards = [])
{
return $cards;
}
}
```
<br>
## RemoveDefaultGetBlockPrefixRector
Rename `getBlockPrefix()` if it returns the default value - class to underscore, e.g. UserFormType = user_form
- class: `Rector\Symfony\Rector\ClassMethod\RemoveDefaultGetBlockPrefixRector`
```diff
use Symfony\Component\Form\AbstractType;
class TaskType extends AbstractType
2019-09-25 08:49:53 +00:00
{
- public function getBlockPrefix()
- {
- return 'task';
- }
}
```
<br>
## RemoveDelegatingParentCallRector
Removed dead parent call, that does not change anything
- class: `Rector\DeadCode\Rector\ClassMethod\RemoveDelegatingParentCallRector`
```diff
class SomeClass
{
- public function prettyPrint(array $stmts): string
- {
- return parent::prettyPrint($stmts);
- }
}
```
<br>
## RemoveDoubleAssignRector
Simplify useless double assigns
- class: `Rector\DeadCode\Rector\Assign\RemoveDoubleAssignRector`
```diff
-$value = 1;
$value = 1;
```
<br>
## RemoveDoubleUnderscoreInMethodNameRector
Non-magic PHP object methods cannot start with "__"
- class: `Rector\CodingStyle\Rector\ClassMethod\RemoveDoubleUnderscoreInMethodNameRector`
```diff
class SomeClass
{
- public function __getName($anotherObject)
+ public function getName($anotherObject)
{
- $anotherObject->__getSurname();
+ $anotherObject->getSurname();
}
}
```
<br>
## RemoveDuplicatedArrayKeyRector
Remove duplicated `key` in defined arrays.
- class: `Rector\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector`
```diff
$item = [
- 1 => 'A',
1 => 'B'
];
```
<br>
## RemoveDuplicatedCaseInSwitchRector
2020-04-24 22:57:13 +00:00
2 following switch keys with identical will be reduced to one result
2020-04-24 22:57:13 +00:00
- class: `Rector\DeadCode\Rector\Switch_\RemoveDuplicatedCaseInSwitchRector`
2020-04-24 22:57:13 +00:00
```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-04-24 22:57:13 +00:00
}
```
<br>
2020-04-24 22:57:13 +00:00
## RemoveDuplicatedIfReturnRector
2020-04-29 20:01:42 +00:00
Remove duplicated if stmt with return in function/method body
2020-04-29 20:01:42 +00:00
- class: `Rector\DeadCode\Rector\FunctionLike\RemoveDuplicatedIfReturnRector`
2020-04-29 20:01:42 +00:00
```diff
class SomeClass
{
public function run($value)
{
if ($value) {
return true;
}
$value2 = 100;
-
- if ($value) {
- return true;
- }
}
}
```
<br>
## RemoveDuplicatedInstanceOfRector
2020-04-29 21:23:14 +00:00
Remove duplicated instanceof in one call
2020-04-29 21:23:14 +00:00
- class: `Rector\DeadCode\Rector\BinaryOp\RemoveDuplicatedInstanceOfRector`
2020-04-29 21:23:14 +00:00
```diff
class SomeClass
{
- public function run($value)
+ public function run($value): void
{
- $isIt = $value instanceof A || $value instanceof A;
- $isIt = $value instanceof A && $value instanceof A;
+ $isIt = $value instanceof A;
+ $isIt = $value instanceof A;
}
}
2020-04-29 21:23:14 +00:00
```
<br>
2020-04-29 21:23:14 +00:00
## RemoveEmptyClassMethodRector
2020-06-05 10:33:30 +00:00
Remove empty method calls not required by parents
2020-06-05 10:33:30 +00:00
- class: `Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector`
2020-06-05 10:33:30 +00:00
```diff
class OrphanClass
{
- public function __construct()
- {
- }
}
2020-06-05 10:33:30 +00:00
```
<br>
2020-06-05 10:33:30 +00:00
## RemoveEmptyMethodCallRector
2020-03-26 22:22:29 +00:00
Remove empty method call
2020-03-26 22:22:29 +00:00
- class: `Rector\DeadCode\Rector\MethodCall\RemoveEmptyMethodCallRector`
2020-03-26 22:22:29 +00:00
```diff
class SomeClass
{
public function callThis()
2020-03-26 22:22:29 +00:00
{
}
}
-$some = new SomeClass();
-$some->callThis();
+$some = new SomeClass();
```
2020-03-26 22:22:29 +00:00
<br>
2020-03-26 22:22:29 +00:00
## RemoveEmptyTestMethodRector
2020-04-23 22:28:33 +00:00
Remove empty test methods
2020-04-23 22:28:33 +00:00
- class: `Rector\PHPUnit\Rector\ClassMethod\RemoveEmptyTestMethodRector`
2020-04-23 22:28:33 +00:00
```diff
class SomeTest extends \PHPUnit\Framework\TestCase
{
- /**
- * testGetTranslatedModelField method
- *
- * @return void
- */
- public function testGetTranslatedModelField()
- {
- }
}
2020-04-23 22:28:33 +00:00
```
<br>
2020-04-23 22:28:33 +00:00
## RemoveExpectAnyFromMockRector
2020-04-23 12:34:27 +00:00
Remove `expect($this->any())` from mocks as it has no added value
2020-04-23 12:34:27 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\RemoveExpectAnyFromMockRector`
2020-04-23 12:34:27 +00:00
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
public function test()
{
$translator = $this->getMock('SomeClass');
- $translator->expects($this->any())
- ->method('trans')
+ $translator->method('trans')
->willReturn('translated max {{ max }}!');
}
}
2020-04-23 12:34:27 +00:00
```
<br>
2020-04-23 12:34:27 +00:00
## RemoveExtraParametersRector
2020-04-24 12:00:49 +00:00
Remove extra parameters
2020-04-24 12:00:49 +00:00
- class: `Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector`
2020-04-24 12:00:49 +00:00
```diff
-strlen("asdf", 1);
+strlen("asdf");
2020-04-24 12:00:49 +00:00
```
<br>
2020-04-24 12:00:49 +00:00
## RemoveFinalFromEntityRector
2020-06-05 10:33:30 +00:00
Remove final from Doctrine entities
2020-06-05 10:33:30 +00:00
- class: `Rector\Restoration\Rector\Class_\RemoveFinalFromEntityRector`
2020-06-05 10:33:30 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
-final class SomeClass
+class SomeClass
{
}
2020-06-05 10:33:30 +00:00
```
<br>
2020-06-05 10:33:30 +00:00
## RemoveFuncCallArgRector
Remove argument by position by function name
:wrench: **configure it!**
- class: `Rector\Generic\Rector\FuncCall\RemoveFuncCallArgRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\FuncCall\RemoveFuncCallArgRector;
use Rector\Generic\ValueObject\RemoveFuncCallArg;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveFuncCallArgRector::class)
->call('configure', [[
RemoveFuncCallArgRector::REMOVED_FUNCTION_ARGUMENTS => inline_value_objects([
new RemoveFuncCallArg('remove_last_arg', 1),
]),
]]);
};
```
```diff
-remove_last_arg(1, 2);
+remove_last_arg(1);
```
<br>
## RemoveIncludeRector
Remove includes (include, include_once, require, require_once) from source
- class: `Rector\Legacy\Rector\Include_\RemoveIncludeRector`
```diff
// Comment before require
-include 'somefile.php';
+
// Comment after require
```
<br>
## RemoveIniGetSetFuncCallRector
Remove `ini_get` by configuration
:wrench: **configure it!**
- class: `Rector\Generic\Rector\FuncCall\RemoveIniGetSetFuncCallRector`
2019-03-31 12:25:39 +00:00
```php
use Rector\Generic\Rector\FuncCall\RemoveIniGetSetFuncCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-03-31 12:25:39 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-03-31 12:25:39 +00:00
$services->set(RemoveIniGetSetFuncCallRector::class)
->call('configure', [[
RemoveIniGetSetFuncCallRector::KEYS_TO_REMOVE => ['y2k_compliance'],
]]);
};
```
2019-03-31 12:25:39 +00:00
2019-03-31 12:25:39 +00:00
```diff
-ini_get('y2k_compliance');
-ini_set('y2k_compliance', 1);
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
## RemoveInterfacesRector
2019-03-31 12:25:39 +00:00
Removes interfaces usage from class.
2019-03-31 12:25:39 +00:00
:wrench: **configure it!**
2019-03-31 12:25:39 +00:00
- class: `Rector\Generic\Rector\Class_\RemoveInterfacesRector`
2019-03-31 12:25:39 +00:00
```php
use Rector\Generic\Rector\Class_\RemoveInterfacesRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-03-31 12:25:39 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-03-16 20:31:46 +00:00
$services->set(RemoveInterfacesRector::class)
->call('configure', [[
RemoveInterfacesRector::INTERFACES_TO_REMOVE => [SomeInterface::class],
]]);
};
```
2019-03-16 20:31:46 +00:00
2019-03-16 20:31:46 +00:00
```diff
-class SomeClass implements SomeInterface
+class SomeClass
{
}
```
2019-03-16 20:31:46 +00:00
<br>
## RemoveJmsInjectParamsAnnotationRector
Removes JMS\DiExtraBundle\Annotation\InjectParams annotation
- class: `Rector\JMS\Rector\ClassMethod\RemoveJmsInjectParamsAnnotationRector`
```diff
use JMS\DiExtraBundle\Annotation as DI;
class SomeClass
2019-03-16 20:31:46 +00:00
{
- /**
- * @DI\InjectParams({
- * "subscribeService" = @DI\Inject("app.email.service.subscribe"),
- * "ipService" = @DI\Inject("app.util.service.ip")
- * })
- */
public function __construct()
2019-03-16 20:31:46 +00:00
{
}
-}
+}
2019-03-31 12:25:39 +00:00
```
<br>
2019-03-31 12:25:39 +00:00
## RemoveJmsInjectServiceAnnotationRector
2019-03-31 12:25:39 +00:00
Removes JMS\DiExtraBundle\Annotation\Services annotation
2019-03-16 20:31:46 +00:00
- class: `Rector\JMS\Rector\Class_\RemoveJmsInjectServiceAnnotationRector`
2019-03-31 12:25:39 +00:00
```diff
use JMS\DiExtraBundle\Annotation as DI;
-/**
- * @DI\Service("email.web.services.subscribe_token", public=true)
- */
class SomeClass
2019-03-31 12:25:39 +00:00
{
2019-03-16 20:31:46 +00:00
}
```
<br>
## RemoveMissingCompactVariableRector
2020-01-06 15:06:07 +00:00
Remove non-existing vars from `compact()`
2020-01-06 15:06:07 +00:00
- class: `Rector\Php73\Rector\FuncCall\RemoveMissingCompactVariableRector`
2020-01-06 15:06:07 +00:00
```diff
class SomeClass
{
public function run()
{
$value = 'yes';
- compact('value', 'non_existing');
+ compact('value');
2020-01-06 15:06:07 +00:00
}
}
```
<br>
2020-01-06 15:06:07 +00:00
## RemoveNonExistingVarAnnotationRector
Removes non-existing `@var` annotations above the code
- class: `Rector\PHPStan\Rector\Node\RemoveNonExistingVarAnnotationRector`
```diff
class SomeClass
{
public function get()
{
- /** @var Training[] $trainings */
return $this->getData();
}
}
```
<br>
## RemoveNullPropertyInitializationRector
2020-03-28 23:06:05 +00:00
Remove initialization with null value from property declarations
2020-05-12 15:09:29 +00:00
- class: `Rector\DeadCode\Rector\PropertyProperty\RemoveNullPropertyInitializationRector`
2020-05-12 15:09:29 +00:00
```diff
class SunshineCommand extends ParentClassWithNewConstructor
{
- private $myVar = null;
+ private $myVar;
}
```
<br>
## RemoveOverriddenValuesRector
Remove initial assigns of overridden values
- class: `Rector\DeadCode\Rector\FunctionLike\RemoveOverriddenValuesRector`
2020-05-12 15:09:29 +00:00
```diff
final class SomeController
2020-05-12 15:09:29 +00:00
{
public function run()
{
- $directories = [];
$possibleDirectories = [];
$directories = array_filter($possibleDirectories, 'file_exists');
2020-05-12 15:09:29 +00:00
}
}
```
<br>
2020-05-12 15:09:29 +00:00
## RemoveParamReturnDocblockRector
2020-05-29 10:41:25 +00:00
Remove `@param` and `@return` docblock with same type and no description on typed argument and return
2020-05-29 10:41:25 +00:00
- class: `Rector\CodingStyle\Rector\ClassMethod\RemoveParamReturnDocblockRector`
2020-05-29 10:41:25 +00:00
```diff
use stdClass;
class SomeClass
{
/**
- * @param string $a
* @param string $b description
- * @return stdClass
*/
function foo(string $a, string $b): stdClass
{
}
2020-05-29 10:41:25 +00:00
}
```
<br>
2020-05-29 10:41:25 +00:00
## RemoveParentAndNameFromComponentConstructorRector
Remove `$parent` and `$name` in control constructor
- class: `Rector\Nette\Rector\ClassMethod\RemoveParentAndNameFromComponentConstructorRector`
```diff
use Nette\Application\UI\Control;
class SomeControl extends Control
{
- public function __construct(IContainer $parent = null, $name = null, int $value)
+ public function __construct(int $value)
{
- parent::__construct($parent, $name);
$this->value = $value;
}
}
```
<br>
## RemoveParentCallWithoutParentRector
Remove unused parent call with no parent class
- class: `Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector`
```diff
class OrphanClass
{
public function __construct()
{
- parent::__construct();
}
}
```
<br>
## RemoveParentRector
Removes extends class by name
:wrench: **configure it!**
- class: `Rector\Generic\Rector\Class_\RemoveParentRector`
```php
use Rector\Generic\Rector\Class_\RemoveParentRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RemoveParentRector::class)
->call('configure', [[
RemoveParentRector::PARENT_TYPES_TO_REMOVE => ['SomeParentClass'],
]]);
};
```
```diff
-final class SomeClass extends SomeParentClass
+final class SomeClass
{
}
```
<br>
## RemoveProjectFileRector
Remove file relative to project directory
:wrench: **configure it!**
- class: `Rector\FileSystemRector\Rector\FileNode\RemoveProjectFileRector`
```php
use Rector\FileSystemRector\Rector\FileNode\RemoveProjectFileRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-03-28 23:06:05 +00:00
$services->set(RemoveProjectFileRector::class)
->call('configure', [[
RemoveProjectFileRector::FILE_PATHS_TO_REMOVE => ['someFile/ToBeRemoved.txt'],
]]);
};
```
2020-03-28 23:06:05 +00:00
2020-03-28 23:06:05 +00:00
```diff
-// someFile/ToBeRemoved.txt
2020-03-28 23:06:05 +00:00
```
<br>
2020-03-28 23:06:05 +00:00
## RemoveRedundantDefaultClassAnnotationValuesRector
Removes redundant default values from Doctrine ORM annotations on class level
- class: `Rector\DoctrineCodeQuality\Rector\Class_\RemoveRedundantDefaultClassAnnotationValuesRector`
```diff
use Doctrine\ORM\Mapping as ORM;
/**
- * @ORM\Entity(readOnly=false)
+ * @ORM\Entity()
*/
class SomeClass
{
}
```
<br>
## RemoveRedundantDefaultPropertyAnnotationValuesRector
Removes redundant default values from Doctrine ORM annotations on class property level
- class: `Rector\DoctrineCodeQuality\Rector\Property\RemoveRedundantDefaultPropertyAnnotationValuesRector`
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeClass
{
/**
* @ORM\ManyToOne(targetEntity=Training::class)
- * @ORM\JoinColumn(name="training", unique=false)
+ * @ORM\JoinColumn(name="training")
*/
private $training;
}
```
<br>
## RemoveReferenceFromCallRector
Remove & from function and method calls
- class: `Rector\Php54\Rector\FuncCall\RemoveReferenceFromCallRector`
```diff
final class SomeClass
{
public function run($one)
{
- return strlen(&$one);
+ return strlen($one);
}
}
```
<br>
## RemoveRepositoryFromEntityAnnotationRector
2019-09-25 08:49:53 +00:00
Removes repository class from `@Entity` annotation
2019-09-25 08:49:53 +00:00
- class: `Rector\Doctrine\Rector\Class_\RemoveRepositoryFromEntityAnnotationRector`
2019-09-25 08:49:53 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
- * @ORM\Entity(repositoryClass="ProductRepository")
+ * @ORM\Entity
*/
class Product
{
}
```
<br>
## RemoveServiceFromSensioRouteRector
Remove service from Sensio `@Route`
- class: `Rector\Sensio\Rector\ClassMethod\RemoveServiceFromSensioRouteRector`
2019-09-25 08:49:53 +00:00
```diff
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
final class SomeClass
{
/**
- * @Route(service="some_service")
+ * @Route()
*/
public function run()
2019-09-25 08:49:53 +00:00
{
}
}
```
2019-09-25 08:49:53 +00:00
<br>
## RemoveSetTempDirOnExcelWriterRector
Remove `setTempDir()` on PHPExcel_Writer_Excel5
- class: `Rector\PHPOffice\Rector\MethodCall\RemoveSetTempDirOnExcelWriterRector`
```diff
final class SomeClass
2019-09-25 08:49:53 +00:00
{
public function run(): void
{
$writer = new \PHPExcel_Writer_Excel5;
- $writer->setTempDir();
}
2019-09-25 08:49:53 +00:00
}
```
<br>
2019-09-25 08:49:53 +00:00
## RemoveSetterOnlyPropertyAndMethodCallRector
2019-09-25 08:49:53 +00:00
Removes method that set values that are never used
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\Property\RemoveSetterOnlyPropertyAndMethodCallRector`
2020-07-24 11:46:57 +00:00
```diff
class SomeClass
{
- private $name;
-
- public function setName($name)
- {
- $this->name = $name;
- }
}
2020-07-24 11:46:57 +00:00
class ActiveOnlySetter
{
public function run()
{
$someClass = new SomeClass();
- $someClass->setName('Tom');
}
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
## RemoveSoleValueSprintfRector
2019-09-25 08:49:53 +00:00
Remove `sprintf()` wrapper if not needed
2019-11-06 23:52:19 +00:00
- class: `Rector\CodeQuality\Rector\FuncCall\RemoveSoleValueSprintfRector`
```diff
class SomeClass
{
public function run()
{
- $value = sprintf('%s', 'hi');
+ $value = 'hi';
$welcome = 'hello';
- $value = sprintf('%s', $welcome);
+ $value = $welcome;
}
}
```
2019-09-25 08:49:53 +00:00
<br>
2019-09-25 08:49:53 +00:00
## RemoveTemporaryUuidColumnPropertyRector
2019-09-25 08:49:53 +00:00
Remove temporary `$uuid` property
2020-07-24 11:46:57 +00:00
- class: `Rector\Doctrine\Rector\Property\RemoveTemporaryUuidColumnPropertyRector`
2020-07-24 11:46:57 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Column
{
/**
* @ORM\Column
*/
public $id;
-
- /**
- * @ORM\Column
- */
- public $uuid;
}
```
<br>
## RemoveTemporaryUuidRelationPropertyRector
Remove temporary *Uuid relation properties
- class: `Rector\Doctrine\Rector\Property\RemoveTemporaryUuidRelationPropertyRector`
2019-09-25 08:49:53 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Column
{
/**
* @ORM\ManyToMany(targetEntity="Phonenumber")
*/
private $apple;
-
- /**
- * @ORM\ManyToMany(targetEntity="Phonenumber")
- */
- private $appleUuid;
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveTraitRector
2019-09-25 08:49:53 +00:00
Remove specific traits from code
2019-09-25 08:49:53 +00:00
:wrench: **configure it!**
2019-09-25 08:49:53 +00:00
- class: `Rector\Generic\Rector\Class_\RemoveTraitRector`
2019-09-25 08:49:53 +00:00
```php
use Rector\Generic\Rector\Class_\RemoveTraitRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-09-25 08:49:53 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-09-25 08:49:53 +00:00
$services->set(RemoveTraitRector::class)
->call('configure', [[
RemoveTraitRector::TRAITS_TO_REMOVE => ['TraitNameToRemove'],
]]);
};
```
2019-09-25 08:49:53 +00:00
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
{
- use SomeTrait;
}
```
2019-09-25 08:49:53 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnreachableStatementRector
2020-07-24 11:46:57 +00:00
Remove unreachable statements
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector`
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
2019-09-25 08:49:53 +00:00
{
public function run()
2019-09-25 08:49:53 +00:00
{
return 5;
-
- $removeMe = 10;
2019-09-25 08:49:53 +00:00
}
}
```
<br>
2019-09-25 08:49:53 +00:00
## RemoveUnusedAliasRector
2019-09-25 08:49:53 +00:00
Removes unused use aliases. Keep annotation aliases like "Doctrine\ORM\Mapping as ORM" to keep convention format
2019-09-25 08:49:53 +00:00
- class: `Rector\CodingStyle\Rector\Use_\RemoveUnusedAliasRector`
2019-09-25 08:49:53 +00:00
```diff
-use Symfony\Kernel as BaseKernel;
+use Symfony\Kernel;
2019-09-25 08:49:53 +00:00
-class SomeClass extends BaseKernel
+class SomeClass extends Kernel
{
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
## RemoveUnusedAssignVariableRector
2019-09-25 08:49:53 +00:00
Remove assigned unused variable
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\Assign\RemoveUnusedAssignVariableRector`
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
{
public function run()
{
- $value = $this->process();
+ $this->process();
}
public function process()
{
// something going on
return 5;
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnusedClassConstantRector
2019-09-25 08:49:53 +00:00
Remove unused class constants
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\ClassConst\RemoveUnusedClassConstantRector`
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
{
- private const SOME_CONST = 'dead';
-
public function run()
{
}
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
## RemoveUnusedClassesRector
2019-09-25 08:49:53 +00:00
Remove unused classes without interface
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\Class_\RemoveUnusedClassesRector`
2019-09-25 08:49:53 +00:00
```diff
interface SomeInterface
{
}
2019-09-25 08:49:53 +00:00
class SomeClass implements SomeInterface
{
public function run($items)
{
return null;
}
-}
-
-class NowhereUsedClass
-{
}
```
2019-09-25 08:49:53 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnusedDoctrineEntityMethodAndPropertyRector
2020-07-24 11:46:57 +00:00
Removes unused methods and properties from Doctrine entity classes
2020-02-13 21:48:16 +00:00
- class: `Rector\DeadCode\Rector\Class_\RemoveUnusedDoctrineEntityMethodAndPropertyRector`
2020-02-13 21:48:16 +00:00
```diff
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class UserEntity
{
- /**
- * @ORM\Column
- */
- private $name;
-
- public function getName()
- {
- return $this->name;
- }
-
- public function setName($name)
- {
- $this->name = $name;
- }
}
```
<br>
## RemoveUnusedForeachKeyRector
2019-09-25 08:49:53 +00:00
Remove unused `key` in foreach
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\Foreach_\RemoveUnusedForeachKeyRector`
2020-07-24 11:46:57 +00:00
```diff
$items = [];
-foreach ($items as $key => $value) {
+foreach ($items as $value) {
$result = $value;
}
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
## RemoveUnusedFunctionRector
Remove unused function
- class: `Rector\DeadCode\Rector\Function_\RemoveUnusedFunctionRector`
```diff
-function removeMe()
-{
-}
-
function useMe()
{
}
useMe();
```
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnusedNonEmptyArrayBeforeForeachRector
2020-07-24 11:46:57 +00:00
Remove unused if check to non-empty array before foreach of the array
- class: `Rector\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector`
```diff
class SomeClass
{
public function run()
{
$values = [];
- if ($values !== []) {
- foreach ($values as $value) {
- echo $value;
- }
+ foreach ($values as $value) {
+ echo $value;
}
}
}
```
2019-05-01 23:56:58 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnusedParameterRector
2020-07-24 11:46:57 +00:00
Remove unused parameter, if not required by interface or parent class
2019-05-01 23:56:58 +00:00
- class: `Rector\DeadCode\Rector\ClassMethod\RemoveUnusedParameterRector`
2019-05-01 23:56:58 +00:00
```diff
class SomeClass
{
- public function __construct($value, $value2)
+ public function __construct($value)
{
$this->value = $value;
}
}
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
## RemoveUnusedPrivateConstantRector
2019-05-01 23:56:58 +00:00
Remove unused private constant
2019-05-01 23:56:58 +00:00
- class: `Rector\DeadCode\Rector\ClassConst\RemoveUnusedPrivateConstantRector`
2019-05-01 23:56:58 +00:00
```diff
final class SomeController
{
- private const SOME_CONSTANT = 5;
public function run()
{
return 5;
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnusedPrivateMethodRector
2019-05-29 13:40:20 +00:00
Remove unused private method
- class: `Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector`
2019-05-01 23:56:58 +00:00
```diff
final class SomeController
{
public function run()
{
return 5;
}
-
- private function skip()
- {
- return 10;
- }
}
2019-09-25 08:49:53 +00:00
```
2019-05-29 13:40:20 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnusedPrivatePropertyRector
2020-07-24 11:46:57 +00:00
Remove unused private properties
2019-09-25 08:49:53 +00:00
- class: `Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector`
2019-09-25 08:49:53 +00:00
```diff
class SomeClass
{
- private $property;
}
2019-05-29 13:40:20 +00:00
```
2019-05-01 23:56:58 +00:00
<br>
2019-05-29 13:40:20 +00:00
## RemoveUnusedVariableAssignRector
2019-08-05 21:10:47 +00:00
Remove unused assigns to variables
2019-08-05 21:10:47 +00:00
- class: `Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector`
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
public function run()
{
- $value = 5;
}
}
```
2019-08-05 21:10:47 +00:00
<br>
2020-07-24 11:46:57 +00:00
## RemoveUnusedVariableInCatchRector
2020-07-24 11:46:57 +00:00
Remove unused variable in `catch()`
2019-08-05 21:10:47 +00:00
- class: `Rector\Php80\Rector\Catch_\RemoveUnusedVariableInCatchRector`
2019-08-05 21:10:47 +00:00
```diff
final class SomeClass
{
public function run()
{
try {
- } catch (Throwable $notUsedThrowable) {
+ } catch (Throwable) {
}
}
}
2019-08-05 21:10:47 +00:00
```
<br>
## RemoveUselessJustForSakeInterfaceRector
Remove interface, that are added just for its sake, but nowhere useful
- class: `Rector\Restoration\Rector\Class_\RemoveUselessJustForSakeInterfaceRector`
```diff
-class SomeClass implements OnlyHereUsedInterface
+class SomeClass
{
}
-interface OnlyHereUsedInterface
-{
-}
-
class SomePresenter
{
- public function __construct(OnlyHereUsedInterface $onlyHereUsed)
+ public function __construct(SomeClass $onlyHereUsed)
{
}
}
```
<br>
2020-07-24 11:46:57 +00:00
## RemoveZeroBreakContinueRector
2020-07-24 11:46:57 +00:00
Remove 0 from break and continue
- class: `Rector\Php54\Rector\Break_\RemoveZeroBreakContinueRector`
```diff
class SomeClass
{
public function run($random)
{
- continue 0;
- break 0;
+ continue;
+ break;
$five = 5;
- continue $five;
+ continue 5;
- break $random;
+ break;
}
}
```
<br>
2019-08-05 21:10:47 +00:00
## RenameAnnotationRector
Turns defined annotations above properties and methods to their new values.
:wrench: **configure it!**
- class: `Rector\Renaming\Rector\ClassMethod\RenameAnnotationRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Renaming\Rector\ClassMethod\RenameAnnotationRector;
use Rector\Renaming\ValueObject\RenameAnnotation;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameAnnotationRector::class)
->call('configure', [[
RenameAnnotationRector::RENAMED_ANNOTATIONS_IN_TYPES => inline_value_objects([
new RenameAnnotation('PHPUnit\Framework\TestCase', 'test', 'scenario'),
]),
]]);
};
```
```diff
class SomeTest extends PHPUnit\Framework\TestCase
{
/**
- * @test
+ * @scenario
*/
public function someMethod()
{
}
}
```
<br>
## RenameClassConstantRector
Replaces defined class constants in their calls.
:wrench: **configure it!**
- class: `Rector\Renaming\Rector\ClassConstFetch\RenameClassConstantRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Renaming\Rector\ClassConstFetch\RenameClassConstantRector;
use Rector\Renaming\ValueObject\RenameClassConstant;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameClassConstantRector::class)
->call('configure', [[
RenameClassConstantRector::CLASS_CONSTANT_RENAME => inline_value_objects([
new RenameClassConstant('SomeClass', 'OLD_CONSTANT', 'NEW_CONSTANT'),
new RenameClassConstant('SomeClass', 'OTHER_OLD_CONSTANT', 'DifferentClass::NEW_CONSTANT'),
]),
]]);
};
```
```diff
-$value = SomeClass::OLD_CONSTANT;
-$value = SomeClass::OTHER_OLD_CONSTANT;
+$value = SomeClass::NEW_CONSTANT;
+$value = DifferentClass::NEW_CONSTANT;
```
<br>
## RenameClassConstantsUseToStringsRector
Replaces constant by value
:wrench: **configure it!**
- class: `Rector\Generic\Rector\ClassConstFetch\RenameClassConstantsUseToStringsRector`
```php
use Rector\Generic\Rector\ClassConstFetch\RenameClassConstantsUseToStringsRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameClassConstantsUseToStringsRector::class)
->call('configure', [[
RenameClassConstantsUseToStringsRector::OLD_CONSTANTS_TO_NEW_VALUES_BY_TYPE => [
'Nette\Configurator' => [
'DEVELOPMENT' => 'development',
'PRODUCTION' => 'production',
],
],
]]);
};
```
```diff
-$value === Nette\Configurator::DEVELOPMENT
+$value === "development"
```
<br>
## RenameClassRector
2020-01-06 15:06:07 +00:00
Replaces defined classes by new ones.
2020-01-06 15:06:07 +00:00
:wrench: **configure it!**
2020-01-06 15:06:07 +00:00
- class: `Rector\Renaming\Rector\Name\RenameClassRector`
2020-01-06 15:06:07 +00:00
```php
use Rector\Renaming\Rector\Name\RenameClassRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-01-06 15:06:07 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameClassRector::class)
->call('configure', [[
RenameClassRector::OLD_TO_NEW_CLASSES => [
'App\SomeOldClass' => 'App\SomeNewClass',
],
]]);
};
```
```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;
}
}
```
<br>
## RenameConstantRector
Replace constant by new ones
:wrench: **configure it!**
- class: `Rector\Renaming\Rector\ConstFetch\RenameConstantRector`
```php
use Rector\Renaming\Rector\ConstFetch\RenameConstantRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-01-06 15:06:07 +00:00
$services->set(RenameConstantRector::class)
->call('configure', [[
RenameConstantRector::OLD_TO_NEW_CONSTANTS => [
'MYSQL_ASSOC' => 'MYSQLI_ASSOC',
'OLD_CONSTANT' => 'NEW_CONSTANT',
],
]]);
};
```
2020-01-06 15:06:07 +00:00
2020-01-06 15:06:07 +00:00
```diff
final class SomeClass
2020-01-06 15:06:07 +00:00
{
public function run()
{
- return MYSQL_ASSOC;
+ return MYSQLI_ASSOC;
2020-01-06 15:06:07 +00:00
}
}
```
<br>
2020-01-06 15:06:07 +00:00
## RenameEventNamesInEventSubscriberRector
Changes event names from Nette ones to Symfony ones
- class: `Rector\NetteToSymfony\Rector\ClassMethod\RenameEventNamesInEventSubscriberRector`
```diff
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class SomeClass implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- return ['nette.application' => 'someMethod'];
+ return [\SymfonyEvents::KERNEL => 'someMethod'];
}
}
```
<br>
## RenameForeachValueVariableToMatchMethodCallReturnTypeRector
Renames value variable name in foreach loop to match method type
- class: `Rector\Naming\Rector\Foreach_\RenameForeachValueVariableToMatchMethodCallReturnTypeRector`
```diff
class SomeClass
{
public function run()
{
$array = [];
- foreach ($object->getMethods() as $property) {
- $array[] = $property;
+ foreach ($object->getMethods() as $method) {
+ $array[] = $method;
}
}
}
```
<br>
## RenameFunctionRector
2019-05-29 13:40:20 +00:00
Turns defined function call new one.
2019-05-29 13:40:20 +00:00
:wrench: **configure it!**
2019-05-29 13:40:20 +00:00
- class: `Rector\Renaming\Rector\FuncCall\RenameFunctionRector`
2019-05-01 23:56:58 +00:00
```php
use Rector\Renaming\Rector\FuncCall\RenameFunctionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-05-01 23:56:58 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameFunctionRector::class)
->call('configure', [[
RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [
'view' => 'Laravel\Templating\render',
],
]]);
};
```
```diff
-view("...", []);
+Laravel\Templating\render("...", []);
```
<br>
## RenameMethodCallBasedOnParameterRector
2020-07-24 11:46:57 +00:00
Changes method calls based on matching the first parameter value.
:wrench: **configure it!**
- class: `Rector\CakePHP\Rector\MethodCall\RenameMethodCallBasedOnParameterRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\CakePHP\Rector\MethodCall\RenameMethodCallBasedOnParameterRector;
use Rector\CakePHP\ValueObject\RenameMethodCallBasedOnParameter;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-01-03 18:20:13 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-01-03 18:20:13 +00:00
$services->set(RenameMethodCallBasedOnParameterRector::class)
->call('configure', [[
RenameMethodCallBasedOnParameterRector::CALLS_WITH_PARAM_RENAMES => inline_value_objects([
new RenameMethodCallBasedOnParameter('getParam', 'paging', 'getAttribute', 'ServerRequest'),
new RenameMethodCallBasedOnParameter('withParam', 'paging', 'withAttribute', 'ServerRequest'),
]),
]]);
};
```
2020-01-03 18:20:13 +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-01-03 18:20:13 +00:00
```
<br>
## RenameMethodRector
Turns method names to new ones.
:wrench: **configure it!**
- class: `Rector\Renaming\Rector\MethodCall\RenameMethodRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Renaming\Rector\MethodCall\RenameMethodRector;
use Rector\Renaming\ValueObject\MethodCallRename;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-10-15 14:46:31 +00:00
$services->set(RenameMethodRector::class)
->call('configure', [[
RenameMethodRector::METHOD_CALL_RENAMES => inline_value_objects([
new MethodCallRename('SomeExampleClass', 'oldMethod', 'newMethod'),
]),
]]);
};
```
2019-10-15 14:46:31 +00:00
2019-10-15 14:46:31 +00:00
```diff
$someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();
2019-10-15 14:46:31 +00:00
```
<br>
2019-10-15 14:46:31 +00:00
## RenameMktimeWithoutArgsToTimeRector
Renames `mktime()` without arguments to `time()`
- class: `Rector\Php70\Rector\FuncCall\RenameMktimeWithoutArgsToTimeRector`
```diff
class SomeClass
{
public function run()
{
$time = mktime(1, 2, 3);
- $nextTime = mktime();
+ $nextTime = time();
}
}
```
<br>
2020-06-06 13:07:56 +00:00
## RenameNamespaceRector
2020-06-06 13:07:56 +00:00
Replaces old namespace by new one.
2020-06-06 13:07:56 +00:00
:wrench: **configure it!**
2020-06-06 13:07:56 +00:00
- class: `Rector\Renaming\Rector\Namespace_\RenameNamespaceRector`
2020-06-06 13:07:56 +00:00
```php
use Rector\Renaming\Rector\Namespace_\RenameNamespaceRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-06-06 13:07:56 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-12-31 11:50:32 +00:00
$services->set(RenameNamespaceRector::class)
->call('configure', [[
RenameNamespaceRector::OLD_TO_NEW_NAMESPACES => [
'SomeOldNamespace' => 'SomeNewNamespace',
],
]]);
};
```
2018-12-31 11:50:32 +00:00
```diff
-$someObject = new SomeOldNamespace\SomeClass;
+$someObject = new SomeNewNamespace\SomeClass;
2019-10-15 14:46:31 +00:00
```
<br>
2019-10-15 14:46:31 +00:00
## RenameParamToMatchTypeRector
2018-10-21 22:26:45 +00:00
Rename variable to match new ClassType
2018-10-21 22:26:45 +00:00
- class: `Rector\Naming\Rector\ClassMethod\RenameParamToMatchTypeRector`
2018-10-21 22:26:45 +00:00
```diff
final class SomeClass
{
- public function run(Apple $pie)
+ public function run(Apple $apple)
{
- $food = $pie;
+ $food = $apple;
}
}
2018-10-21 22:26:45 +00:00
```
<br>
2018-08-01 20:09:34 +00:00
## RenamePropertyRector
2018-08-01 20:09:34 +00:00
Replaces defined old properties by new ones.
2018-08-01 20:09:34 +00:00
:wrench: **configure it!**
2018-08-01 20:09:34 +00:00
- class: `Rector\Renaming\Rector\PropertyFetch\RenamePropertyRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Renaming\Rector\PropertyFetch\RenamePropertyRector;
use Rector\Renaming\ValueObject\RenameProperty;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2018-09-28 16:33:35 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-09-28 16:33:35 +00:00
$services->set(RenamePropertyRector::class)
->call('configure', [[
RenamePropertyRector::RENAMED_PROPERTIES => inline_value_objects([
new RenameProperty('SomeClass', 'someOldProperty', 'someNewProperty'),
]),
]]);
};
```
2018-09-28 16:33:35 +00:00
```diff
-$someObject->someOldProperty;
+$someObject->someNewProperty;
2018-09-28 16:33:35 +00:00
```
<br>
## RenamePropertyToMatchTypeRector
Rename property and method param to match its type
- class: `Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector`
```diff
class SomeClass
{
/**
* @var EntityManager
*/
- private $eventManager;
+ private $entityManager;
- public function __construct(EntityManager $eventManager)
+ public function __construct(EntityManager $entityManager)
{
- $this->eventManager = $eventManager;
+ $this->entityManager = $entityManager;
}
}
```
<br>
## RenameSpecFileToTestFileRector
Rename "*Spec.php" file to "*Test.php" file
- class: `Rector\PhpSpecToPHPUnit\Rector\FileNode\RenameSpecFileToTestFileRector`
```diff
-// tests/SomeSpec.php
+// tests/SomeTest.php
```
<br>
## RenameStaticMethodRector
Turns method names to new ones.
2020-07-24 11:46:57 +00:00
:wrench: **configure it!**
- class: `Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector;
use Rector\Renaming\ValueObject\RenameStaticMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(RenameStaticMethodRector::class)
->call('configure', [[
RenameStaticMethodRector::OLD_TO_NEW_METHODS_BY_CLASSES => inline_value_objects([
new RenameStaticMethod('SomeClass', 'oldMethod', 'AnotherExampleClass', 'newStaticMethod'),
]),
]]);
};
```
```diff
-SomeClass::oldStaticMethod();
+AnotherExampleClass::newStaticMethod();
```
<br>
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector;
use Rector\Renaming\ValueObject\RenameStaticMethod;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-05-01 23:56:58 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2019-05-01 23:56:58 +00:00
$services->set(RenameStaticMethodRector::class)
->call('configure', [[
RenameStaticMethodRector::OLD_TO_NEW_METHODS_BY_CLASSES => inline_value_objects([
new RenameStaticMethod('SomeClass', 'oldMethod', 'SomeClass', 'newStaticMethod'),
]),
]]);
};
```
2019-05-01 23:56:58 +00:00
2019-05-29 13:40:20 +00:00
```diff
-SomeClass::oldStaticMethod();
+SomeClass::newStaticMethod();
2019-05-01 23:56:58 +00:00
```
<br>
2019-05-01 23:56:58 +00:00
## RenameTesterTestToPHPUnitToTestFileRector
2019-10-15 14:46:31 +00:00
Rename "*.phpt" file to "*Test.php" file
2019-10-15 14:46:31 +00:00
- class: `Rector\NetteTesterToPHPUnit\Rector\FileNode\RenameTesterTestToPHPUnitToTestFileRector`
2019-10-15 14:46:31 +00:00
```diff
-// tests/SomeTestCase.phpt
+// tests/SomeTestCase.php
2019-10-15 14:46:31 +00:00
```
<br>
2019-10-15 14:46:31 +00:00
## RenameVariableToMatchMethodCallReturnTypeRector
Rename variable to match method return type
- class: `Rector\Naming\Rector\Assign\RenameVariableToMatchMethodCallReturnTypeRector`
```diff
class SomeClass
{
public function run()
{
- $a = $this->getRunner();
+ $runner = $this->getRunner();
}
public function getRunner(): Runner
{
return new Runner();
}
}
```
<br>
## RenameVariableToMatchNewTypeRector
Rename variable to match new ClassType
- class: `Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector`
2018-07-31 12:50:39 +00:00
```diff
final class SomeClass
{
public function run()
{
- $search = new DreamSearch();
- $search->advance();
+ $dreamSearch = new DreamSearch();
+ $dreamSearch->advance();
}
}
2018-07-31 12:50:39 +00:00
```
<br>
## RepeatedLiteralToClassConstantRector
2019-03-31 12:25:39 +00:00
Replace repeated strings with constant
2019-03-31 12:25:39 +00:00
- class: `Rector\SOLID\Rector\Class_\RepeatedLiteralToClassConstantRector`
2019-03-31 12:25:39 +00:00
```diff
class SomeClass
2019-03-31 12:25:39 +00:00
{
+ /**
+ * @var string
+ */
+ private const REQUIRES = 'requires';
public function run($key, $items)
2019-03-31 12:25:39 +00:00
{
- if ($key === 'requires') {
- return $items['requires'];
+ if ($key === self::REQUIRES) {
+ return $items[self::REQUIRES];
}
2019-03-31 12:25:39 +00:00
}
}
```
<br>
2019-03-31 12:25:39 +00:00
## ReplaceArrayWithObjectRector
2018-05-04 22:30:32 +00:00
Replace complex array configuration in configs with value object
:wrench: **configure it!**
- class: `Rector\SymfonyPhpConfig\Rector\ArrayItem\ReplaceArrayWithObjectRector`
```php
use Rector\Renaming\Rector\MethodCall\RenameMethodRector;
use Rector\Renaming\ValueObject\MethodCallRename;
use Rector\SymfonyPhpConfig\Rector\ArrayItem\ReplaceArrayWithObjectRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReplaceArrayWithObjectRector::class)
->call('configure', [[
ReplaceArrayWithObjectRector::CONSTANT_NAMES_TO_VALUE_OBJECTS => [
RenameMethodRector::OLD_TO_NEW_METHODS_BY_CLASS => MethodCallRename::class,
],
]]);
};
```
2018-05-04 22:30:32 +00:00
```diff
use Rector\Renaming\Rector\MethodCall\RenameMethodRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2018-05-04 22:30:32 +00:00
$services->set(RenameMethodRector::class)
->call('configure', [[
- RenameMethodRector::OLD_TO_NEW_METHODS_BY_CLASS => [
- 'Illuminate\Auth\Access\Gate' => [
- 'access' => 'inspect',
- ]
- ]]
- ]);
+ RenameMethodRector::OLD_TO_NEW_METHODS_BY_CLASS => \Rector\SymfonyPhpConfig\inline_value_objects([
+ new \Rector\Renaming\ValueObject\MethodCallRename('Illuminate\Auth\Access\Gate', 'access', 'inspect'),
+ ])
+ ]]);
}
```
<br>
## ReplaceAssertArraySubsetWithDmsPolyfillRector
Change `assertArraySubset()` to static call of DMS\PHPUnitExtensions\ArraySubset\Assert
- class: `Rector\PHPUnit\Rector\MethodCall\ReplaceAssertArraySubsetWithDmsPolyfillRector`
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
public function test()
{
- self::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
+ \DMS\PHPUnitExtensions\ArraySubset\Assert::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
- $this->assertArraySubset(['bar' => 0], ['bar' => '0'], true);
+ \DMS\PHPUnitExtensions\ArraySubset\Assert::assertArraySubset(['bar' => 0], ['bar' => '0'], true);
}
}
```
<br>
## ReplaceEachAssignmentWithKeyCurrentRector
2018-05-04 22:30:32 +00:00
Replace `each()` assign outside loop
- class: `Rector\Php72\Rector\Assign\ReplaceEachAssignmentWithKeyCurrentRector`
```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>
## ReplaceEventManagerWithEventSubscriberRector
Change Kdyby EventManager to EventDispatcher
- class: `Rector\NetteKdyby\Rector\MethodCall\ReplaceEventManagerWithEventSubscriberRector`
```diff
use Kdyby\Events\EventManager;
final class SomeClass
{
/**
* @var EventManager
*/
private $eventManager;
public function __construct(EventManager $eventManager)
{
$this->eventManager = eventManager;
}
2018-05-04 22:30:32 +00:00
public function run()
{
$key = '2000';
- $this->eventManager->dispatchEvent(static::class . '::onCopy', new EventArgsList([$this, $key]));
+ $this->eventManager->dispatch(new SomeClassCopyEvent($this, $key));
}
}
2018-05-04 22:30:32 +00:00
```
<br>
## ReplaceHttpServerVarsByServerRector
Rename old `$HTTP_*` variable names to new replacements
- class: `Rector\Php53\Rector\Variable\ReplaceHttpServerVarsByServerRector`
```diff
-$serverVars = $HTTP_SERVER_VARS;
+$serverVars = $_SERVER;
```
<br>
## ReplaceMagicEventPropertySubscriberWithEventClassSubscriberRector
2018-05-04 22:30:32 +00:00
Change `getSubscribedEvents()` from on magic property, to Event class
2018-05-04 22:30:32 +00:00
- class: `Rector\NetteKdyby\Rector\ClassMethod\ReplaceMagicEventPropertySubscriberWithEventClassSubscriberRector`
2018-05-04 22:30:32 +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
{
+ $album = $albumServiceApproveEventAlbum->getAlbum();
$album->play();
}
}
```
2018-10-23 18:58:57 +00:00
<br>
## ReplaceMagicPropertyEventWithEventClassRector
2018-10-23 18:58:57 +00:00
Change `$onProperty` magic call with event disptacher and class dispatch
2018-10-23 18:58:57 +00:00
- class: `Rector\NetteKdyby\Rector\MethodCall\ReplaceMagicPropertyEventWithEventClassRector`
```diff
final class FileManager
{
- public $onUpload;
+ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
+ public function __construct(EventDispatcherInterface $eventDispatcher)
+ {
+ $this->eventDispatcher = $eventDispatcher;
+ }
+
public function run(User $user)
{
- $this->onUpload($user);
+ $onFileManagerUploadEvent = new FileManagerUploadEvent($user);
+ $this->eventDispatcher->dispatch($onFileManagerUploadEvent);
}
2019-05-29 13:40:20 +00:00
}
2018-10-12 23:15:00 +00:00
```
<br>
2018-10-23 18:58:57 +00:00
## ReplaceParentCallByPropertyCallRector
2018-10-23 18:58:57 +00:00
Changes method calls in child of specific types to defined property method call
:wrench: **configure it!**
- class: `Rector\Transform\Rector\MethodCall\ReplaceParentCallByPropertyCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\MethodCall\ReplaceParentCallByPropertyCallRector;
use Rector\Transform\ValueObject\ReplaceParentCallByPropertyCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(ReplaceParentCallByPropertyCallRector::class)
->call('configure', [[
ReplaceParentCallByPropertyCallRector::PARENT_CALLS_TO_PROPERTIES => inline_value_objects([
new ReplaceParentCallByPropertyCall('SomeTypeToReplace', 'someMethodCall', 'someProperty'),
]),
]]);
};
```
2018-10-23 18:58:57 +00:00
```diff
final class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run(SomeTypeToReplace $someTypeToReplace)
2019-05-29 13:40:20 +00:00
{
- $someTypeToReplace->someMethodCall();
+ $this->someProperty->someMethodCall();
2019-05-29 13:40:20 +00:00
}
}
```
<br>
## ReplaceParentRepositoryCallsByRepositoryPropertyRector
Handles method calls in child of Doctrine EntityRepository and moves them to `$this->repository` property.
- class: `Rector\Architecture\Rector\MethodCall\ReplaceParentRepositoryCallsByRepositoryPropertyRector`
```diff
<?php
use Doctrine\ORM\EntityRepository;
class SomeRepository extends EntityRepository
{
public function someMethod()
2019-05-29 13:40:20 +00:00
{
- return $this->findAll();
+ return $this->repository->findAll();
2019-05-29 13:40:20 +00:00
}
}
```
<br>
## ReplaceSensioRouteAnnotationWithSymfonyRector
Replace Sensio `@Route` annotation with Symfony one
- class: `Rector\Sensio\Rector\ClassMethod\ReplaceSensioRouteAnnotationWithSymfonyRector`
```diff
-use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
+use Symfony\Component\Routing\Annotation\Route;
final class SomeClass
{
/**
* @Route()
*/
public function run()
{
}
}
```
<br>
## ReplaceTimeNumberWithDateTimeConstantRector
Replace `time` numbers with `Nette\Utils\DateTime` constants
- class: `Rector\NetteUtilsCodeQuality\Rector\LNumber\ReplaceTimeNumberWithDateTimeConstantRector`
```diff
final class SomeClass
{
public function run()
{
- return 86400;
+ return \Nette\Utils\DateTime::DAY;
}
}
```
<br>
## ReplaceVariableByPropertyFetchRector
Turns variable in controller action to property fetch, as follow up to action injection variable to property change.
- class: `Rector\Generic\Rector\Variable\ReplaceVariableByPropertyFetchRector`
```diff
final class SomeController
{
/**
* @var ProductRepository
*/
private $productRepository;
public function __construct(ProductRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public function default()
{
- $products = $productRepository->fetchAll();
+ $products = $this->productRepository->fetchAll();
}
}
```
<br>
## RequestGetCookieDefaultArgumentToCoalesceRector
2019-06-06 13:01:53 +00:00
Add removed `Nette\Http\Request::getCookies()` default value as coalesce
2019-06-06 13:01:53 +00:00
- class: `Rector\Nette\Rector\MethodCall\RequestGetCookieDefaultArgumentToCoalesceRector`
```diff
use Nette\Http\Request;
class SomeClass
{
public function run(Request $request)
{
- return $request->getCookie('name', 'default');
+ return $request->getCookie('name') ?? 'default';
}
}
```
<br>
## RequestStaticValidateToInjectRector
Change static `validate()` method to `$request->validate()`
- class: `Rector\Laravel\Rector\StaticCall\RequestStaticValidateToInjectRector`
2019-06-06 13:01:53 +00:00
```diff
use Illuminate\Http\Request;
2019-06-06 13:01:53 +00:00
class SomeClass
2019-06-06 13:01:53 +00:00
{
- public function store()
+ public function store(\Illuminate\Http\Request $request)
2019-06-06 13:01:53 +00:00
{
- $validatedData = Request::validate(['some_attribute' => 'required']);
+ $validatedData = $request->validate(['some_attribute' => 'required']);
2019-06-06 13:01:53 +00:00
}
}
```
<br>
## ReservedFnFunctionRector
Change `fn()` function name, since it will be reserved keyword
:wrench: **configure it!**
- class: `Rector\Php74\Rector\Function_\ReservedFnFunctionRector`
```php
use Rector\Php74\Rector\Function_\ReservedFnFunctionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ReservedFnFunctionRector::class)
->call('configure', [[
ReservedFnFunctionRector::RESERVED_NAMES_TO_NEW_ONES => [
'fn' => 'someFunctionName',
],
]]);
};
```
```diff
class SomeClass
{
public function run()
{
- function fn($value)
+ function f($value)
{
return $value;
}
- fn(5);
+ f(5);
}
}
```
<br>
## ReservedObjectRector
2019-05-29 13:40:20 +00:00
Changes reserved "Object" name to "<Smart>Object" where <Smart> can be configured
:wrench: **configure it!**
2019-05-29 13:40:20 +00:00
- class: `Rector\Php71\Rector\Name\ReservedObjectRector`
```php
use Rector\Php71\Rector\Name\ReservedObjectRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-09-25 08:49:53 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(ReservedObjectRector::class)
->call('configure', [[
ReservedObjectRector::RESERVED_KEYWORDS_TO_REPLACEMENTS => [
'ReservedObject' => 'SmartObject',
'Object' => 'AnotherSmartObject',
],
]]);
};
```
2019-09-25 08:49:53 +00:00
2019-09-25 08:49:53 +00:00
```diff
-class Object
+class SmartObject
2019-09-25 08:49:53 +00:00
{
}
```
<br>
2019-09-25 08:49:53 +00:00
## ResponseStatusCodeRector
2019-05-29 13:40:20 +00:00
Turns status code numbers to constants
2019-05-29 13:40:20 +00:00
- class: `Rector\Symfony\Rector\BinaryOp\ResponseStatusCodeRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeController
{
public function index()
{
$response = new \Symfony\Component\HttpFoundation\Response();
- $response->setStatusCode(200);
+ $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
2019-05-29 13:40:20 +00:00
- if ($response->getStatusCode() === 200) {}
+ if ($response->getStatusCode() === \Symfony\Component\HttpFoundation\Response::HTTP_OK) {}
}
}
```
<br>
2019-05-29 13:40:20 +00:00
## RestoreDefaultNullToNullableTypePropertyRector
Add null default to properties with PHP 7.4 property nullable type
2019-05-29 13:40:20 +00:00
- class: `Rector\Php74\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
- public ?string $name;
+ public ?string $name = null;
}
```
2018-10-23 18:58:57 +00:00
<br>
## RestoreFullyQualifiedNameRector
2018-05-04 22:30:32 +00:00
Restore accidentally shortened class names to its fully qualified form.
2018-07-31 12:50:39 +00:00
- class: `Rector\Restoration\Rector\Use_\RestoreFullyQualifiedNameRector`
```diff
-use ShortClassOnly;
+use App\Whatever\ShortClassOnly;
class AnotherClass
{
}
```
<br>
## ReturnArrayClassMethodToYieldRector
Turns array return to yield return in specific type and method
:wrench: **configure it!**
- class: `Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector;
use Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(ReturnArrayClassMethodToYieldRector::class)
->call('configure', [[
ReturnArrayClassMethodToYieldRector::METHODS_TO_YIELDS => inline_value_objects([
new ReturnArrayClassMethodToYield('EventSubscriberInterface', 'getSubscribedEvents'),
]),
]]);
};
```
```diff
class SomeEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- return ['event' => 'callback'];
+ yield 'event' => 'callback';
}
}
```
<br>
## ReturnFluentChainMethodCallToNormalMethodCallRector
Turns fluent interface calls to classic ones.
- class: `Rector\Defluent\Rector\Return_\ReturnFluentChainMethodCallToNormalMethodCallRector`
```diff
$someClass = new SomeClass();
-return $someClass->someFunction()
- ->otherFunction();
+$someClass->someFunction();
+$someClass->otherFunction();
+return $someClass;
```
<br>
## ReturnNewFluentChainMethodCallToNonFluentRector
Turns fluent interface calls to classic ones.
- class: `Rector\Defluent\Rector\Return_\ReturnNewFluentChainMethodCallToNonFluentRector`
```diff
-return (new SomeClass())->someFunction()
- ->otherFunction();
+$someClass = new SomeClass();
+$someClass->someFunction();
+$someClass->otherFunction();
+return $someClass;
```
<br>
## ReturnThisRemoveRector
Removes "return `$this;"` from *fluent interfaces* for specified classes.
- class: `Rector\Defluent\Rector\ClassMethod\ReturnThisRemoveRector`
```diff
class SomeExampleClass
{
public function someFunction()
{
- return $this;
}
public function otherFunction()
{
- return $this;
}
}
2018-05-04 22:30:32 +00:00
```
<br>
## ReturnTypeDeclarationRector
Change `@return` types and type from static analysis to type declarations if not a BC-break
- class: `Rector\TypeDeclaration\Rector\FunctionLike\ReturnTypeDeclarationRector`
```diff
<?php
2019-05-29 13:40:20 +00:00
class SomeClass
{
- /**
- * @return int
- */
- public function getCount()
+ public function getCount(): int
{
}
}
```
<br>
## RootNodeTreeBuilderRector
Changes Process string argument to an array
- class: `Rector\Symfony\Rector\New_\RootNodeTreeBuilderRector`
```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();
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
## RouterListToControllerAnnotationsRector
2019-05-29 13:40:20 +00:00
Change new `Route()` from RouteFactory to `@Route` annotation above controller method
2019-05-29 13:40:20 +00:00
- class: `Rector\NetteToSymfony\Rector\ClassMethod\RouterListToControllerAnnotationsRector`
2019-05-29 13:40:20 +00:00
```diff
final class RouterFactory
{
public function create(): RouteList
{
$routeList = new RouteList();
+
+ // case of single action controller, usually get() or __invoke() method
$routeList[] = new Route('some-path', SomePresenter::class);
return $routeList;
}
}
+use Symfony\Component\Routing\Annotation\Route;
+
final class SomePresenter
{
+ /**
+ * @Route(path="some-path")
+ */
public function run()
{
}
}
```
<br>
## SelfContainerGetMethodCallFromTestToInjectPropertyRector
Change `$container->get()` calls in PHPUnit to `@inject` properties autowired by jakzal/phpunit-injector
- class: `Rector\PHPUnit\Rector\Class_\SelfContainerGetMethodCallFromTestToInjectPropertyRector`
```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
{
}
```
<br>
## SelfContainerGetMethodCallFromTestToSetUpMethodRector
Move self::$container service fetching from test methods up to setUp method
- class: `Rector\SymfonyPHPUnit\Rector\Class_\SelfContainerGetMethodCallFromTestToSetUpMethodRector`
```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();
}
}
```
<br>
## SensitiveConstantNameRector
Changes case insensitive constants to sensitive ones.
- class: `Rector\Php73\Rector\ConstFetch\SensitiveConstantNameRector`
```diff
define('FOO', 42, true);
var_dump(FOO);
-var_dump(foo);
+var_dump(FOO);
```
<br>
## SensitiveDefineRector
Changes case insensitive constants to sensitive ones.
- class: `Rector\Php73\Rector\FuncCall\SensitiveDefineRector`
```diff
-define('FOO', 42, true);
+define('FOO', 42);
```
<br>
## SensitiveHereNowDocRector
Changes heredoc/nowdoc that contains closing word to safe wrapper name
- class: `Rector\Php73\Rector\String_\SensitiveHereNowDocRector`
```diff
-$value = <<<A
+$value = <<<A_WRAP
A
-A
+A_WRAP
```
<br>
## ServiceEntityRepositoryParentCallToDIRector
Change ServiceEntityRepository to dependency injection, with repository property
- class: `Rector\Doctrine\Rector\ClassMethod\ServiceEntityRepositoryParentCallToDIRector`
```diff
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
final class ProjectRepository extends ServiceEntityRepository
{
- public function __construct(ManagerRegistry $registry)
+ /**
+ * @var \Doctrine\ORM\EntityManagerInterface
+ */
+ private $entityManager;
+
+ /**
+ * @var \Doctrine\ORM\EntityRepository<Project>
+ */
+ private $repository;
+
+ public function __construct(\Doctrine\ORM\EntityManagerInterface $entityManager)
{
- parent::__construct($registry, Project::class);
+ $this->repository = $entityManager->getRepository(Project::class);
+ $this->entityManager = $entityManager;
}
}
```
<br>
## ServiceGetterToConstructorInjectionRector
Get service call to constructor injection
:wrench: **configure it!**
- class: `Rector\Transform\Rector\MethodCall\ServiceGetterToConstructorInjectionRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\MethodCall\ServiceGetterToConstructorInjectionRector;
use Rector\Transform\ValueObject\ServiceGetterToConstructorInjection;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(ServiceGetterToConstructorInjectionRector::class)
->call('configure', [[
ServiceGetterToConstructorInjectionRector::METHOD_CALL_TO_SERVICES => inline_value_objects([
new ServiceGetterToConstructorInjection('FirstService', 'getAnotherService', 'AnotherService'),
]),
]]);
};
```
```diff
final class SomeClass
{
/**
* @var FirstService
*/
private $firstService;
- public function __construct(FirstService $firstService)
- {
- $this->firstService = $firstService;
- }
-
- public function run()
- {
- $anotherService = $this->firstService->getAnotherService();
- $anotherService->run();
- }
-}
-
-class FirstService
-{
/**
* @var AnotherService
*/
private $anotherService;
- public function __construct(AnotherService $anotherService)
+ public function __construct(FirstService $firstService, AnotherService $anotherService)
{
+ $this->firstService = $firstService;
$this->anotherService = $anotherService;
}
- public function getAnotherService(): AnotherService
+ public function run()
{
- return $this->anotherService;
+ $anotherService = $this->anotherService;
+ $anotherService->run();
}
}
```
<br>
2019-08-05 21:10:47 +00:00
## ServiceLocatorToDIRector
Turns `$this->getRepository()` in Symfony Controller to constructor injection and private property access.
2019-08-05 21:10:47 +00:00
- class: `Rector\Architecture\Rector\MethodCall\ServiceLocatorToDIRector`
```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(...);
}
}
```
2019-08-05 21:10:47 +00:00
<br>
## SetClassWithArgumentToSetFactoryRector
Change setClass with class and arguments to separated methods
- class: `Rector\Nette\Rector\MethodCall\SetClassWithArgumentToSetFactoryRector`
2019-08-05 21:10:47 +00:00
```diff
use Nette\DI\ContainerBuilder;
class SomeClass
2019-08-05 21:10:47 +00:00
{
public function run(ContainerBuilder $containerBuilder)
{
$containerBuilder->addDefinition('...')
- ->setClass('SomeClass', [1, 2]);
+ ->setFactory('SomeClass', [1, 2]);
}
}
2019-08-05 21:10:47 +00:00
```
<br>
2019-08-05 21:10:47 +00:00
## SetCookieRector
Convert `setcookie` argument to PHP7.3 option array
- class: `Rector\Php73\Rector\FuncCall\SetCookieRector`
```diff
-setcookie('name', $value, 360);
+setcookie('name', $value, ['expires' => 360]);
```
2019-09-21 22:14:49 +00:00
<br>
```diff
-setcookie('name', $name, 0, '', '', true, true);
+setcookie('name', $name, ['expires' => 0, 'path' => '', 'domain' => '', 'secure' => true, 'httponly' => true]);
```
<br>
## SetTypeToCastRector
Changes `settype()` to (type) where possible
- class: `Rector\CodeQuality\Rector\FuncCall\SetTypeToCastRector`
```diff
class SomeClass
{
- public function run($foo)
+ public function run(array $items)
{
- settype($foo, 'string');
+ $foo = (string) $foo;
- return settype($foo, 'integer');
+ return (int) $foo;
}
}
```
<br>
## ShortenElseIfRector
Shortens else/if to elseif
- class: `Rector\CodeQuality\Rector\If_\ShortenElseIfRector`
```diff
class SomeClass
{
public function run()
{
if ($cond1) {
return $action1;
- } else {
- if ($cond2) {
- return $action2;
- }
+ } elseif ($cond2) {
+ return $action2;
}
}
}
```
<br>
## SimpleFunctionAndFilterRector
Changes Twig_Function_Method to Twig_SimpleFunction calls in Twig_Extension.
- class: `Rector\Twig\Rector\Return_\SimpleFunctionAndFilterRector`
```diff
class SomeExtension extends Twig_Extension
{
public function getFunctions()
{
return [
- 'is_mobile' => new Twig_Function_Method($this, 'isMobile'),
+ new Twig_SimpleFunction('is_mobile', [$this, 'isMobile']),
];
}
public function getFilters()
{
return [
- 'is_mobile' => new Twig_Filter_Method($this, 'isMobile'),
+ new Twig_SimpleFilter('is_mobile', [$this, 'isMobile']),
];
}
}
```
<br>
## SimplifyArraySearchRector
Simplify `array_search` to `in_array`
- class: `Rector\CodeQuality\Rector\Identical\SimplifyArraySearchRector`
```diff
-array_search("searching", $array) !== false;
+in_array("searching", $array);
```
<br>
```diff
-array_search("searching", $array, true) !== false;
+in_array("searching", $array, true);
```
<br>
## SimplifyBoolIdenticalTrueRector
2018-09-28 16:33:35 +00:00
Symplify bool value compare to true or false
2018-09-28 16:33:35 +00:00
- class: `Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector`
2018-09-28 16:33:35 +00:00
```diff
class SomeClass
2018-09-28 16:33:35 +00:00
{
public function run(bool $value, string $items)
2018-09-28 16:33:35 +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-09-28 16:33:35 +00:00
}
}
```
<br>
## SimplifyConditionsRector
2019-08-17 13:06:02 +00:00
Simplify conditions
2019-08-17 13:06:02 +00:00
- class: `Rector\CodeQuality\Rector\Identical\SimplifyConditionsRector`
2019-08-17 13:06:02 +00:00
```diff
-if (! ($foo !== 'bar')) {...
+if ($foo === 'bar') {...
2019-08-17 13:06:02 +00:00
```
<br>
2019-08-17 13:06:02 +00:00
## SimplifyDeMorganBinaryRector
2019-08-17 13:06:02 +00:00
Simplify negated conditions with de Morgan theorem
2019-08-17 13:06:02 +00:00
- class: `Rector\CodeQuality\Rector\BooleanNot\SimplifyDeMorganBinaryRector`
2019-08-17 13:06:02 +00:00
```diff
<?php
2019-08-17 13:06:02 +00:00
$a = 5;
$b = 10;
-$result = !($a > 20 || $b <= 50);
+$result = $a <= 20 && $b > 50;
```
<br>
## SimplifyDuplicatedTernaryRector
Remove ternary that duplicated return value of true : false
- class: `Rector\CodeQuality\Rector\Ternary\SimplifyDuplicatedTernaryRector`
```diff
class SomeClass
{
public function run(bool $value, string $name)
2019-08-17 13:06:02 +00:00
{
- $isTrue = $value ? true : false;
+ $isTrue = $value;
$isName = $name ? true : false;
2019-08-17 13:06:02 +00:00
}
}
```
<br>
2019-08-17 13:06:02 +00:00
## SimplifyEmptyArrayCheckRector
Simplify `is_array` and `empty` functions combination into a simple identical check for an empty array
- class: `Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector`
```diff
-is_array($values) && empty($values)
+$values === []
```
<br>
## SimplifyForeachInstanceOfRector
Simplify unnecessary foreach check of instances
- class: `Rector\PHPUnit\Rector\Foreach_\SimplifyForeachInstanceOfRector`
```diff
-foreach ($foos as $foo) {
- $this->assertInstanceOf(SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);
```
<br>
2019-05-19 08:27:38 +00:00
## SimplifyForeachToArrayFilterRector
2019-05-19 08:27:38 +00:00
Simplify foreach with function filtering to array filter
- class: `Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToArrayFilterRector`
2019-05-19 08:27:38 +00:00
```diff
-$directories = [];
$possibleDirectories = [];
-foreach ($possibleDirectories as $possibleDirectory) {
- if (file_exists($possibleDirectory)) {
- $directories[] = $possibleDirectory;
- }
-}
+$directories = array_filter($possibleDirectories, 'file_exists');
2019-09-25 08:49:53 +00:00
```
<br>
2019-09-25 08:49:53 +00:00
## SimplifyForeachToCoalescingRector
Changes foreach that returns set value to ??
- class: `Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToCoalescingRector`
```diff
-foreach ($this->oldToNewFunctions as $oldFunction => $newFunction) {
- if ($currentFunction === $oldFunction) {
- return $newFunction;
- }
-}
-
-return null;
+return $this->oldToNewFunctions[$currentFunction] ?? null;
```
<br>
## SimplifyFuncGetArgsCountRector
Simplify `count` of `func_get_args()` to `func_num_args()`
- class: `Rector\CodeQuality\Rector\FuncCall\SimplifyFuncGetArgsCountRector`
```diff
-count(func_get_args());
+func_num_args();
```
<br>
## SimplifyIfElseToTernaryRector
2019-09-25 08:49:53 +00:00
Changes if/else for same value as assign to ternary
2019-09-25 08:49:53 +00:00
- class: `Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector`
2019-09-25 08:49:53 +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;
2019-09-25 08:49:53 +00:00
}
}
```
<br>
2019-09-25 08:49:53 +00:00
## SimplifyIfElseWithSameContentRector
2020-07-24 11:46:57 +00:00
Remove if/else if they have same content
2019-12-18 09:53:46 +00:00
- class: `Rector\DeadCode\Rector\If_\SimplifyIfElseWithSameContentRector`
2019-12-18 09:53:46 +00:00
```diff
class SomeClass
{
public function run()
2019-12-18 09:53:46 +00:00
{
- if (true) {
- return 1;
- } else {
- return 1;
- }
+ return 1;
2019-12-18 09:53:46 +00:00
}
}
```
<br>
2019-12-18 09:53:46 +00:00
## SimplifyIfIssetToNullCoalescingRector
2019-09-25 08:49:53 +00:00
Simplify binary if to null coalesce
2019-09-25 08:49:53 +00:00
- class: `Rector\CodeQuality\Rector\If_\SimplifyIfIssetToNullCoalescingRector`
2019-09-25 08:49:53 +00:00
```diff
final class SomeController
2019-09-25 08:49:53 +00:00
{
public function run($possibleStatieYamlFile)
2019-09-25 08:49:53 +00:00
{
- if (isset($possibleStatieYamlFile['import'])) {
- $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'], $filesToImport);
- } else {
- $possibleStatieYamlFile['import'] = $filesToImport;
- }
+ $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'] ?? [], $filesToImport);
2019-05-19 08:27:38 +00:00
}
}
```
<br>
2019-05-19 08:27:38 +00:00
## SimplifyIfNotNullReturnRector
2019-05-19 08:27:38 +00:00
Changes redundant null check to instant return
2019-05-19 08:27:38 +00:00
- class: `Rector\CodeQuality\Rector\If_\SimplifyIfNotNullReturnRector`
2019-05-19 08:27:38 +00:00
```diff
$newNode = 'something ;
-if ($newNode !== null) {
- return $newNode;
-}
-
-return null;
+return $newNode;
2019-05-19 08:27:38 +00:00
```
<br>
2019-05-19 08:27:38 +00:00
## SimplifyIfReturnBoolRector
2019-08-05 21:10:47 +00:00
Shortens if return false/true to direct return
2019-08-05 21:10:47 +00:00
- class: `Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector`
2019-08-05 21:10:47 +00:00
```diff
-if (strpos($docToken->getContent(), "\n") === false) {
- return true;
-}
-
-return false;
+return strpos($docToken->getContent(), "\n") === false;
```
<br>
2019-08-05 21:10:47 +00:00
## SimplifyInArrayValuesRector
2018-05-04 22:30:32 +00:00
Removes unneeded `array_values()` in `in_array()` call
2018-08-01 20:09:34 +00:00
- class: `Rector\CodeQuality\Rector\FuncCall\SimplifyInArrayValuesRector`
2018-05-04 22:30:32 +00:00
```diff
-in_array("key", array_values($array), true);
+in_array("key", $array, true);
```
<br>
## SimplifyMirrorAssignRector
Removes unneeded $a = $a assigns
- class: `Rector\DeadCode\Rector\Expression\SimplifyMirrorAssignRector`
```diff
-$a = $a;
```
<br>
## SimplifyRegexPatternRector
Simplify regex pattern to known ranges
- class: `Rector\CodeQuality\Rector\FuncCall\SimplifyRegexPatternRector`
```diff
class SomeClass
2018-08-01 20:09:34 +00:00
{
public function run($value)
{
- preg_match('#[a-zA-Z0-9+]#', $value);
+ preg_match('#[\w\d+]#', $value);
}
2018-08-01 20:09:34 +00:00
}
2018-05-04 22:30:32 +00:00
```
<br>
## SimplifyStrposLowerRector
Simplify `strpos(strtolower(),` "...") calls
- class: `Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector`
```diff
-strpos(strtolower($var), "...")"
+stripos($var, "...")"
```
<br>
## SimplifyTautologyTernaryRector
2019-12-19 22:07:06 +00:00
Simplify tautology ternary to value
2019-12-19 22:07:06 +00:00
- class: `Rector\CodeQuality\Rector\Ternary\SimplifyTautologyTernaryRector`
2019-12-19 22:07:06 +00:00
```diff
-$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;
+$value = $fullyQualifiedTypeHint;
```
2020-07-24 11:46:57 +00:00
<br>
## SimplifyUselessVariableRector
2020-07-24 11:46:57 +00:00
Removes useless variable assigns
- class: `Rector\CodeQuality\Rector\Return_\SimplifyUselessVariableRector`
```diff
function () {
- $a = true;
- return $a;
+ return true;
};
2019-12-19 22:07:06 +00:00
```
<br>
## SimplifyWebTestCaseAssertionsRector
Simplify use of assertions in WebTestCase
- class: `Rector\Symfony\Rector\MethodCall\SimplifyWebTestCaseAssertionsRector`
2019-12-19 22:07:06 +00:00
```diff
use PHPUnit\Framework\TestCase;
class SomeClass extends TestCase
{
public function test()
{
- $this->assertSame(200, $client->getResponse()->getStatusCode());
+ $this->assertResponseIsSuccessful();
}
public function testUrl()
{
- $this->assertSame(301, $client->getResponse()->getStatusCode());
- $this->assertSame('https://example.com', $client->getResponse()->headers->get('Location'));
+ $this->assertResponseRedirects('https://example.com', 301);
}
public function testContains()
{
- $this->assertContains('Hello World', $crawler->filter('h1')->text());
+ $this->assertSelectorTextContains('h1', 'Hello World');
}
2019-12-19 22:07:06 +00:00
}
```
<br>
2019-12-19 22:07:06 +00:00
## SingleInArrayToCompareRector
2019-06-06 13:01:53 +00:00
Changes `in_array()` with single element to ===
2019-06-06 13:01:53 +00:00
- class: `Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector`
2019-06-06 13:01:53 +00:00
```diff
class SomeClass
2019-06-06 13:01:53 +00:00
{
public function run()
2019-06-06 13:01:53 +00:00
{
- if (in_array(strtolower($type), ['$this'], true)) {
+ if (strtolower($type) === '$this') {
return strtolower($type);
}
2019-06-06 13:01:53 +00:00
}
}
```
<br>
## SingleStaticServiceToDynamicRector
2019-06-06 13:01:53 +00:00
Change full static service, to dynamic one
2020-07-24 11:46:57 +00:00
:wrench: **configure it!**
2018-05-04 22:30:32 +00:00
- class: `Rector\RemovingStatic\Rector\Class_\SingleStaticServiceToDynamicRector`
```php
use Rector\RemovingStatic\Rector\Class_\SingleStaticServiceToDynamicRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SingleStaticServiceToDynamicRector::class)
->call('configure', [[
SingleStaticServiceToDynamicRector::CLASS_TYPES => ['SomeClass'],
]]);
};
```
2018-08-01 20:09:34 +00:00
```diff
class AnotherClass
2019-05-29 13:40:20 +00:00
{
+ /**
+ * @var SomeClass
+ */
+ private $someClass;
+
+ public fuction __construct(SomeClass $someClass)
+ {
+ $this->someClass = $someClass;
+ }
+
public function run()
{
SomeClass::someStatic();
}
}
class SomeClass
{
- public static function run()
+ public function run()
{
- self::someStatic();
+ $this->someStatic();
}
- private static function someStatic()
+ private function someStatic()
2019-12-26 10:21:09 +00:00
{
}
2019-05-29 13:40:20 +00:00
}
2018-08-01 20:09:34 +00:00
```
<br>
## SluggableBehaviorRector
Change Sluggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
- class: `Rector\DoctrineGedmoToKnplabs\Rector\Class_\SluggableBehaviorRector`
2018-05-04 22:30:32 +00:00
```diff
use Gedmo\Mapping\Annotation as Gedmo;
+use Knp\DoctrineBehaviors\Model\Sluggable\SluggableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\SluggableInterface;
-class SomeClass
+class SomeClass implements SluggableInterface
{
+ use SluggableTrait;
+
/**
- * @Gedmo\Slug(fields={"name"})
+ * @return string[]
*/
- private $slug;
-
- public function getSlug(): ?string
+ public function getSluggableFields(): array
{
- return $this->slug;
- }
-
- public function setSlug(?string $slug): void
- {
- $this->slug = $slug;
+ return ['name'];
}
}
```
<br>
## SoftDeletableBehaviorRector
Change SoftDeletable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
- class: `Rector\DoctrineGedmoToKnplabs\Rector\Class_\SoftDeletableBehaviorRector`
```diff
-use Gedmo\Mapping\Annotation as Gedmo;
+use Knp\DoctrineBehaviors\Contract\Entity\SoftDeletableInterface;
+use Knp\DoctrineBehaviors\Model\SoftDeletable\SoftDeletableTrait;
-/**
- * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=true)
- */
-class SomeClass
+class SomeClass implements SoftDeletableInterface
{
- /**
- * @ORM\Column(name="deletedAt", type="datetime", nullable=true)
- */
- private $deletedAt;
-
- public function getDeletedAt()
- {
- return $this->deletedAt;
- }
-
- public function setDeletedAt($deletedAt)
- {
- $this->deletedAt = $deletedAt;
- }
+ use SoftDeletableTrait;
}
```
<br>
2020-07-24 11:46:57 +00:00
## SpecificAssertContainsRector
2020-07-24 11:46:57 +00:00
Change `assertContains()/assertNotContains()` method to new string and iterable alternatives
2018-05-04 22:30:32 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\SpecificAssertContainsRector`
2018-05-04 22:30:32 +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');
}
}
2018-05-04 22:30:32 +00:00
```
<br>
2020-07-24 11:46:57 +00:00
## SpecificAssertContainsWithoutIdentityRector
2020-07-24 11:46:57 +00:00
Change `assertContains()/assertNotContains()` with non-strict comparison to new specific alternatives
2018-08-01 20:09:34 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\SpecificAssertContainsWithoutIdentityRector`
2018-05-04 22:30:32 +00:00
```diff
<?php
-final class SomeTest extends \PHPUnit\Framework\TestCase
+final class SomeTest extends TestCase
2019-05-29 13:40:20 +00:00
{
public function test()
2019-05-29 13:40:20 +00:00
{
$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');
2019-05-29 13:40:20 +00:00
}
}
2018-05-04 22:30:32 +00:00
```
<br>
## SpecificAssertInternalTypeRector
2019-03-16 20:31:46 +00:00
Change `assertInternalType()/assertNotInternalType()` method to new specific alternatives
2019-03-16 20:31:46 +00:00
- class: `Rector\PHPUnit\Rector\MethodCall\SpecificAssertInternalTypeRector`
2019-03-16 20:31:46 +00:00
```diff
final class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
$value = 'value';
- $this->assertInternalType('string', $value);
- $this->assertNotInternalType('array', $value);
+ $this->assertIsString($value);
+ $this->assertIsNotArray($value);
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## SplitDoubleAssignRector
2019-03-16 20:31:46 +00:00
Split multiple inline assigns to `each` own lines default value, to prevent undefined array issues
- class: `Rector\CodingStyle\Rector\Assign\SplitDoubleAssignRector`
2019-03-16 20:31:46 +00:00
```diff
class SomeClass
{
public function run()
{
- $one = $two = 1;
+ $one = 1;
+ $two = 1;
}
}
2019-03-16 20:31:46 +00:00
```
<br>
2019-03-16 20:31:46 +00:00
## SplitGroupedConstantsAndPropertiesRector
2020-07-24 11:46:57 +00:00
Separate constant and properties to own lines
2018-08-01 20:09:34 +00:00
- class: `Rector\CodingStyle\Rector\ClassConst\SplitGroupedConstantsAndPropertiesRector`
2018-05-04 22:30:32 +00:00
```diff
class SomeClass
{
- const HI = true, AHOJ = 'true';
+ const HI = true;
+ const AHOJ = 'true';
/**
* @var string
*/
- public $isIt, $isIsThough;
+ public $isIt;
+
+ /**
+ * @var string
+ */
+ public $isIsThough;
}
2018-05-04 22:30:32 +00:00
```
<br>
## SplitGroupedUseImportsRector
Split grouped use imports and trait statements to standalone lines
- class: `Rector\CodingStyle\Rector\Use_\SplitGroupedUseImportsRector`
```diff
-use A, B;
+use A;
+use B;
class SomeClass
{
- use SomeTrait, AnotherTrait;
+ use SomeTrait;
+ use AnotherTrait;
}
```
<br>
## SplitListAssignToSeparateLineRector
Splits `[$a, $b] = [5, 10]` scalar assign to standalone lines
- class: `Rector\CodeQuality\Rector\Assign\SplitListAssignToSeparateLineRector`
```diff
final class SomeClass
{
public function run(): void
{
- [$a, $b] = [1, 2];
+ $a = 1;
+ $b = 2;
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## SplitStringClassConstantToClassConstFetchRector
Separate class constant in a string to class constant fetch and string
- class: `Rector\CodingStyle\Rector\String_\SplitStringClassConstantToClassConstFetchRector`
```diff
class SomeClass
2018-10-23 18:58:57 +00:00
{
const HI = true;
}
2018-05-04 22:30:32 +00:00
class AnotherClass
{
public function get()
{
- return 'SomeClass::HI';
+ return SomeClass::class . '::HI';
}
2018-10-21 22:26:45 +00:00
}
2018-10-12 23:15:00 +00:00
```
<br>
## StartsWithFunctionToNetteUtilsStringsRector
Use `Nette\Utils\Strings::startsWith()` over bare string-functions
- class: `Rector\Nette\Rector\Identical\StartsWithFunctionToNetteUtilsStringsRector`
2020-07-24 11:46:57 +00:00
```diff
class SomeClass
{
public function start($needle)
{
$content = 'Hi, my name is Tom';
- $yes = substr($content, 0, strlen($needle)) === $needle;
+ $yes = \Nette\Utils\Strings::startsWith($content, $needle);
}
}
```
<br>
## StaticCallOnNonStaticToInstanceCallRector
Changes static call to instance call, where not useful
- class: `Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector`
```diff
class Something
{
public function doWork()
{
}
}
class Another
{
public function run()
{
- return Something::doWork();
+ return (new Something)->doWork();
}
}
```
<br>
## StaticCallToFuncCallRector
2018-07-31 12:50:39 +00:00
Turns static call to function call.
2018-08-01 20:09:34 +00:00
:wrench: **configure it!**
2020-07-24 11:46:57 +00:00
- class: `Rector\Transform\Rector\StaticCall\StaticCallToFuncCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\StaticCall\StaticCallToFuncCallRector;
use Rector\Transform\ValueObject\StaticCallToFuncCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2020-07-24 11:46:57 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
2020-07-29 08:33:10 +00:00
$services = $containerConfigurator->services();
$services->set(StaticCallToFuncCallRector::class)
->call('configure', [[
StaticCallToFuncCallRector::STATIC_CALLS_TO_FUNCTIONS => inline_value_objects([
new StaticCallToFuncCall('OldClass', 'oldMethod', 'new_function'),
]),
]]);
2020-07-24 11:46:57 +00:00
};
2018-08-01 20:09:34 +00:00
```
2018-07-31 12:50:39 +00:00
```diff
-OldClass::oldMethod("args");
+new_function("args");
2018-07-31 12:50:39 +00:00
```
<br>
## StaticCallToMethodCallRector
2018-07-31 12:50:39 +00:00
Change static call to service method via constructor injection
:wrench: **configure it!**
2020-07-24 11:46:57 +00:00
- class: `Rector\Transform\Rector\StaticCall\StaticCallToMethodCallRector`
2018-08-01 20:09:34 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Transform\Rector\StaticCall\StaticCallToMethodCallRector;
use Rector\Transform\ValueObject\StaticCallToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2018-07-31 12:50:39 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StaticCallToMethodCallRector::class)
->call('configure', [[
StaticCallToMethodCallRector::STATIC_CALLS_TO_METHOD_CALLS => inline_value_objects([
new StaticCallToMethodCall(
'Nette\Utils\FileSystem',
'write',
'Symplify\SmartFileSystem\SmartFileSystem',
'dumpFile'
),
]),
]]);
};
```
```diff
-use Nette\Utils\FileSystem;
+use Symplify\SmartFileSystem\SmartFileSystem;
class SomeClass
{
+ /**
+ * @var SmartFileSystem
+ */
+ private $smartFileSystem;
+
+ public function __construct(SmartFileSystem $smartFileSystem)
+ {
+ $this->smartFileSystem = $smartFileSystem;
+ }
+
public function run()
{
- return FileSystem::write('file', 'content');
+ return $this->smartFileSystem->dumpFile('file', 'content');
}
}
2018-08-01 20:09:34 +00:00
```
<br>
## StaticTypeToSetterInjectionRector
Changes types to setter injection
:wrench: **configure it!**
- class: `Rector\RemovingStatic\Rector\Class_\StaticTypeToSetterInjectionRector`
```php
use Rector\RemovingStatic\Rector\Class_\StaticTypeToSetterInjectionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StaticTypeToSetterInjectionRector::class)
->call('configure', [[
StaticTypeToSetterInjectionRector::STATIC_TYPES => ['SomeStaticClass'],
]]);
};
```
2018-08-01 20:09:34 +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();
}
}
2018-08-01 20:09:34 +00:00
```
<br>
## StrContainsRector
2018-09-28 16:33:35 +00:00
Replace `strpos()` !== false and `strstr()` with `str_contains()`
2018-09-28 16:33:35 +00:00
- class: `Rector\Php80\Rector\NotIdentical\StrContainsRector`
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
public function run()
{
- return strpos('abc', 'a') !== false;
+ return str_contains('abc', 'a');
}
2018-08-01 20:09:34 +00:00
}
2018-05-04 22:30:32 +00:00
```
<br>
2018-10-23 18:58:57 +00:00
## StrEndsWithRector
2019-02-18 15:51:24 +00:00
Change helper functions to `str_ends_with()`
2019-02-18 15:51:24 +00:00
- class: `Rector\Php80\Rector\Identical\StrEndsWithRector`
2020-07-24 11:46:57 +00:00
```diff
class SomeClass
{
public function run()
{
- $isMatch = substr($haystack, -strlen($needle)) === $needle;
+ $isMatch = str_ends_with($haystack, $needle);
}
}
2019-02-18 15:51:24 +00:00
```
<br>
## StrStartsWithRector
Change helper functions to `str_starts_with()`
- class: `Rector\Php80\Rector\Identical\StrStartsWithRector`
```diff
class SomeClass
{
public function run()
{
- $isMatch = substr($haystack, 0, strlen($needle)) === $needle;
+ $isMatch = str_starts_with($haystack, $needle);
- $isNotMatch = substr($haystack, 0, strlen($needle)) !== $needle;
+ $isNotMatch = ! str_starts_with($haystack, $needle);
}
}
2019-02-18 15:51:24 +00:00
```
<br>
2019-02-18 15:51:24 +00:00
## StrictArraySearchRector
2020-07-24 11:46:57 +00:00
Makes `array_search` search for identical elements
2018-05-04 22:30:32 +00:00
- class: `Rector\CodingStyle\Rector\FuncCall\StrictArraySearchRector`
```diff
-array_search($value, $items);
+array_search($value, $items, true);
```
<br>
## StringClassNameToClassConstantRector
Replace string class names by <class>::class constant
:wrench: **configure it!**
- class: `Rector\Php55\Rector\String_\StringClassNameToClassConstantRector`
```php
use Rector\Php55\Rector\String_\StringClassNameToClassConstantRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StringClassNameToClassConstantRector::class)
->call('configure', [[
StringClassNameToClassConstantRector::CLASSES_TO_SKIP => ['ClassName', 'AnotherClassName'],
]]);
};
```
2018-07-31 12:50:39 +00:00
2018-08-01 20:09:34 +00:00
```diff
class AnotherClass
{
}
class SomeClass
{
public function run()
{
- return 'AnotherClass';
+ return \AnotherClass::class;
}
}
2018-05-04 22:30:32 +00:00
```
<br>
## StringFormTypeToClassRector
2020-07-24 11:46:57 +00:00
Turns string Form Type references to their `CONSTANT` alternatives in FormTypes in Form in Symfony. To enable custom types, add `link` to your container XML `dump` in "$parameters->set(Option::SYMFONY_CONTAINER_XML_PATH_PARAMETER, ...);"
2018-05-05 00:04:41 +00:00
- class: `Rector\Symfony\Rector\MethodCall\StringFormTypeToClassRector`
2018-08-01 20:09:34 +00:00
```diff
$formBuilder = new Symfony\Component\Form\FormBuilder;
-$formBuilder->add('name', 'form.type.text');
+$formBuilder->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class);
2018-05-05 00:04:41 +00:00
```
<br>
## StringToArrayArgumentProcessRector
2020-07-24 11:46:57 +00:00
Changes Process string argument to an array
- class: `Rector\Symfony\Rector\New_\StringToArrayArgumentProcessRector`
```diff
use Symfony\Component\Process\Process;
-$process = new Process('ls -l');
+$process = new Process(['ls', '-l']);
```
<br>
2019-05-29 13:40:20 +00:00
## StringToClassConstantRector
2020-07-24 11:46:57 +00:00
Changes strings to specific constants
2019-11-06 23:52:19 +00:00
:wrench: **configure it!**
- class: `Rector\Generic\Rector\String_\StringToClassConstantRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\String_\StringToClassConstantRector;
use Rector\Generic\ValueObject\StringToClassConstant;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(StringToClassConstantRector::class)
->call('configure', [[
StringToClassConstantRector::STRINGS_TO_CLASS_CONSTANTS => inline_value_objects([
new StringToClassConstant('compiler.post_dump', 'Yet\AnotherClass', 'CONSTANT'),
]),
]]);
};
```
2019-11-06 23:52:19 +00:00
```diff
final class SomeSubscriber
2019-11-06 23:52:19 +00:00
{
public static function getSubscribedEvents()
2019-11-06 23:52:19 +00:00
{
- return ['compiler.post_dump' => 'compile'];
+ return [\Yet\AnotherClass::CONSTANT => 'compile'];
2019-11-06 23:52:19 +00:00
}
}
```
<br>
2019-11-06 23:52:19 +00:00
## StringableForToStringRector
2020-07-28 15:15:30 +00:00
Add `Stringable` interface to classes with `__toString()` method
2020-07-28 15:15:30 +00:00
- class: `Rector\Php80\Rector\Class_\StringableForToStringRector`
2020-07-28 15:15:30 +00:00
```diff
-class SomeClass
+class SomeClass implements Stringable
{
- public function __toString()
+ public function __toString(): string
2020-07-28 15:15:30 +00:00
{
return 'I can stringz';
2020-07-28 15:15:30 +00:00
}
}
```
<br>
2020-07-28 15:15:30 +00:00
## StringifyDefineRector
2020-07-24 11:46:57 +00:00
Make first argument of `define()` string
- class: `Rector\Php72\Rector\FuncCall\StringifyDefineRector`
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
public function run(int $a)
{
- define(CONSTANT_2, 'value');
+ define('CONSTANT_2', 'value');
define('CONSTANT', 'value');
}
2019-05-29 13:40:20 +00:00
}
```
<br>
## StringifyStrNeedlesRector
2020-07-24 11:46:57 +00:00
Makes needles explicit strings
- class: `Rector\Php73\Rector\FuncCall\StringifyStrNeedlesRector`
```diff
$needle = 5;
-$fivePosition = strpos('725', $needle);
+$fivePosition = strpos('725', (string) $needle);
```
<br>
## StringsAssertNakedRector
String asserts must be passed directly to `assert()`
- class: `Rector\Php72\Rector\FuncCall\StringsAssertNakedRector`
```diff
function nakedAssert()
2019-05-29 13:40:20 +00:00
{
- assert('true === true');
- assert("true === true");
+ assert(true === true);
+ assert(true === true);
2019-05-29 13:40:20 +00:00
}
```
<br>
## StrlenZeroToIdenticalEmptyStringRector
2018-05-04 22:30:32 +00:00
Changes `strlen` comparison to 0 to direct empty string compare
2018-05-04 22:30:32 +00:00
- class: `Rector\CodeQuality\Rector\Identical\StrlenZeroToIdenticalEmptyStringRector`
2018-07-31 12:50:39 +00:00
```diff
class SomeClass
{
public function run($value)
{
- $empty = strlen($value) === 0;
+ $empty = $value === '';
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## StrposToStringsContainsRector
2018-05-04 22:30:32 +00:00
Use `Nette\Utils\Strings` over bare string-functions
- class: `Rector\Nette\Rector\NotIdentical\StrposToStringsContainsRector`
2018-08-01 20:09:34 +00:00
```diff
class SomeClass
{
public function run()
{
$name = 'Hi, my name is Tom';
- return strpos($name, 'Hi') !== false;
+ return \Nette\Utils\Strings::contains($name, 'Hi');
}
}
```
<br>
2019-05-29 13:40:20 +00:00
## SubstrStrlenFunctionToNetteUtilsStringsRector
2019-05-29 13:40:20 +00:00
Use `Nette\Utils\Strings` over bare string-functions
2019-05-29 13:40:20 +00:00
- class: `Rector\Nette\Rector\FuncCall\SubstrStrlenFunctionToNetteUtilsStringsRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
public function run()
{
- return substr($value, 0, 3);
+ return \Nette\Utils\Strings::substring($value, 0, 3);
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## SwapClassMethodArgumentsRector
Reorder class method arguments, including their calls
:wrench: **configure it!**
- class: `Rector\Generic\Rector\StaticCall\SwapClassMethodArgumentsRector`
2018-09-28 16:33:35 +00:00
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\StaticCall\SwapClassMethodArgumentsRector;
use Rector\Generic\ValueObject\SwapClassMethodArguments;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SwapClassMethodArgumentsRector::class)
->call('configure', [[
SwapClassMethodArgumentsRector::ARGUMENT_SWAPS => inline_value_objects([
new SwapClassMethodArguments('SomeClass', 'run', [1, 0]), ]
),
]]);
};
```
2018-09-28 16:33:35 +00:00
```diff
class SomeClass
2019-05-29 13:40:20 +00:00
{
- public static function run($first, $second)
+ public static function run($second, $first)
{
- self::run($first, $second);
+ self::run($second, $first);
}
2019-05-29 13:40:20 +00:00
}
2018-09-28 16:33:35 +00:00
```
<br>
## SwapFuncCallArgumentsRector
Swap arguments in function calls
:wrench: **configure it!**
- class: `Rector\Generic\Rector\FuncCall\SwapFuncCallArgumentsRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\FuncCall\SwapFuncCallArgumentsRector;
use Rector\Generic\ValueObject\SwapFuncCallArguments;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(SwapFuncCallArgumentsRector::class)
->call('configure', [[
SwapFuncCallArgumentsRector::FUNCTION_ARGUMENT_SWAPS => inline_value_objects([
new SwapFuncCallArguments('some_function', [1, 0]), ]
),
]]);
};
```
```diff
final class SomeClass
{
public function run($one, $two)
{
- return some_function($one, $two);
+ return some_function($two, $one);
}
}
```
2020-07-24 11:46:57 +00:00
<br>
2020-07-24 11:46:57 +00:00
## SymplifyQuoteEscapeRector
Prefer quote that are not inside the string
- class: `Rector\CodingStyle\Rector\String_\SymplifyQuoteEscapeRector`
```diff
class SomeClass
{
public function run()
{
- $name = "\" Tom";
- $name = '\' Sara';
+ $name = '" Tom';
+ $name = "' Sara";
}
}
```
<br>
## TemplateAnnotationToThisRenderRector
Turns `@Template` annotation to explicit method call in Controller of FrameworkExtraBundle in Symfony
- class: `Rector\Sensio\Rector\ClassMethod\TemplateAnnotationToThisRenderRector`
```diff
-/**
- * @Template()
- */
public function indexAction()
{
+ return $this->render('index.html.twig');
}
```
<br>
## TemplateMagicAssignToExplicitVariableArrayRector
Change `$this->templates->{magic}` to `$this->template->render(..., $values)`
- class: `Rector\Nette\Rector\ClassMethod\TemplateMagicAssignToExplicitVariableArrayRector`
2020-07-24 11:46:57 +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']);
}
}
```
<br>
## TernaryConditionVariableAssignmentRector
Assign outcome of ternary condition to variable, where applicable
- class: `Rector\CodingStyle\Rector\Ternary\TernaryConditionVariableAssignmentRector`
2019-05-29 13:40:20 +00:00
```diff
function ternary($value)
{
- $value ? $a = 1 : $a = 0;
+ $a = $value ? 1 : 0;
}
```
<br>
2020-07-24 11:46:57 +00:00
## TernaryToBooleanOrFalseToBooleanAndRector
2020-07-24 11:46:57 +00:00
Change ternary of bool : false to && bool
- class: `Rector\DeadCode\Rector\Ternary\TernaryToBooleanOrFalseToBooleanAndRector`
```diff
class SomeClass
{
public function go()
{
- return $value ? $this->getBool() : false;
+ return $value && $this->getBool();
}
private function getBool(): bool
{
return (bool) 5;
}
}
```
<br>
## TernaryToElvisRector
2020-07-24 11:46:57 +00:00
Use ?: instead of ?, where useful
- class: `Rector\Php53\Rector\Ternary\TernaryToElvisRector`
```diff
function elvis()
{
- $value = $a ? $a : false;
+ $value = $a ?: false;
}
2019-05-29 13:40:20 +00:00
```
<br>
2019-05-29 13:40:20 +00:00
## TernaryToNullCoalescingRector
2020-07-24 11:46:57 +00:00
Changes unneeded null check to ?? operator
2020-05-31 15:26:08 +00:00
- class: `Rector\Php70\Rector\Ternary\TernaryToNullCoalescingRector`
2020-05-31 15:26:08 +00:00
```diff
-$value === null ? 10 : $value;
+$value ?? 10;
2020-05-31 15:26:08 +00:00
```
<br>
2020-05-31 15:26:08 +00:00
```diff
-isset($value) ? $value : 10;
+$value ?? 10;
2020-05-31 15:26:08 +00:00
```
<br>
2020-07-24 11:46:57 +00:00
## TernaryToSpaceshipRector
2020-07-24 11:46:57 +00:00
Use <=> spaceship instead of ternary with same effect
- class: `Rector\Php70\Rector\Ternary\TernaryToSpaceshipRector`
```diff
function order_func($a, $b) {
- return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
+ return $a <=> $b;
}
```
<br>
## TestListenerToHooksRector
Refactor "*TestListener.php" to particular "*Hook.php" files
- class: `Rector\PHPUnit\Rector\Class_\TestListenerToHooksRector`
```diff
namespace App\Tests;
-use PHPUnit\Framework\TestListener;
-
-final class BeforeListHook implements TestListener
+final class BeforeListHook implements \PHPUnit\Runner\BeforeTestHook, \PHPUnit\Runner\AfterTestHook
{
- public function addError(Test $test, \Throwable $t, float $time): void
+ public function executeBeforeTest(Test $test): void
{
- }
-
- public function addWarning(Test $test, Warning $e, float $time): void
- {
- }
-
- public function addFailure(Test $test, AssertionFailedError $e, float $time): void
- {
- }
-
- public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
- {
- }
-
- public function addRiskyTest(Test $test, \Throwable $t, float $time): void
- {
- }
-
- public function addSkippedTest(Test $test, \Throwable $t, float $time): void
- {
- }
-
- public function startTestSuite(TestSuite $suite): void
- {
- }
-
- public function endTestSuite(TestSuite $suite): void
- {
- }
-
- public function startTest(Test $test): void
- {
echo 'start test!';
}
- public function endTest(Test $test, float $time): void
+ public function executeAfterTest(Test $test, float $time): void
{
echo $time;
}
}
```
<br>
## ThisCallOnStaticMethodToStaticCallRector
2020-07-24 11:46:57 +00:00
Changes `$this->call()` to static method to static call
- class: `Rector\Php70\Rector\MethodCall\ThisCallOnStaticMethodToStaticCallRector`
```diff
class SomeClass
{
public static function run()
{
- $this->eat();
+ static::eat();
}
public static function eat()
{
}
}
```
<br>
## ThrowWithPreviousExceptionRector
2020-07-29 23:39:41 +00:00
When throwing into a catch block, checks that the previous exception is passed to the new throw clause
2020-07-29 23:39:41 +00:00
- class: `Rector\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector`
2020-07-29 23:39:41 +00:00
```diff
class SomeClass
{
public function run()
{
try {
$someCode = 1;
} catch (Throwable $throwable) {
- throw new AnotherException('ups');
+ throw new AnotherException('ups', $throwable->getCode(), $throwable);
}
}
}
```
<br>
2020-07-29 23:39:41 +00:00
## TimestampableBehaviorRector
Change Timestampable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
2020-07-29 23:39:41 +00:00
- class: `Rector\DoctrineGedmoToKnplabs\Rector\Class_\TimestampableBehaviorRector`
2020-07-29 23:39:41 +00:00
```diff
-use Gedmo\Timestampable\Traits\TimestampableEntity;
+use Knp\DoctrineBehaviors\Model\Timestampable\TimestampableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\TimestampableInterface;
2020-07-29 23:39:41 +00:00
-class SomeClass
+class SomeClass implements TimestampableInterface
{
- use TimestampableEntity;
+ use TimestampableTrait;
2020-07-29 23:39:41 +00:00
}
```
<br>
## ToStringToMethodCallRector
Turns defined code uses of `"__toString()"` method to specific method calls.
:wrench: **configure it!**
- class: `Rector\MagicDisclosure\Rector\String_\ToStringToMethodCallRector`
```php
use Rector\MagicDisclosure\Rector\String_\ToStringToMethodCallRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ToStringToMethodCallRector::class)
->call('configure', [[
ToStringToMethodCallRector::METHOD_NAMES_BY_TYPE => [
'SomeObject' => 'getPath',
],
]]);
};
```
```diff
$someValue = new SomeObject;
-$result = (string) $someValue;
-$result = $someValue->__toString();
+$result = $someValue->getPath();
+$result = $someValue->getPath();
```
<br>
## TokenGetAllToObjectRector
Complete missing constructor dependency instance by type
- class: `Rector\Php80\Rector\FuncCall\TokenGetAllToObjectRector`
```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;
}
}
}
```
<br>
## TranslateClassMethodToVariadicsRector
Change `translate()` method call 2nd arg to variadic
- class: `Rector\Nette\Rector\ClassMethod\TranslateClassMethodToVariadicsRector`
```diff
use Nette\Localization\ITranslator;
final class SomeClass implements ITranslator
{
- public function translate($message, $count = null)
+ public function translate($message, ... $parameters)
{
+ $count = $parameters[0] ?? null;
return [$message, $count];
}
}
```
<br>
## TranslationBehaviorRector
Change Translation from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
- class: `Rector\DoctrineGedmoToKnplabs\Rector\Class_\TranslationBehaviorRector`
```diff
-use Gedmo\Mapping\Annotation as Gedmo;
-use Doctrine\ORM\Mapping as ORM;
-use Gedmo\Translatable\Translatable;
+use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
-/**
- * @ORM\Table
- */
-class Article implements Translatable
+class SomeClass implements TranslatableInterface
{
+ use TranslatableTrait;
+}
+
+
+use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
+use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;
+
+class SomeClassTranslation implements TranslationInterface
+{
+ use TranslationTrait;
+
/**
- * @Gedmo\Translatable
* @ORM\Column(length=128)
*/
private $title;
/**
- * @Gedmo\Translatable
* @ORM\Column(type="text")
*/
private $content;
-
- /**
- * @Gedmo\Locale
- * Used locale to override Translation listener`s locale
- * this is not a mapped field of entity metadata, just a simple property
- * and it is not necessary because globally locale can be set in listener
- */
- private $locale;
-
- public function setTitle($title)
- {
- $this->title = $title;
- }
-
- public function getTitle()
- {
- return $this->title;
- }
-
- public function setContent($content)
- {
- $this->content = $content;
- }
-
- public function getContent()
- {
- return $this->content;
- }
-
- public function setTranslatableLocale($locale)
- {
- $this->locale = $locale;
- }
}
```
<br>
## TreeBehaviorRector
Change Tree from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
- class: `Rector\DoctrineGedmoToKnplabs\Rector\Class_\TreeBehaviorRector`
```diff
-use Doctrine\Common\Collections\Collection;
-use Gedmo\Mapping\Annotation as Gedmo;
+use Knp\DoctrineBehaviors\Contract\Entity\TreeNodeInterface;
+use Knp\DoctrineBehaviors\Model\Tree\TreeNodeTrait;
-/**
- * @Gedmo\Tree(type="nested")
- */
-class SomeClass
+class SomeClass implements TreeNodeInterface
{
- /**
- * @Gedmo\TreeLeft
- * @ORM\Column(name="lft", type="integer")
- * @var int
- */
- private $lft;
-
- /**
- * @Gedmo\TreeRight
- * @ORM\Column(name="rgt", type="integer")
- * @var int
- */
- private $rgt;
-
- /**
- * @Gedmo\TreeLevel
- * @ORM\Column(name="lvl", type="integer")
- * @var int
- */
- private $lvl;
-
- /**
- * @Gedmo\TreeRoot
- * @ORM\ManyToOne(targetEntity="Category")
- * @ORM\JoinColumn(name="tree_root", referencedColumnName="id", onDelete="CASCADE")
- * @var Category
- */
- private $root;
-
- /**
- * @Gedmo\TreeParent
- * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
- * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
- * @var Category
- */
- private $parent;
-
- /**
- * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
- * @var Category[]|Collection
- */
- private $children;
-
- public function getRoot(): self
- {
- return $this->root;
- }
-
- public function setParent(self $category): void
- {
- $this->parent = $category;
- }
-
- public function getParent(): self
- {
- return $this->parent;
- }
+ use TreeNodeTrait;
}
```
<br>
## TryCatchToExpectExceptionRector
Turns try/catch to `expectException()` call
- class: `Rector\PHPUnit\Rector\ClassMethod\TryCatchToExpectExceptionRector`
```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();
```
<br>
## TypedPropertyRector
Changes property `@var` annotations from annotation to type.
:wrench: **configure it!**
- class: `Rector\Php74\Rector\Property\TypedPropertyRector`
```php
use Rector\Php74\Rector\Property\TypedPropertyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(TypedPropertyRector::class)
->call('configure', [[
TypedPropertyRector::CLASS_LIKE_TYPE_ONLY => false,
]]);
};
```
```diff
final class SomeClass
{
- /**
- * @var int
- */
- private count;
+ private int count;
}
```
<br>
## UnderscoreToCamelCaseLocalVariableNameRector
Change under_score local variable names to camelCase
- class: `Rector\Naming\Rector\Variable\UnderscoreToCamelCaseLocalVariableNameRector`
```diff
final class SomeClass
{
public function run($a_b)
{
- $some_value = $a_b;
+ $someValue = $a_b;
}
}
```
<br>
## UnderscoreToCamelCasePropertyNameRector
Change under_score names to camelCase
- class: `Rector\Naming\Rector\Property\UnderscoreToCamelCasePropertyNameRector`
```diff
final class SomeClass
{
- public $property_name;
+ public $propertyName;
public function run($a)
{
- $this->property_name = 5;
+ $this->propertyName = 5;
}
}
```
<br>
## UnderscoreToCamelCaseVariableNameRector
Change under_score names to camelCase
- class: `Rector\Naming\Rector\Variable\UnderscoreToCamelCaseVariableNameRector`
```diff
final class SomeClass
{
- public function run($a_b)
+ public function run($aB)
{
- $some_value = $a_b;
+ $someValue = $aB;
}
}
```
<br>
## UnionTypesRector
Change docs types to union types, where possible (properties are covered by TypedPropertiesRector)
- class: `Rector\Php80\Rector\FunctionLike\UnionTypesRector`
```diff
class SomeClass
{
/**
* @param array|int $number
* @return bool|float
*/
- public function go($number)
+ public function go(array|int $number): bool|float
{
}
}
```
<br>
## UnnecessaryTernaryExpressionRector
Remove unnecessary ternary expressions.
- class: `Rector\CodeQuality\Rector\Ternary\UnnecessaryTernaryExpressionRector`
```diff
-$foo === $bar ? true : false;
+$foo === $bar;
```
<br>
## UnsetAndIssetToMethodCallRector
Turns defined `__isset`/`__unset` calls to specific method calls.
:wrench: **configure it!**
- class: `Rector\MagicDisclosure\Rector\Isset_\UnsetAndIssetToMethodCallRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\MagicDisclosure\Rector\Isset_\UnsetAndIssetToMethodCallRector;
use Rector\MagicDisclosure\ValueObject\IssetUnsetToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(UnsetAndIssetToMethodCallRector::class)
->call('configure', [[
UnsetAndIssetToMethodCallRector::ISSET_UNSET_TO_METHOD_CALL => inline_value_objects([
new IssetUnsetToMethodCall('SomeContainer', 'hasService', 'removeService'),
]),
]]);
};
```
```diff
$container = new SomeContainer;
-isset($container["someKey"]);
+$container->hasService("someKey");
```
<br>
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\MagicDisclosure\Rector\Isset_\UnsetAndIssetToMethodCallRector;
use Rector\MagicDisclosure\ValueObject\IssetUnsetToMethodCall;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(UnsetAndIssetToMethodCallRector::class)
->call('configure', [[
UnsetAndIssetToMethodCallRector::ISSET_UNSET_TO_METHOD_CALL => inline_value_objects([
new IssetUnsetToMethodCall('SomeContainer', 'hasService', 'removeService'),
]),
]]);
};
```
```diff
$container = new SomeContainer;
-unset($container["someKey"]);
+$container->removeService("someKey");
```
<br>
## UnsetCastRector
Removes (unset) cast
- class: `Rector\Php72\Rector\Unset_\UnsetCastRector`
```diff
-$different = (unset) $value;
+$different = null;
-$value = (unset) $value;
+unset($value);
```
<br>
## UnusedForeachValueToArrayKeysRector
Change foreach with unused `$value` but only `$key,` to `array_keys()`
- class: `Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector`
```diff
class SomeClass
{
public function run()
{
$items = [];
- foreach ($values as $key => $value) {
+ foreach (array_keys($values) as $key) {
$items[$key] = null;
}
}
}
```
<br>
## UnwrapFutureCompatibleIfFunctionExistsRector
Remove functions exists if with else for always existing
- class: `Rector\Polyfill\Rector\If_\UnwrapFutureCompatibleIfFunctionExistsRector`
```diff
class SomeClass
{
public function run()
{
// session locking trough other addons
- if (function_exists('session_abort')) {
- session_abort();
- } else {
- session_write_close();
- }
+ session_abort();
}
}
```
<br>
## UnwrapFutureCompatibleIfPhpVersionRector
Remove php version checks if they are passed
- class: `Rector\Polyfill\Rector\If_\UnwrapFutureCompatibleIfPhpVersionRector`
```diff
// current PHP: 7.2
-if (version_compare(PHP_VERSION, '7.2', '<')) {
- return 'is PHP 7.1-';
-} else {
- return 'is PHP 7.2+';
-}
+return 'is PHP 7.2+';
```
<br>
## UpdateFileNameByClassNameFileSystemRector
Rename file to respect class name
- class: `Rector\Restoration\Rector\ClassLike\UpdateFileNameByClassNameFileSystemRector`
```diff
-// app/SomeClass.php
+// app/AnotherClass.php
class AnotherClass
{
}
```
<br>
## UseAddingPostRector
Post Rector that adds use statements
- class: `Rector\PostRector\Rector\UseAddingPostRector`
```diff
+use App\SomeClass;
+
$someClass = new SomeClass();
```
<br>
## UseClassKeywordForClassNameResolutionRector
Use `class` keyword for class name resolution in string instead of hardcoded string reference
- class: `Rector\CodingStyle\Rector\String_\UseClassKeywordForClassNameResolutionRector`
```diff
-$value = 'App\SomeClass::someMethod()';
+$value = \App\SomeClass . '::someMethod()';
```
<br>
## UseIdenticalOverEqualWithSameTypeRector
Use ===/!== over ==/!=, it values have the same type
- class: `Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector`
```diff
class SomeClass
{
public function run(int $firstValue, int $secondValue)
{
- $isSame = $firstValue == $secondValue;
- $isDiffernt = $firstValue != $secondValue;
+ $isSame = $firstValue === $secondValue;
+ $isDiffernt = $firstValue !== $secondValue;
}
}
```
<br>
## UseIncrementAssignRector
Use ++ increment instead of `$var += 1`
- class: `Rector\CodingStyle\Rector\Plus\UseIncrementAssignRector`
```diff
class SomeClass
{
public function run()
{
- $style += 1;
+ ++$style
}
}
```
<br>
## UseInterfaceOverImplementationInConstructorRector
2019-05-29 13:40:20 +00:00
Use interface instead of specific class
- class: `Rector\SOLID\Rector\ClassMethod\UseInterfaceOverImplementationInConstructorRector`
2020-07-24 11:46:57 +00:00
```diff
class SomeClass
{
- public function __construct(SomeImplementation $someImplementation)
+ public function __construct(SomeInterface $someImplementation)
{
}
}
2020-07-24 11:46:57 +00:00
class SomeImplementation implements SomeInterface
{
}
interface SomeInterface
{
}
```
<br>
## UseMessageVariableForSprintfInSymfonyStyleRector
Decouple `$message` property from `sprintf()` calls in `$this->smyfonyStyle->method()`
- class: `Rector\CodingStyle\Rector\MethodCall\UseMessageVariableForSprintfInSymfonyStyleRector`
```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>
## UseSpecificWillMethodRector
Changes `->will($this->xxx())` to one specific method
- class: `Rector\PHPUnit\Rector\MethodCall\UseSpecificWillMethodRector`
```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 }}!');
}
}
```
<br>
## VarConstantCommentRector
`Constant` should have a `@var` comment with type
- class: `Rector\CodingStyle\Rector\ClassConst\VarConstantCommentRector`
2019-05-29 13:40:20 +00:00
```diff
class SomeClass
{
+ /**
+ * @var string
+ */
const HI = 'hi';
}
2018-07-31 12:50:39 +00:00
```
<br>
## VarDumperTestTraitMethodArgsRector
Adds a new `$filter` argument in `VarDumperTestTrait->assertDumpEquals()` and `VarDumperTestTrait->assertDumpMatchesFormat()` in Validator in Symfony.
2018-05-04 22:30:32 +00:00
- class: `Rector\Symfony\Rector\MethodCall\VarDumperTestTraitMethodArgsRector`
2018-08-01 20:09:34 +00:00
```diff
-$varDumperTestTrait->assertDumpEquals($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpEquals($dump, $data, $filter = 0, $message = "");
```
2018-05-04 22:30:32 +00:00
<br>
```diff
-$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $filter = 0, $message = "");
2018-08-01 20:09:34 +00:00
```
<br>
## VarInlineAnnotationToAssertRector
Turn `@var` inline checks above code to `assert()` of the type
2019-08-05 21:10:47 +00:00
- class: `Rector\StrictCodeQuality\Rector\Stmt\VarInlineAnnotationToAssertRector`
2019-08-05 21:10:47 +00:00
```diff
class SomeClass
{
public function run()
{
/** @var SpecificClass $value */
+ assert($value instanceof SpecificClass);
$value->call();
}
}
```
2019-08-05 21:10:47 +00:00
<br>
2020-07-24 11:46:57 +00:00
## VarToPublicPropertyRector
2020-07-24 11:46:57 +00:00
Remove unused private method
2019-08-05 21:10:47 +00:00
- class: `Rector\Php52\Rector\Property\VarToPublicPropertyRector`
2019-08-05 21:10:47 +00:00
```diff
final class SomeController
2019-08-05 21:10:47 +00:00
{
- var $name = 'Tom';
+ public $name = 'Tom';
}
```
2019-08-05 21:10:47 +00:00
<br>
## VersionCompareFuncCallToConstantRector
Changes use of call to version compare function to use of PHP version constant
- class: `Rector\CodingStyle\Rector\FuncCall\VersionCompareFuncCallToConstantRector`
```diff
class SomeClass
{
public function run()
2019-08-05 21:10:47 +00:00
{
- version_compare(PHP_VERSION, '5.3.0', '<');
+ PHP_VERSION_ID < 50300;
2019-08-05 21:10:47 +00:00
}
}
```
<br>
2019-08-05 21:10:47 +00:00
## WhileEachToForeachRector
2018-05-04 22:30:32 +00:00
`each()` function is deprecated, use `foreach()` instead.
- class: `Rector\Php72\Rector\While_\WhileEachToForeachRector`
2018-05-04 22:30:32 +00:00
```diff
-while (list($key, $callback) = each($callbacks)) {
+foreach ($callbacks as $key => $callback) {
// ...
}
```
2020-07-24 11:46:57 +00:00
<br>
```diff
-while (list($key) = each($callbacks)) {
+foreach (array_keys($callbacks) as $key) {
// ...
}
```
2020-07-24 11:46:57 +00:00
<br>
## WithConsecutiveArgToArrayRector
2018-08-01 20:09:34 +00:00
Split `withConsecutive()` arg to array
- class: `Rector\PHPUnit\Rector\MethodCall\WithConsecutiveArgToArrayRector`
2018-08-01 20:09:34 +00:00
2018-05-04 22:30:32 +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]);
}
}
2018-07-31 06:38:48 +00:00
```
<br>
## WrapEncapsedVariableInCurlyBracesRector
Wrap encapsed variables in curly braces
- class: `Rector\CodingStyle\Rector\Encapsed\WrapEncapsedVariableInCurlyBracesRector`
```diff
function run($world)
{
- echo "Hello $world!"
+ echo "Hello {$world}!"
}
```
<br>
## WrapReturnRector
Wrap return value of specific method
:wrench: **configure it!**
- class: `Rector\Generic\Rector\ClassMethod\WrapReturnRector`
```php
use Migrify\SymfonyPhpConfig\inline_value_objects;
use Rector\Generic\Rector\ClassMethod\WrapReturnRector;
use Rector\Generic\ValueObject\WrapReturn;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(WrapReturnRector::class)
->call('configure', [[
WrapReturnRector::TYPE_METHOD_WRAPS => inline_value_objects([new WrapReturn('SomeClass', 'getItem', true)]),
]]);
};
```
```diff
final class SomeClass
{
public function getItem()
{
- return 1;
+ return [1];
}
}
```
<br>
## WrapTransParameterNameRector
2020-07-24 11:46:57 +00:00
Adds %% to placeholder name of `trans()` method if missing
2018-08-01 20:09:34 +00:00
- class: `Rector\NetteToSymfony\Rector\MethodCall\WrapTransParameterNameRector`
2018-08-01 20:09:34 +00:00
2018-05-04 22:30:32 +00:00
```diff
use Symfony\Component\Translation\Translator;
final class SomeController
{
public function run()
{
$translator = new Translator('');
$translated = $translator->trans(
'Hello %name%',
- ['name' => $name]
+ ['%name%' => $name]
);
}
}
2018-05-04 22:30:32 +00:00
```
<br>
## WrapVariableVariableNameInCurlyBracesRector
2019-12-18 09:53:46 +00:00
Ensure variable variables are wrapped in curly braces
2020-07-24 11:46:57 +00:00
- class: `Rector\Php70\Rector\Variable\WrapVariableVariableNameInCurlyBracesRector`
2020-07-24 11:46:57 +00:00
```diff
function run($foo)
2019-12-18 09:53:46 +00:00
{
- global $$foo->bar;
+ global ${$foo->bar};
2019-12-18 09:53:46 +00:00
}
```
<br>
2019-12-18 09:53:46 +00:00
## YieldClassMethodToArrayClassMethodRector
2019-09-25 08:49:53 +00:00
Turns yield return to array return in specific type and method
2019-09-25 08:49:53 +00:00
:wrench: **configure it!**
- class: `Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector`
2019-09-25 08:49:53 +00:00
```php
use Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
2019-09-25 08:49:53 +00:00
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
2020-07-24 11:46:57 +00:00
$services->set(YieldClassMethodToArrayClassMethodRector::class)
->call('configure', [[
YieldClassMethodToArrayClassMethodRector::METHODS_BY_TYPE => [
'EventSubscriberInterface' => ['getSubscribedEvents'],
],
]]);
};
```
```diff
class SomeEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- yield 'event' => 'callback';
+ return ['event' => 'callback'];
}
}
```
<br>