291 KiB
All 461 Rectors Overview
Projects
- Architecture
- Autodiscovery
- CakePHP
- CakePHPToSymfony
- Celebrity
- CodeQuality
- CodingStyle
- DeadCode
- Doctrine
- DoctrineCodeQuality
- DoctrineGedmoToKnplabs
- DynamicTypeAnalysis
- ElasticSearchDSL
- FileSystemRector
- Guzzle
- JMS
- Laravel
- Legacy
- MinimalScope
- MysqlToMysqli
- Nette
- NetteTesterToPHPUnit
- NetteToSymfony
- Oxid
- PHPStan
- PHPUnit
- PHPUnitSymfony
- PSR4
- Phalcon
- Php52
- Php53
- Php54
- Php55
- Php56
- Php70
- Php71
- Php72
- Php73
- Php74
- Php80
- PhpDeglobalize
- PhpSpecToPHPUnit
- Polyfill
- Refactoring
- RemovingStatic
- Renaming
- Restoration
- SOLID
- Sensio
- Shopware
- Silverstripe
- StrictCodeQuality
- Sylius
- Symfony
- SymfonyCodeQuality
- SymfonyPHPUnit
- Twig
- TypeDeclaration
- ZendToSymfony
Architecture
ConstructorInjectionToActionInjectionRector
final class SomeController
{
- /**
- * @var ProductRepository
- */
- private $productRepository;
-
- public function __construct(ProductRepository $productRepository)
+ public function default(ProductRepository $productRepository)
{
- $this->productRepository = $productRepository;
- }
-
- public function default()
- {
- $products = $this->productRepository->fetchAll();
+ $products = $productRepository->fetchAll();
}
}
MoveRepositoryFromParentToConstructorRector
Turns parent EntityRepository class to constructor dependency
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);
+ }
}
ReplaceParentRepositoryCallsByRepositoryPropertyRector
Handles method calls in child of Doctrine EntityRepository and moves them to "$this->repository" property.
<?php
use Doctrine\ORM\EntityRepository;
class SomeRepository extends EntityRepository
{
public function someMethod()
{
- return $this->findAll();
+ return $this->repository->findAll();
}
}
ServiceLocatorToDIRector
Turns "$this->getRepository()" in Symfony Controller to constructor injection and private property access.
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(...);
}
}
Autodiscovery
MoveEntitiesToEntityDirectoryRector
Move entities to Entity namespace
-// file: app/Controller/Product.php
+// file: app/Entity/Product.php
-namespace App\Controller;
+namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Product
{
}
MoveInterfacesToContractNamespaceDirectoryRector
Move interface to "Contract" namespace
-// file: app/Exception/Rule.php
+// file: app/Contract/Rule.php
-namespace App\Exception;
+namespace App\Contract;
interface Rule
{
}
MoveServicesBySuffixToDirectoryRector
Move classes by their suffix to their own group/directory
services:
Rector\Autodiscovery\Rector\FileSystem\MoveServicesBySuffixToDirectoryRector:
$groupNamesBySuffix:
- Repository
↓
-// file: app/Entity/ProductRepository.php
+// file: app/Repository/ProductRepository.php
-namespace App/Entity;
+namespace App/Repository;
class ProductRepository
{
}
MoveValueObjectsToValueObjectDirectoryRector
Move value object to ValueObject namespace/directory
CakePHP
AppUsesStaticCallToUseStatementRector
Change App::uses() to use imports
-App::uses('NotificationListener', 'Event');
+use Event\NotificationListener;
CakeEventManager::instance()->attach(new NotificationListener());
ChangeSnakedFixtureNameToCamelRector
Changes $fixtues style from snake_case to CamelCase.
class SomeTest
{
protected $fixtures = [
- 'app.posts',
- 'app.users',
- 'some_plugin.posts/special_posts',
+ 'app.Posts',
+ 'app.Users',
+ 'some_plugin.Posts/SpeectialPosts',
];
ImplicitShortClassNameUseStatementRector
Collect implicit class names and add imports
use App\Foo\Plugin;
+use Cake\TestSuite\Fixture\TestFixture;
class LocationsFixture extends TestFixture implements Plugin
{
}
ModalToGetSetRector
Changes combined set/get value()
to specific getValue()
or setValue(x)
.
$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']);
RenameMethodCallBasedOnParameterRector
Changes method calls based on matching the first parameter value.
services:
Rector\CakePHP\Rector\MethodCall\RenameMethodCallBasedOnParameterRector:
$methodNamesByTypes:
getParam:
match_parameter: paging
replace_with: getAttribute
withParam:
match_parameter: paging
replace_with: withAttribute
↓
$object = new ServerRequest();
-$config = $object->getParam('paging');
-$object = $object->withParam('paging', ['a value']);
+$config = $object->getAttribute('paging');
+$object = $object->withAttribute('paging', ['a value']);
CakePHPToSymfony
CakePHPBeforeFilterToRequestEventSubscriberRector
Migrate CakePHP beforeFilter() method from controller to Event Subscriber before request
class SuperadminController extends \AppController
{
- public function beforeFilter()
- {
- // something
- }
}
CakePHPControllerActionToSymfonyControllerActionRector
- class:
Rector\CakePHPToSymfony\Rector\ClassMethod\CakePHPControllerActionToSymfonyControllerActionRector
- test fixtures
Migrate CakePHP 2.4 Controller action to Symfony 5
+use Symfony\Component\HttpFoundation\Response;
+
class HomepageController extends \AppController
{
- public function index()
+ public function index(): Response
{
$value = 5;
}
}
CakePHPControllerComponentToSymfonyRector
- class:
Rector\CakePHPToSymfony\Rector\Class_\CakePHPControllerComponentToSymfonyRector
- test fixtures
Migrate CakePHP 2.4 Controller $components property to Symfony 5
class MessagesController extends \AppController
{
- public $components = ['Overview'];
+ private function __construct(OverviewComponent $overviewComponent)
+ {
+ $this->overviewComponent->filter();
+ }
public function someAction()
{
- $this->Overview->filter();
+ $this->overviewComponent->filter();
}
}
class OverviewComponent extends \Component
{
public function filter()
{
}
}
CakePHPControllerHelperToSymfonyRector
Migrate CakePHP 2.4 Controller $helpers and $components property to Symfony 5
class HomepageController extends AppController
{
- public $helpers = ['Flash'];
-
public function index()
{
- $this->Flash->success(__('Your post has been saved.'));
- $this->Flash->error(__('Unable to add your post.'));
+ $this->addFlash('success', __('Your post has been saved.'));
+ $this->addFlash('error', __('Unable to add your post.'));
}
}
CakePHPControllerRedirectToSymfonyRector
- class:
Rector\CakePHPToSymfony\Rector\ClassMethod\CakePHPControllerRedirectToSymfonyRector
- test fixtures
Migrate CakePHP 2.4 Controller redirect() to Symfony 5
class RedirectController extends \AppController
{
public function index()
{
- $this->redirect('boom');
+ return $this->redirect('boom');
}
}
CakePHPControllerRenderToSymfonyRector
- class:
Rector\CakePHPToSymfony\Rector\ClassMethod\CakePHPControllerRenderToSymfonyRector
- test fixtures
Migrate CakePHP 2.4 Controller render() to Symfony 5
class RedirectController extends \AppController
{
public function index()
{
- $this->render('custom_file');
+ return $this->render('redirect/custom_file.twig');
}
}
CakePHPControllerToSymfonyControllerRector
- class:
Rector\CakePHPToSymfony\Rector\Class_\CakePHPControllerToSymfonyControllerRector
- test fixtures
Migrate CakePHP 2.4 Controller to Symfony 5
-class HomepageController extends AppController
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+
+class HomepageController extends AbstractController
{
- public function index()
+ public function index(): Response
{
}
}
CakePHPImplicitRouteToExplicitRouteAnnotationRector
- class:
Rector\CakePHPToSymfony\Rector\Class_\CakePHPImplicitRouteToExplicitRouteAnnotationRector
- test fixtures
Migrate CakePHP implicit routes to Symfony @route annotations
-class PaymentsController extends AppController
+use Symfony\Component\Routing\Annotation\Route;
+
+class AdminPaymentsController extends AppController
{
+ /**
+ * @Route(path="/payments/index", name="payments_index")
+ */
public function index()
{
}
}
CakePHPModelToDoctrineEntityRector
Migrate CakePHP Model active record to Doctrine\ORM Entity and EntityRepository
-class Activity extends \AppModel
+use Doctrine\Mapping\Annotation as ORM;
+
+/**
+ * @ORM\Entity
+ */
+class Activity
{
- public $belongsTo = [
- 'ActivityType' => [
- 'className' => 'ActivityType',
- 'foreignKey' => 'activity_type_id',
- 'dependent' => false,
- ],
- ];
+ /**
+ * @ORM\ManyToOne(targetEntity="ActivityType")
+ * @ORM\JoinColumn(name="activity_type_id")
+ */
+ private $activityType;
}
CakePHPModelToDoctrineRepositoryRector
Migrate CakePHP Model active record to Doctrine\ORM\Repository with repository/DQL method calls
-class Activity extends \AppModel
+use Doctrine\ORM\EntityManagerInterface;
+
+class Activity
{
+}
+
+class ActivityRepository
+{
+ /**
+ * @var EntityManagerInterface
+ */
+ private $repository;
+
+ public function __construct(EntityManagerInterface $entityManager)
+ {
+ $this->repository = $entityManager->getRepository(Activity::class);
+ }
+
public function getAll()
{
- $result = $this->find('all');
+ $result = $this->repository->findAll();
return $result;
}
public function getOne()
{
- $result = $this->find('first', [
- 'conditions' => [
- 'DocumentVersionsSave.revision_number' => $versionId,
- 'DocumentVersionsSave.document_id' => $documentId,
- ],
- 'order' => [
- 'created DESC',
- ],
- ]);
+ $result = $this->findOneBy([
+ 'revision_number' => $versionId,
+ 'document_id' => $documentId,
+ ], 'created DESC');
return $result;
}
}
CakePHPTemplateHToTwigRector
Migrate CakePHP 2.4 h() function calls to Twig
-<h3><?php echo h($value); ?></h3>
+<h3>{{ value|escape }}</h3>
CakePHPTemplateLinkToTwigRector
Migrate CakePHP 2.4 template method calls to Twig
<li>
- <?php echo $this->Html->link('List Rights', ['action' => 'index']); ?>
+ <a href="{{ path('index') }}">List Rights</a>
</li>
CakePHPTemplateTranslateToTwigRector
Migrate CakePHP 2.4 template method calls with translate to Twig
-<h3><?php echo __("Actions"); ?></h3>
+<h3>{{ "Actions"|trans }}</h3>
Celebrity
CommonNotEqualRector
Use common != instead of less known <> with same meaning
final class SomeClass
{
public function run($one, $two)
{
- return $one <> $two;
+ return $one != $two;
}
}
LogicalToBooleanRector
Change OR, AND to ||, && with more common understanding
-if ($f = false or true) {
+if (($f = false) || true) {
return $f;
}
SetTypeToCastRector
Changes settype() to (type) where possible
class SomeClass
{
- public function run($foo)
+ public function run(array $items)
{
- settype($foo, 'string');
+ $foo = (string) $foo;
- return settype($foo, 'integer');
+ return (int) $foo;
}
}
CodeQuality
AbsolutizeRequireAndIncludePathRector
include/require to absolute path. This Rector might introduce backwards incompatible code, when the include/require beeing changed depends on the current working directory.
class SomeClass
{
public function run()
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
require $variable;
}
}
AddPregQuoteDelimiterRector
Add preg_quote delimiter when missing
-'#' . preg_quote('name') . '#';
+'#' . preg_quote('name', '#') . '#';
AndAssignsToSeparateLinesRector
Split 2 assigns ands to separate line
class SomeClass
{
public function run()
{
$tokens = [];
- $token = 4 and $tokens[] = $token;
+ $token = 4;
+ $tokens[] = $token;
}
}
ArrayKeyExistsTernaryThenValueToCoalescingRector
- class:
Rector\CodeQuality\Rector\Ternary\ArrayKeyExistsTernaryThenValueToCoalescingRector
- test fixtures
Change array_key_exists() ternary to coalesing
class SomeClass
{
public function run($values, $keyToMatch)
{
- $result = array_key_exists($keyToMatch, $values) ? $values[$keyToMatch] : null;
+ $result = $values[$keyToMatch] ?? null;
}
}
ArrayMergeOfNonArraysToSimpleArrayRector
Change array_merge of non arrays to array directly
class SomeClass
{
public function go()
{
$value = 5;
$value2 = 10;
- return array_merge([$value], [$value2]);
+ return [$value, $value2];
}
}
BooleanNotIdenticalToNotIdenticalRector
Negated identical boolean compare to not identical compare (does not apply to non-bool values)
class SomeClass
{
public function run()
{
$a = true;
$b = false;
- var_dump(! $a === $b); // true
- var_dump(! ($a === $b)); // true
+ var_dump($a !== $b); // true
+ var_dump($a !== $b); // true
var_dump($a !== $b); // true
}
}
CallableThisArrayToAnonymousFunctionRector
Convert [$this, "method"] to proper anonymous function
class SomeClass
{
public function run()
{
$values = [1, 5, 3];
- usort($values, [$this, 'compareSize']);
+ usort($values, function ($first, $second) {
+ return $this->compareSize($first, $second);
+ });
return $values;
}
private function compareSize($first, $second)
{
return $first <=> $second;
}
}
ChangeArrayPushToArrayAssignRector
Change array_push() to direct variable assign
class SomeClass
{
public function run()
{
$items = [];
- array_push($items, $item);
+ $items[] = $item;
}
}
CombineIfRector
Merges nested if statements
class SomeClass {
public function run()
{
- if ($cond1) {
- if ($cond2) {
- return 'foo';
- }
+ if ($cond1 && $cond2) {
+ return 'foo';
}
}
}
CombinedAssignRector
Simplify $value = $value + 5; assignments to shorter ones
-$value = $value + 5;
+$value += 5;
CompactToVariablesRector
Change compact() call to own array
class SomeClass
{
public function run()
{
$checkout = 'one';
$form = 'two';
- return compact('checkout', 'form');
+ return ['checkout' => $checkout, 'form' => $form];
}
}
CompleteDynamicPropertiesRector
Add missing dynamic properties
class SomeClass
{
+ /**
+ * @var int
+ */
+ public $value;
public function set()
{
$this->value = 5;
}
}
ConsecutiveNullCompareReturnsToNullCoalesceQueueRector
- class:
Rector\CodeQuality\Rector\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector
- test fixtures
Change multiple null compares to ?? queue
class SomeClass
{
public function run()
{
- if (null !== $this->orderItem) {
- return $this->orderItem;
- }
-
- if (null !== $this->orderItemUnit) {
- return $this->orderItemUnit;
- }
-
- return null;
+ return $this->orderItem ?? $this->orderItemUnit;
}
}
ExplicitBoolCompareRector
Make if conditions more explicit
final class SomeController
{
public function run($items)
{
- if (!count($items)) {
+ if (count($items) === 0) {
return 'no items';
}
}
}
ForRepeatedCountToOwnVariableRector
Change count() in for function to own variable
class SomeClass
{
public function run($items)
{
- for ($i = 5; $i <= count($items); $i++) {
+ $itemsCount = count($items);
+ for ($i = 5; $i <= $itemsCount; $i++) {
echo $items[$i];
}
}
}
ForToForeachRector
Change for() to foreach() where useful
class SomeClass
{
public function run($tokens)
{
- for ($i = 0, $c = count($tokens); $i < $c; ++$i) {
- if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'fn') {
+ foreach ($tokens as $i => $token) {
+ if ($token[0] === T_STRING && $token[1] === 'fn') {
$previousNonSpaceToken = $this->getPreviousNonSpaceToken($tokens, $i);
if ($previousNonSpaceToken !== null && $previousNonSpaceToken[0] === T_OBJECT_OPERATOR) {
continue;
}
$tokens[$i][0] = self::T_FN;
}
}
}
}
ForeachItemsAssignToEmptyArrayToAssignRector
- class:
Rector\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector
- test fixtures
Change foreach() items assign to empty array to direct assign
class SomeClass
{
public function run($items)
{
$items2 = [];
- foreach ($items as $item) {
- $items2[] = $item;
- }
+ $items2 = $items;
}
}
ForeachToInArrayRector
Simplify foreach
loops into in_array
when possible
-foreach ($items as $item) {
- if ($item === "something") {
- return true;
- }
-}
-
-return false;
+in_array("something", $items, true);
GetClassToInstanceOfRector
Changes comparison with get_class to instanceof
-if (EventsListener::class === get_class($event->job)) { }
+if ($event->job instanceof EventsListener) { }
InArrayAndArrayKeysToArrayKeyExistsRector
Simplify in_array
and array_keys
functions combination into array_key_exists
when array_keys
has one argument only
-in_array("key", array_keys($array), true);
+array_key_exists("key", $array);
InlineIfToExplicitIfRector
Change inline if to explicit if
class SomeClass
{
public function run()
{
$userId = null;
- is_null($userId) && $userId = 5;
+ if (is_null($userId)) {
+ $userId = 5;
+ }
}
}
IntvalToTypeCastRector
Change intval() to faster and readable (int) $value
class SomeClass
{
public function run($value)
{
- return intval($value);
+ return (int) $value;
}
}
IsAWithStringWithThirdArgumentRector
class SomeClass
{
public function __construct(string $value)
{
- return is_a($value, 'stdClass');
+ return is_a($value, 'stdClass', true);
}
}
JoinStringConcatRector
Joins concat of 2 strings
class SomeClass
{
public function run()
{
- $name = 'Hi' . ' Tom';
+ $name = 'Hi Tom';
}
}
RemoveAlwaysTrueConditionSetInConstructorRector
If conditions is always true, perform the content right away
final class SomeClass
{
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function go()
{
- if ($this->value) {
- return 'yes';
- }
+ return 'yes';
}
}
RemoveSoleValueSprintfRector
Remove sprintf() wrapper if not needed
class SomeClass
{
public function run()
{
- $value = sprintf('%s', 'hi');
+ $value = 'hi';
$welcome = 'hello';
- $value = sprintf('%s', $welcome);
+ $value = $welcome;
}
}
ShortenElseIfRector
Shortens else/if to elseif
class SomeClass
{
public function run()
{
if ($cond1) {
return $action1;
- } else {
- if ($cond2) {
- return $action2;
- }
+ } elseif ($cond2) {
+ return $action2;
}
}
}
SimplifyArraySearchRector
Simplify array_search to in_array
-array_search("searching", $array) !== false;
+in_array("searching", $array, true);
-array_search("searching", $array) != false;
+in_array("searching", $array);
SimplifyBoolIdenticalTrueRector
Symplify bool value compare to true or false
class SomeClass
{
public function run(bool $value, string $items)
{
- $match = in_array($value, $items, TRUE) === TRUE;
- $match = in_array($value, $items, TRUE) !== FALSE;
+ $match = in_array($value, $items, TRUE);
+ $match = in_array($value, $items, TRUE);
}
}
SimplifyConditionsRector
Simplify conditions
-if (! ($foo !== 'bar')) {...
+if ($foo === 'bar') {...
SimplifyDeMorganBinaryRector
Simplify negated conditions with de Morgan theorem
<?php
$a = 5;
$b = 10;
-$result = !($a > 20 || $b <= 50);
+$result = $a <= 20 && $b > 50;
SimplifyDuplicatedTernaryRector
Remove ternary that duplicated return value of true : false
class SomeClass
{
public function run(bool $value, string $name)
{
- $isTrue = $value ? true : false;
+ $isTrue = $value;
$isName = $name ? true : false;
}
}
SimplifyEmptyArrayCheckRector
Simplify is_array
and empty
functions combination into a simple identical check for an empty array
-is_array($values) && empty($values)
+$values === []
SimplifyForeachToArrayFilterRector
Simplify foreach with function filtering to array filter
-$directories = [];
$possibleDirectories = [];
-foreach ($possibleDirectories as $possibleDirectory) {
- if (file_exists($possibleDirectory)) {
- $directories[] = $possibleDirectory;
- }
-}
+$directories = array_filter($possibleDirectories, 'file_exists');
SimplifyForeachToCoalescingRector
Changes foreach that returns set value to ??
-foreach ($this->oldToNewFunctions as $oldFunction => $newFunction) {
- if ($currentFunction === $oldFunction) {
- return $newFunction;
- }
-}
-
-return null;
+return $this->oldToNewFunctions[$currentFunction] ?? null;
SimplifyFuncGetArgsCountRector
Simplify count of func_get_args() to fun_num_args()
-count(func_get_args());
+func_num_args();
SimplifyIfElseToTernaryRector
Changes if/else for same value as assign to ternary
class SomeClass
{
public function run()
{
- if (empty($value)) {
- $this->arrayBuilt[][$key] = true;
- } else {
- $this->arrayBuilt[][$key] = $value;
- }
+ $this->arrayBuilt[][$key] = empty($value) ? true : $value;
}
}
SimplifyIfIssetToNullCoalescingRector
Simplify binary if to null coalesce
final class SomeController
{
public function run($possibleStatieYamlFile)
{
- if (isset($possibleStatieYamlFile['import'])) {
- $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'], $filesToImport);
- } else {
- $possibleStatieYamlFile['import'] = $filesToImport;
- }
+ $possibleStatieYamlFile['import'] = array_merge($possibleStatieYamlFile['import'] ?? [], $filesToImport);
}
}
SimplifyIfNotNullReturnRector
Changes redundant null check to instant return
$newNode = 'something ;
-if ($newNode !== null) {
- return $newNode;
-}
-
-return null;
+return $newNode;
SimplifyIfReturnBoolRector
Shortens if return false/true to direct return
-if (strpos($docToken->getContent(), "\n") === false) {
- return true;
-}
-
-return false;
+return strpos($docToken->getContent(), "\n") === false;
SimplifyInArrayValuesRector
Removes unneeded array_values() in in_array() call
-in_array("key", array_values($array), true);
+in_array("key", $array, true);
SimplifyRegexPatternRector
Simplify regex pattern to known ranges
class SomeClass
{
public function run($value)
{
- preg_match('#[a-zA-Z0-9+]#', $value);
+ preg_match('#[\w\d+]#', $value);
}
}
SimplifyStrposLowerRector
Simplify strpos(strtolower(), "...") calls
-strpos(strtolower($var), "...")"
+stripos($var, "...")"
SimplifyTautologyTernaryRector
Simplify tautology ternary to value
-$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;
+$value = $fullyQualifiedTypeHint;
SimplifyUselessVariableRector
Removes useless variable assigns
function () {
- $a = true;
- return $a;
+ return true;
};
SingleInArrayToCompareRector
Changes in_array() with single element to ===
class SomeClass
{
public function run()
{
- if (in_array(strtolower($type), ['$this'], true)) {
+ if (strtolower($type) === '$this') {
return strtolower($type);
}
}
}
StrlenZeroToIdenticalEmptyStringRector
class SomeClass
{
public function run($value)
{
- $empty = strlen($value) === 0;
+ $empty = $value === '';
}
}
ThrowWithPreviousExceptionRector
When throwing into a catch block, checks that the previous exception is passed to the new throw clause
class SomeClass
{
public function run()
{
try {
$someCode = 1;
} catch (Throwable $throwable) {
- throw new AnotherException('ups');
+ throw new AnotherException('ups', $throwable->getCode(), $throwable);
}
}
}
UnnecessaryTernaryExpressionRector
Remove unnecessary ternary expressions.
-$foo === $bar ? true : false;
+$foo === $bar;
UseIdenticalOverEqualWithSameTypeRector
Use ===/!== over ==/!=, it values have the same type
class SomeClass
{
public function run(int $firstValue, int $secondValue)
{
- $isSame = $firstValue == $secondValue;
- $isDiffernt = $firstValue != $secondValue;
+ $isSame = $firstValue === $secondValue;
+ $isDiffernt = $firstValue !== $secondValue;
}
}
CodingStyle
AddArrayDefaultToArrayPropertyRector
Adds array default value to property to prevent foreach over null error
class SomeClass
{
/**
* @var int[]
*/
- private $values;
+ private $values = [];
public function isEmpty()
{
- return $this->values === null;
+ return $this->values === [];
}
}
AnnotateThrowablesRector
Adds @throws DocBlock comments to methods that thrwo \Throwables.
class RootExceptionInMethodWithDocblock
{
/**
* This is a comment.
*
* @param int $code
+ * @throws \RuntimeException
*/
public function throwException(int $code)
{
throw new \RuntimeException('', $code);
}
}
BinarySwitchToIfElseRector
Changes switch with 2 options to if-else
-switch ($foo) {
- case 'my string':
- $result = 'ok';
- break;
-
- default:
- $result = 'not ok';
+if ($foo == 'my string') {
+ $result = 'ok;
+} else {
+ $result = 'not ok';
}
CallUserFuncCallToVariadicRector
Replace call_user_func_call with variadic
class SomeClass
{
public function run()
{
- call_user_func_array('some_function', $items);
+ some_function(...$items);
}
}
CamelCaseFunctionNamingToUnderscoreRector
Change CamelCase naming of functions to under_score naming
-function someCamelCaseFunction()
+function some_camel_case_function()
{
}
-someCamelCaseFunction();
+some_camel_case_function();
CatchExceptionNameMatchingTypeRector
Type and name of catch exception should match
class SomeClass
{
public function run()
{
try {
// ...
- } catch (SomeException $typoException) {
- $typoException->getMessage();
+ } catch (SomeException $someException) {
+ $someException->getMessage();
}
}
}
ConsistentImplodeRector
Changes various implode forms to consistent one
class SomeClass
{
public function run(array $items)
{
- $itemsAsStrings = implode($items);
- $itemsAsStrings = implode($items, '|');
+ $itemsAsStrings = implode('', $items);
+ $itemsAsStrings = implode('|', $items);
$itemsAsStrings = implode('|', $items);
}
}
ConsistentPregDelimiterRector
Replace PREG delimiter with configured one
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);
}
}
EncapsedStringsToSprintfRector
Convert enscaped {$string} to more readable sprintf
final class SomeClass
{
public function run(string $format)
{
- return "Unsupported format {$format}";
+ return sprintf('Unsupported format %s', $format);
}
}
FollowRequireByDirRector
include/require should be followed by absolute path
class SomeClass
{
public function run()
{
- require 'autoload.php';
+ require __DIR__ . '/autoload.php';
}
}
FunctionCallToConstantRector
Changes use of function calls to use constants
class SomeClass
{
public function run()
{
- $value = php_sapi_name();
+ $value = PHP_SAPI;
}
}
class SomeClass
{
public function run()
{
- $value = pi();
+ $value = M_PI;
}
}
IdenticalFalseToBooleanNotRector
Changes === false to negate !
-if ($something === false) {}
+if (! $something) {}
ImportFullyQualifiedNamesRector
Import fully qualified names to use statements
+use SomeAnother\AnotherClass;
+use DateTime;
+
class SomeClass
{
public function create()
{
- return SomeAnother\AnotherClass;
+ return AnotherClass;
}
public function createDate()
{
- return new \DateTime();
+ return new DateTime();
}
}
MakeInheritedMethodVisibilitySameAsParentRector
- class:
Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector
- test fixtures
Make method visibility same as parent one
class ChildClass extends ParentClass
{
- public function run()
+ protected function run()
{
}
}
class ParentClass
{
protected function run()
{
}
}
ManualJsonStringToJsonEncodeArrayRector
Add extra space before new assign set
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);
}
}
NewlineBeforeNewAssignSetRector
Add extra space before new assign set
final class SomeClass
{
public function run()
{
$value = new Value;
$value->setValue(5);
+
$value2 = new Value;
$value2->setValue(1);
}
}
NullableCompareToNullRector
Changes negate of empty comparison of nullable value to explicit === or !== compare
/** @var stdClass|null $value */
-if ($value) {
+if ($value !== null) {
}
-if (!$value) {
+if ($value === null) {
}
PreferThisOrSelfMethodCallRector
Changes $this->... to self:: or vise versa for specific types
services:
Rector\CodingStyle\Rector\MethodCall\PreferThisOrSelfMethodCallRector:
PHPUnit\TestCase: self
↓
class SomeClass extends PHPUnit\TestCase
{
public function run()
{
- $this->assertThis();
+ self::assertThis();
}
}
RemoveUnusedAliasRector
Removes unused use aliases. Keep annotation aliases like "Doctrine\ORM\Mapping as ORM" to keep convention format
-use Symfony\Kernel as BaseKernel;
+use Symfony\Kernel;
-class SomeClass extends BaseKernel
+class SomeClass extends Kernel
{
}
ReturnArrayClassMethodToYieldRector
Turns array return to yield return in specific type and method
services:
Rector\CodingStyle\Rector\ClassMethod\ReturnArrayClassMethodToYieldRector:
EventSubscriberInterface:
- getSubscribedEvents
↓
class SomeEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- return ['event' => 'callback'];
+ yield 'event' => 'callback';
}
}
SimpleArrayCallableToStringRector
Changes redundant anonymous bool functions to simple calls
-$paths = array_filter($paths, function ($path): bool {
- return is_dir($path);
-});
+array_filter($paths, "is_dir");
SplitDoubleAssignRector
Split multiple inline assigns to each own lines default value, to prevent undefined array issues
class SomeClass
{
public function run()
{
- $one = $two = 1;
+ $one = 1;
+ $two = 1;
}
}
SplitGroupedConstantsAndPropertiesRector
Separate constant and properties to own lines
class SomeClass
{
- const HI = true, AHOJ = 'true';
+ const HI = true;
+ const AHOJ = 'true';
/**
* @var string
*/
- public $isIt, $isIsThough;
+ public $isIt;
+
+ /**
+ * @var string
+ */
+ public $isIsThough;
}
SplitStringClassConstantToClassConstFetchRector
- class:
Rector\CodingStyle\Rector\String_\SplitStringClassConstantToClassConstFetchRector
- test fixtures
Separate class constant in a string to class constant fetch and string
class SomeClass
{
const HI = true;
}
class AnotherClass
{
public function get()
{
- return 'SomeClass::HI';
+ return SomeClass::class . '::HI';
}
}
StrictArraySearchRector
Makes array_search search for identical elements
-array_search($value, $items);
+array_search($value, $items, true);
SymplifyQuoteEscapeRector
Prefer quote that are not inside the string
class SomeClass
{
public function run()
{
- $name = "\" Tom";
- $name = '\' Sara';
+ $name = '" Tom';
+ $name = "' Sara";
}
}
UseIncrementAssignRector
Use ++ increment instead of $var += 1.
class SomeClass
{
public function run()
{
- $style += 1;
+ ++$style
}
}
VarConstantCommentRector
Constant should have a @var comment with type
class SomeClass
{
+ /**
+ * @var string
+ */
const HI = 'hi';
}
VersionCompareFuncCallToConstantRector
Changes use of call to version compare function to use of PHP version constant
class SomeClass
{
public function run()
{
- version_compare(PHP_VERSION, '5.3.0', '<');
+ PHP_VERSION_ID < 50300;
}
}
YieldClassMethodToArrayClassMethodRector
Turns yield return to array return in specific type and method
services:
Rector\CodingStyle\Rector\ClassMethod\YieldClassMethodToArrayClassMethodRector:
EventSubscriberInterface:
- getSubscribedEvents
↓
class SomeEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- yield 'event' => 'callback';
+ return ['event' => 'callback'];
}
}
DeadCode
RemoveAlwaysTrueIfConditionRector
Remove if condition that is always true
final class SomeClass
{
public function go()
{
- if (1 === 1) {
- return 'yes';
- }
+ return 'yes';
return 'no';
}
}
RemoveAndTrueRector
Remove and true that has no added value
class SomeClass
{
public function run()
{
- return true && 5 === 1;
+ return 5 === 1;
}
}
RemoveCodeAfterReturnRector
Remove dead code after return statement
class SomeClass
{
public function run(int $a)
{
return $a;
- $a++;
}
}
RemoveConcatAutocastRector
Remove (string) casting when it comes to concat, that does this by default
class SomeConcatingClass
{
public function run($value)
{
- return 'hi ' . (string) $value;
+ return 'hi ' . $value;
}
}
RemoveDeadConstructorRector
Remove empty constructor
class SomeClass
{
- public function __construct()
- {
- }
}
RemoveDeadIfForeachForRector
Remove if, foreach and for that does not do anything
class SomeClass
{
public function run($someObject)
{
$value = 5;
- if ($value) {
- }
-
if ($someObject->run()) {
- }
-
- foreach ($values as $value) {
}
return $value;
}
}
RemoveDeadReturnRector
Remove last return in the functions, since does not do anything
class SomeClass
{
public function run()
{
$shallWeDoThis = true;
if ($shallWeDoThis) {
return;
}
-
- return;
}
}
RemoveDeadStmtRector
Removes dead code statements
-$value = 5;
-$value;
+$value = 5;
RemoveDeadTryCatchRector
Remove dead try/catch
class SomeClass
{
public function run()
{
- try {
- // some code
- }
- catch (Throwable $throwable) {
- throw $throwable;
- }
+ // some code
}
}
RemoveDeadZeroAndOneOperationRector
class SomeClass
{
public function run()
{
- $value = 5 * 1;
- $value = 5 + 0;
+ $value = 5;
+ $value = 5;
}
}
RemoveDefaultArgumentValueRector
Remove argument value, if it is the same as default value
class SomeClass
{
public function run()
{
- $this->runWithDefault([]);
- $card = self::runWithStaticDefault([]);
+ $this->runWithDefault();
+ $card = self::runWithStaticDefault();
}
public function runWithDefault($items = [])
{
return $items;
}
public function runStaticWithDefault($cards = [])
{
return $cards;
}
}
RemoveDelegatingParentCallRector
class SomeClass
{
- public function prettyPrint(array $stmts): string
- {
- return parent::prettyPrint($stmts);
- }
}
RemoveDoubleAssignRector
Simplify useless double assigns
-$value = 1;
$value = 1;
RemoveDuplicatedArrayKeyRector
Remove duplicated key in defined arrays.
$item = [
- 1 => 'A',
1 => 'B'
];
RemoveDuplicatedCaseInSwitchRector
2 following switch keys with identical will be reduced to one result
class SomeClass
{
public function run()
{
switch ($name) {
case 'clearHeader':
return $this->modifyHeader($node, 'remove');
case 'clearAllHeaders':
- return $this->modifyHeader($node, 'replace');
case 'clearRawHeaders':
return $this->modifyHeader($node, 'replace');
case '...':
return 5;
}
}
}
RemoveDuplicatedInstanceOfRector
class SomeClass
{
public function run($value)
{
- $isIt = $value instanceof A || $value instanceof A;
- $isIt = $value instanceof A && $value instanceof A;
+ $isIt = $value instanceof A;
+ $isIt = $value instanceof A;
}
}
RemoveEmptyClassMethodRector
Remove empty method calls not required by parents
class OrphanClass
{
- public function __construct()
- {
- }
}
RemoveNullPropertyInitializationRector
Remove initialization with null value from property declarations
class SunshineCommand extends ParentClassWithNewConstructor
{
- private $myVar = null;
+ private $myVar;
}
RemoveOverriddenValuesRector
Remove initial assigns of overridden values
final class SomeController
{
public function run()
{
- $directories = [];
$possibleDirectories = [];
$directories = array_filter($possibleDirectories, 'file_exists');
}
}
RemoveParentCallWithoutParentRector
Remove unused parent call with no parent class
class OrphanClass
{
public function __construct()
{
- parent::__construct();
}
}
RemoveSetterOnlyPropertyAndMethodCallRector
Removes method that set values that are never used
class SomeClass
{
- private $name;
-
- public function setName($name)
- {
- $this->name = $name;
- }
}
class ActiveOnlySetter
{
public function run()
{
$someClass = new SomeClass();
- $someClass->setName('Tom');
}
}
RemoveUnreachableStatementRector
Remove unreachable statements
class SomeClass
{
public function run()
{
return 5;
-
- $removeMe = 10;
}
}
RemoveUnusedClassConstantRector
Remove unused class constants
class SomeClass
{
- private const SOME_CONST = 'dead';
-
public function run()
{
}
}
RemoveUnusedClassesRector
Remove unused classes without interface
interface SomeInterface
{
}
class SomeClass implements SomeInterface
{
public function run($items)
{
return null;
}
-}
-
-class NowhereUsedClass
-{
}
RemoveUnusedDoctrineEntityMethodAndPropertyRector
- class:
Rector\DeadCode\Rector\Class_\RemoveUnusedDoctrineEntityMethodAndPropertyRector
- test fixtures
Removes unused methods and properties from Doctrine entity classes
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;
- }
}
RemoveUnusedForeachKeyRector
Remove unused key in foreach
$items = [];
-foreach ($items as $key => $value) {
+foreach ($items as $value) {
$result = $value;
}
RemoveUnusedParameterRector
Remove unused parameter, if not required by interface or parent class
class SomeClass
{
- public function __construct($value, $value2)
+ public function __construct($value)
{
$this->value = $value;
}
}
RemoveUnusedPrivateConstantRector
Remove unused private constant
final class SomeController
{
- private const SOME_CONSTANT = 5;
public function run()
{
return 5;
}
}
RemoveUnusedPrivateMethodRector
Remove unused private method
final class SomeController
{
public function run()
{
return 5;
}
-
- private function skip()
- {
- return 10;
- }
}
RemoveUnusedPrivatePropertyRector
Remove unused private properties
class SomeClass
{
- private $property;
}
SimplifyIfElseWithSameContentRector
Remove if/else if they have same content
class SomeClass
{
public function run()
{
- if (true) {
- return 1;
- } else {
- return 1;
- }
+ return 1;
}
}
SimplifyMirrorAssignRector
Removes unneeded $a = $a assigns
-$a = $a;
TernaryToBooleanOrFalseToBooleanAndRector
Change ternary of bool : false to && bool
class SomeClass
{
public function go()
{
- return $value ? $this->getBool() : false;
+ return $value && $this->getBool();
}
private function getBool(): bool
{
return (bool) 5;
}
}
Doctrine
AddEntityIdByConditionRector
Add entity id with annotations when meets condition
services:
Rector\Doctrine\Rector\Class_\AddEntityIdByConditionRector: { }
↓
class SomeClass
{
use SomeTrait;
+
+ /**
+ * @ORM\Id
+ * @ORM\Column(type="integer")
+ * @ORM\GeneratedValue(strategy="AUTO")
+ */
+ private $id;
+
+ public function getId(): int
+ {
+ return $this->id;
+ }
}
AddUuidAnnotationsToIdPropertyRector
Add uuid annotations to $id property
AddUuidMirrorForRelationPropertyRector
Adds $uuid property to entities, that already have $id with integer type.Require for step-by-step migration from int to uuid.
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
AlwaysInitializeUuidInEntityRector
Add uuid initializion to all entities that misses it
ChangeGetIdTypeToUuidRector
Change return type of getId() to uuid interface
ChangeGetUuidMethodCallToGetIdRector
Change getUuid() method call to getId()
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;
}
}
ChangeIdenticalUuidToEqualsMethodCallRector
Change $uuid === 1 to $uuid->equals(\Ramsey\Uuid\Uuid::fromString(1))
class SomeClass
{
public function match($checkedId): int
{
$building = new Building();
- return $building->getId() === $checkedId;
+ return $building->getId()->equals(\Ramsey\Uuid\Uuid::fromString($checkedId));
}
}
ChangeReturnTypeOfClassMethodWithGetIdRector
- class:
Rector\Doctrine\Rector\ClassMethod\ChangeReturnTypeOfClassMethodWithGetIdRector
- test fixtures
Change getUuid() method call to getId()
class SomeClass
{
- public function getBuildingId(): int
+ public function getBuildingId(): \Ramsey\Uuid\UuidInterface
{
$building = new Building();
return $building->getId();
}
}
ChangeSetIdToUuidValueRector
Change set id to uuid values
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
class SomeClass
{
public function run()
{
$buildingFirst = new Building();
- $buildingFirst->setId(1);
- $buildingFirst->setUuid(Uuid::fromString('a3bfab84-e207-4ddd-b96d-488151de9e96'));
+ $buildingFirst->setId(Uuid::fromString('a3bfab84-e207-4ddd-b96d-488151de9e96'));
}
}
/**
* @ORM\Entity
*/
class Building
{
}
ChangeSetIdTypeToUuidRector
Change param type of setId() to uuid interface
EntityAliasToClassConstantReferenceRector
Replaces doctrine alias with class.
$entityManager = new Doctrine\ORM\EntityManager();
-$entityManager->getRepository("AppBundle:Post");
+$entityManager->getRepository(\App\Entity\Post::class);
ManagerRegistryGetManagerToEntityManagerRector
-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');
}
}
RemoveRepositoryFromEntityAnnotationRector
Removes repository class from @Entity annotation
use Doctrine\ORM\Mapping as ORM;
/**
- * @ORM\Entity(repositoryClass="ProductRepository")
+ * @ORM\Entity
*/
class Product
{
}
RemoveTemporaryUuidColumnPropertyRector
Remove temporary $uuid property
RemoveTemporaryUuidRelationPropertyRector
Remove temporary *Uuid relation properties
DoctrineCodeQuality
ChangeQuerySetParametersMethodParameterFromArrayToArrayCollectionRector
- class:
Rector\DoctrineCodeQuality\Rector\Class_\ChangeQuerySetParametersMethodParameterFromArrayToArrayCollectionRector
- test fixtures
Change array to ArrayCollection in setParameters method of query builder
-use Doctrine\ORM\EntityRepository;
+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()
;
}
}
InitializeDefaultEntityCollectionRector
- class:
Rector\DoctrineCodeQuality\Rector\Class_\InitializeDefaultEntityCollectionRector
- test fixtures
Initialize collection property in Entity constructor
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class SomeClass
{
/**
* @ORM\OneToMany(targetEntity="MarketingEvent")
*/
private $marketingEvents = [];
+
+ public function __construct()
+ {
+ $this->marketingEvents = new ArrayCollection();
+ }
}
DoctrineGedmoToKnplabs
BlameableBehaviorRector
Change Blameable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
-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;
}
LoggableBehaviorRector
Change Loggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
-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;
}
SluggableBehaviorRector
Change Sluggable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
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'];
}
}
SoftDeletableBehaviorRector
Change SoftDeletable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
-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;
}
TimestampableBehaviorRector
Change Timestampable from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
-use Gedmo\Timestampable\Traits\TimestampableEntity;
+use Knp\DoctrineBehaviors\Model\Timestampable\TimestampableTrait;
+use Knp\DoctrineBehaviors\Contract\Entity\TimestampableInterface;
-class SomeClass
+class SomeClass implements TimestampableInterface
{
- use TimestampableEntity;
+ use TimestampableTrait;
}
TranslationBehaviorRector
Change Translation from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
-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;
- }
}
TreeBehaviorRector
Change Tree from gedmo/doctrine-extensions to knplabs/doctrine-behaviors
-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;
}
DynamicTypeAnalysis
AddArgumentTypeWithProbeDataRector
- class:
Rector\DynamicTypeAnalysis\Rector\ClassMethod\AddArgumentTypeWithProbeDataRector
- test fixtures
Add argument type based on probed data
class SomeClass
{
- public function run($arg)
+ public function run(string $arg)
{
}
}
DecorateMethodWithArgumentTypeProbeRector
- class:
Rector\DynamicTypeAnalysis\Rector\ClassMethod\DecorateMethodWithArgumentTypeProbeRector
- test fixtures
Add probe that records argument types to each method
class SomeClass
{
public function run($arg)
{
+ \Rector\DynamicTypeAnalysis\Probe\TypeStaticProbe::recordArgumentType($arg, __METHOD__, 0);
}
}
RemoveArgumentTypeProbeRector
Clean up probe that records argument types
-use Rector\DynamicTypeAnalysis\Probe\TypeStaticProbe;
-
class SomeClass
{
public function run($arg)
{
- TypeStaticProbe::recordArgumentType($arg, __METHOD__, 0);
}
}
ElasticSearchDSL
MigrateFilterToQueryRector
Migrates addFilter to addQuery
use ONGR\ElasticsearchDSL\Search;
use ONGR\ElasticsearchDSL\Query\TermsQuery;
+use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
class SomeClass
{
public function run()
{
$search = new Search();
- $search->addFilter(
- new TermsQuery('categoryIds', [1, 2])
+ $search->addQuery(
+ new TermsQuery('categoryIds', [1, 2]),
+ BoolQuery::FILTER
);
}
}
FileSystemRector
RemoveProjectFileRector
Remove file relative to project directory
Guzzle
MessageAsArrayRector
Changes getMessage(..., true) to getMessageAsArray()
/** @var GuzzleHttp\Message\MessageInterface */
-$value = $message->getMessage('key', true);
+$value = $message->getMessageAsArray('key');
JMS
RemoveJmsInjectParamsAnnotationRector
Removes JMS\DiExtraBundle\Annotation\InjectParams annotation
use JMS\DiExtraBundle\Annotation as DI;
class SomeClass
{
- /**
- * @DI\InjectParams({
- * "subscribeService" = @DI\Inject("app.email.service.subscribe"),
- * "ipService" = @DI\Inject("app.util.service.ip")
- * })
- */
public function __construct()
{
}
-}
+}
RemoveJmsInjectServiceAnnotationRector
Removes JMS\DiExtraBundle\Annotation\Services annotation
use JMS\DiExtraBundle\Annotation as DI;
-/**
- * @DI\Service("email.web.services.subscribe_token", public=true)
- */
class SomeClass
{
}
Laravel
FacadeStaticCallToConstructorInjectionRector
Move Illuminate\Support\Facades* static calls to constructor injection
use Illuminate\Support\Facades\Response;
class ExampleController extends Controller
{
+ /**
+ * @var \Illuminate\Contracts\Routing\ResponseFactory
+ */
+ private $responseFactory;
+
+ public function __construct(\Illuminate\Contracts\Routing\ResponseFactory $responseFactory)
+ {
+ $this->responseFactory = $responseFactory;
+ }
+
public function store()
{
- return Response::view('example', ['new_example' => 123]);
+ return $this->responseFactory->view('example', ['new_example' => 123]);
}
}
HelperFunctionToConstructorInjectionRector
Move help facade-like function calls to constructor injection
class SomeController
{
+ /**
+ * @var \Illuminate\Contracts\View\Factory
+ */
+ private $viewFactory;
+
+ public function __construct(\Illuminate\Contracts\View\Factory $viewFactory)
+ {
+ $this->viewFactory = $viewFactory;
+ }
+
public function action()
{
- $template = view('template.blade');
- $viewFactory = view();
+ $template = $this->viewFactory->make('template.blade');
+ $viewFactory = $this->viewFactory;
}
}
InlineValidationRulesToArrayDefinitionRector
Transforms inline validation rules to array definition
use Illuminate\Foundation\Http\FormRequest;
class SomeClass extends FormRequest
{
public function rules(): array
{
return [
- 'someAttribute' => 'required|string|exists:' . SomeModel::class . 'id',
+ 'someAttribute' => ['required', 'string', \Illuminate\Validation\Rule::exists(SomeModel::class, 'id')],
];
}
}
MinutesToSecondsInCacheRector
Change minutes argument to seconds in Illuminate\Contracts\Cache\Store and Illuminate\Support\Facades\Cache
class SomeClass
{
public function run()
{
- Illuminate\Support\Facades\Cache::put('key', 'value', 60);
+ Illuminate\Support\Facades\Cache::put('key', 'value', 60 * 60);
}
}
Redirect301ToPermanentRedirectRector
Change "redirect" call with 301 to "permanentRedirect"
class SomeClass
{
public function run()
{
- Illuminate\Routing\Route::redirect('/foo', '/bar', 301);
+ Illuminate\Routing\Route::permanentRedirect('/foo', '/bar');
}
}
RequestStaticValidateToInjectRector
Change static validate() method to $request->validate()
use Illuminate\Http\Request;
class SomeClass
{
- public function store()
+ public function store(\Illuminate\Http\Request $request)
{
- $validatedData = Request::validate(['some_attribute' => 'required']);
+ $validatedData = $request->validate(['some_attribute' => 'required']);
}
}
Legacy
ChangeSingletonToServiceRector
Change singleton class to normal class that can be registered as a service
class SomeClass
{
- private static $instance;
-
- private function __construct()
+ public function __construct()
{
- }
-
- public static function getInstance()
- {
- if (null === static::$instance) {
- static::$instance = new static();
- }
-
- return static::$instance;
}
}
MinimalScope
ChangeLocalPropertyToVariableRector
Change local property used in single method to local variable
class SomeClass
{
- private $count;
public function run()
{
- $this->count = 5;
- return $this->count;
+ $count = 5;
+ return $count;
}
}
MysqlToMysqli
MysqlAssignToMysqliRector
Converts more complex mysql functions to mysqli
-$data = mysql_db_name($result, $row);
+mysqli_data_seek($result, $row);
+$fetch = mysql_fetch_row($result);
+$data = $fetch[0];
MysqlFuncCallToMysqliRector
Converts more complex mysql functions to mysqli
-mysql_drop_db($database);
+mysqli_query('DROP DATABASE ' . $database);
MysqlPConnectToMysqliConnectRector
Replace mysql_pconnect() with mysqli_connect() with host p: prefix
final class SomeClass
{
public function run($host, $username, $password)
{
- return mysql_pconnect($host, $username, $password);
+ return mysqli_connect('p:' . $host, $username, $password);
}
}
Nette
AddDatePickerToDateControlRector
Nextras/Form upgrade of addDatePicker method call to DateControl assign
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');
}
}
EndsWithFunctionToNetteUtilsStringsRector
Use Nette\Utils\Strings over bare string-functions
class SomeClass
{
public function end($needle)
{
$content = 'Hi, my name is Tom';
- $yes = substr($content, -strlen($needle)) === $needle;
- $no = $needle !== substr($content, -strlen($needle));
+ $yes = \Nette\Utils\Strings::endsWith($content, $needle);
+ $no = !\Nette\Utils\Strings::endsWith($content, $needle);
}
}
FilePutContentsToFileSystemWriteRector
Change file_put_contents() to FileSystem::write()
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);
}
}
JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector
- class:
Rector\Nette\Rector\FuncCall\JsonDecodeEncodeToNetteUtilsJsonDecodeEncodeRector
- test fixtures
Changes json_encode()/json_decode() to safer and more verbose Nette\Utils\Json::encode()/decode() calls
class SomeClass
{
public function decodeJson(string $jsonString)
{
- $stdClass = json_decode($jsonString);
+ $stdClass = \Nette\Utils\Json::decode($jsonString);
- $array = json_decode($jsonString, true);
- $array = json_decode($jsonString, false);
+ $array = \Nette\Utils\Json::decode($jsonString, \Nette\Utils\Json::FORCE_ARRAY);
+ $array = \Nette\Utils\Json::decode($jsonString);
}
public function encodeJson(array $data)
{
- $jsonString = json_encode($data);
+ $jsonString = \Nette\Utils\Json::encode($data);
- $prettyJsonString = json_encode($data, JSON_PRETTY_PRINT);
+ $prettyJsonString = \Nette\Utils\Json::encode($data, \Nette\Utils\Json::PRETTY);
}
}
PregFunctionToNetteUtilsStringsRector
Use Nette\Utils\Strings over bare preg_* functions
+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#');
}
}
SetClassWithArgumentToSetFactoryRector
Change setClass with class and arguments to separated methods
use Nette\DI\ContainerBuilder;
class SomeClass
{
public function run(ContainerBuilder $containerBuilder)
{
$containerBuilder->addDefinition('...')
- ->setClass('SomeClass', [1, 2]);
+ ->setFactory('SomeClass', [1, 2]);
}
}
StartsWithFunctionToNetteUtilsStringsRector
Use Nette\Utils\Strings over bare string-functions
class SomeClass
{
public function start($needle)
{
$content = 'Hi, my name is Tom';
- $yes = substr($content, 0, strlen($needle)) === $needle;
- $no = $needle !== substr($content, 0, strlen($needle));
+ $yes = \Nette\Utils\Strings::startwith($content, $needle);
+ $no = !\Nette\Utils\Strings::startwith($content, $needle);
}
}
StrposToStringsContainsRector
Use Nette\Utils\Strings over bare string-functions
class SomeClass
{
public function run()
{
$name = 'Hi, my name is Tom';
- return strpos($name, 'Hi') !== false;
+ return \Nette\Utils\Strings::contains($name, 'Hi');
}
}
SubstrStrlenFunctionToNetteUtilsStringsRector
Use Nette\Utils\Strings over bare string-functions
class SomeClass
{
public function run()
{
- return substr($value, 0, 3);
+ return \Nette\Utils\Strings::substring($value, 0, 3);
}
}
TemplateMagicAssignToExplicitVariableArrayRector
- class:
Rector\Nette\Rector\ClassMethod\TemplateMagicAssignToExplicitVariableArrayRector
- test fixtures
Change $this->templates->{magic} to $this->template->render(..., $values)
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']);
}
}
NetteTesterToPHPUnit
NetteAssertToPHPUnitAssertRector
Migrate Nette/Assert calls to PHPUnit
use Tester\Assert;
function someStaticFunctions()
{
- Assert::true(10 == 5);
+ \PHPUnit\Framework\Assert::assertTrue(10 == 5);
}
NetteTesterClassToPHPUnitClassRector
Migrate Nette Tester test case to PHPUnit
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();
+}
RenameTesterTestToPHPUnitToTestFileRector
Rename "*.phpt" file to "*Test.php" file
NetteToSymfony
DeleteFactoryInterfaceRector
Interface factories are not needed in Symfony. Clear constructor injection is used instead
FormControlToControllerAndFormTypeRector
Change Form that extends Control to Controller and decoupled FormType
-use Nette\Application\UI\Form;
-use Nette\Application\UI\Control;
-
-class SomeForm extends Control
+class SomeFormController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
- public function createComponentForm()
+ /**
+ * @Route(...)
+ */
+ public function actionSomeForm(\Symfony\Component\HttpFoundation\Request $request): \Symfony\Component\HttpFoundation\Response
{
- $form = new Form();
- $form->addText('name', 'Your name');
+ $form = $this->createForm(SomeFormType::class);
+ $form->handleRequest($request);
- $form->onSuccess[] = [$this, 'processForm'];
- }
-
- public function processForm(Form $form)
- {
- // process me
+ if ($form->isSuccess() && $form->isValid()) {
+ // process me
+ }
}
}
FromHttpRequestGetHeaderToHeadersGetRector
- class:
Rector\NetteToSymfony\Rector\MethodCall\FromHttpRequestGetHeaderToHeadersGetRector
- test fixtures
Changes getHeader() to $request->headers->get()
use Nette\Request;
final class SomeController
{
public static function someAction(Request $request)
{
- $header = $this->httpRequest->getHeader('x');
+ $header = $request->headers->get('x');
}
}
FromRequestGetParameterToAttributesGetRector
- class:
Rector\NetteToSymfony\Rector\MethodCall\FromRequestGetParameterToAttributesGetRector
- test fixtures
Changes "getParameter()" to "attributes->get()" from Nette to Symfony
use Nette\Request;
final class SomeController
{
public static function someAction(Request $request)
{
- $value = $request->getParameter('abz');
+ $value = $request->attribute->get('abz');
}
}
NetteControlToSymfonyControllerRector
Migrate Nette Component to Symfony Controller
-use Nette\Application\UI\Control;
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+use Symfony\Component\HttpFoundation\Response;
-class SomeControl extends Control
+class SomeController extends AbstractController
{
- public function render()
- {
- $this->template->param = 'some value';
- $this->template->render(__DIR__ . '/poll.latte');
- }
+ public function some(): Response
+ {
+ return $this->render(__DIR__ . '/poll.latte', ['param' => 'some value']);
+ }
}
NetteFormToSymfonyFormRector
Migrate Nette\Forms in Presenter to Symfony
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'
+ ]);
}
}
RenameEventNamesInEventSubscriberRector
- class:
Rector\NetteToSymfony\Rector\ClassMethod\RenameEventNamesInEventSubscriberRector
- test fixtures
Changes event names from Nette ones to Symfony ones
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class SomeClass implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
- return ['nette.application' => 'someMethod'];
+ return [\SymfonyEvents::KERNEL => 'someMethod'];
}
}
RouterListToControllerAnnotationsRector
- class:
Rector\NetteToSymfony\Rector\ClassMethod\RouterListToControllerAnnotationsRector
- test fixtures
Change new Route() from RouteFactory to @Route annotation above controller method
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()
{
}
}
WrapTransParameterNameRector
Adds %% to placeholder name of trans() method if missing
use Symfony\Component\Translation\Translator;
final class SomeController
{
public function run()
{
$translator = new Translator('');
$translated = $translator->trans(
'Hello %name%',
- ['name' => $name]
+ ['%name%' => $name]
);
}
}
Oxid
OxidReplaceBackwardsCompatabilityClassRector
Replaces deprecated backwards compatability classes with namespaces ones in oxNew
-oxNew("oxcmp_basket");
+oxNew(\OxidEsales\Eshop\Application\Component\BasketComponent::class);
PHPStan
PHPStormVarAnnotationRector
Change various @var annotation formats to one PHPStorm understands
-$config = 5;
-/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+/** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */
+$config = 5;
RecastingRemovalRector
Removes recasting of the same type
$string = '';
-$string = (string) $string;
+$string = $string;
$array = [];
-$array = (array) $array;
+$array = $array;
RemoveNonExistingVarAnnotationRector
Removes non-existing @var annotations above the code
class SomeClass
{
public function get()
{
- /** @var Training[] $trainings */
return $this->getData();
}
}
PHPUnit
AddDoesNotPerformAssertionToNonAssertingTestRector
- class:
Rector\PHPUnit\Rector\ClassMethod\AddDoesNotPerformAssertionToNonAssertingTestRector
- test fixtures
Tests without assertion will have @doesNotPerformAssertion
class SomeClass extends PHPUnit\Framework\TestCase
{
+ /**
+ * @doesNotPerformAssertion
+ */
public function test()
{
$nothing = 5;
}
}
AddSeeTestAnnotationRector
Add @see annotation test of the class for faster jump to test. Make it FQN, so it stays in the annotation, not in the PHP source code.
+/**
+ * @see \SomeServiceTest
+ */
class SomeService
{
}
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
{
}
ArrayArgumentInTestToDataProviderRector
Move array argument from tests into data provider [configurable]
services:
Rector\PHPUnit\Rector\Class_\ArrayArgumentInTestToDataProviderRector:
$configuration:
-
class: PHPUnit\Framework\TestCase
old_method: doTestMultiple
new_method: doTestSingle
variable_name: number
↓
use PHPUnit\Framework\TestCase;
class SomeServiceTest extends TestCase
{
- public function test()
+ /**
+ * @dataProvider provideData()
+ */
+ public function test(int $number)
{
- $this->doTestMultiple([1, 2, 3]);
+ $this->doTestSingle($number);
+ }
+
+ public function provideData(): \Iterator
+ {
+ yield [1];
+ yield [2];
+ yield [3];
}
}
AssertCompareToSpecificMethodRector
Turns vague php-only method in PHPUnit TestCase to more specific
-$this->assertSame(10, count($anything), "message");
+$this->assertCount(10, $anything, "message");
-$this->assertNotEquals(get_class($value), stdClass::class);
+$this->assertNotInstanceOf(stdClass::class, $value);
AssertComparisonToSpecificMethodRector
Turns comparison operations to their method name alternatives in PHPUnit TestCase
-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
-$this->assertFalse($foo >= $bar, "message");
+$this->assertLessThanOrEqual($bar, $foo, "message");
AssertEqualsParameterToSpecificMethodsTypeRector
- class:
Rector\PHPUnit\Rector\MethodCall\AssertEqualsParameterToSpecificMethodsTypeRector
- test fixtures
Change assertEquals()/assertNotEquals() method parameters to new specific alternatives
final class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
$value = 'value';
- $this->assertEquals('string', $value, 'message', 5.0);
+ $this->assertEqualsWithDelta('string', $value, 5.0, 'message');
- $this->assertEquals('string', $value, 'message', 0.0, 20);
+ $this->assertEquals('string', $value, 'message', 0.0);
- $this->assertEquals('string', $value, 'message', 0.0, 10, true);
+ $this->assertEqualsCanonicalizing('string', $value, 'message');
- $this->assertEquals('string', $value, 'message', 0.0, 10, false, true);
+ $this->assertEqualsIgnoringCase('string', $value, 'message');
}
}
AssertFalseStrposToContainsRector
Turns strpos
/stripos
comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
-$this->assertNotFalse(stripos($anything, "foo"), "message");
+$this->assertContains("foo", $anything, "message");
AssertInstanceOfComparisonRector
Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertInstanceOf("Foo", $foo, "message");
-$this->assertFalse($foo instanceof Foo, "message");
+$this->assertNotInstanceOf("Foo", $foo, "message");
AssertIssetToSpecificMethodRector
Turns isset comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue(isset($anything->foo));
+$this->assertObjectHasAttribute("foo", $anything);
-$this->assertFalse(isset($anything["foo"]), "message");
+$this->assertArrayNotHasKey("foo", $anything, "message");
AssertNotOperatorRector
Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
-$this->assertFalse(!$foo, "message");
+$this->assertTrue($foo, "message");
AssertPropertyExistsRector
Turns property_exists
comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue(property_exists(new Class, "property"), "message");
+$this->assertClassHasAttribute("property", "Class", "message");
-$this->assertFalse(property_exists(new Class, "property"), "message");
+$this->assertClassNotHasAttribute("property", "Class", "message");
AssertRegExpRector
Turns preg_match
comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertSame(1, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertRegExp("/^Message for ".*"\.$/", $string, $message);
-$this->assertEquals(false, preg_match("/^Message for ".*"\.$/", $string), $message);
+$this->assertNotRegExp("/^Message for ".*"\.$/", $string, $message);
AssertSameBoolNullToSpecificMethodRector
Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertSame(null, $anything);
+$this->assertNull($anything);
-$this->assertNotSame(false, $anything);
+$this->assertNotFalse($anything);
AssertTrueFalseInternalTypeToSpecificMethodRector
- class:
Rector\PHPUnit\Rector\SpecificMethod\AssertTrueFalseInternalTypeToSpecificMethodRector
- test fixtures
Turns true/false with internal type comparisons to their method name alternatives in PHPUnit TestCase
-$this->assertTrue(is_{internal_type}($anything), "message");
+$this->assertInternalType({internal_type}, $anything, "message");
-$this->assertFalse(is_{internal_type}($anything), "message");
+$this->assertNotInternalType({internal_type}, $anything, "message");
AssertTrueFalseToSpecificMethodRector
Turns true/false comparisons to their method name alternatives in PHPUnit TestCase when possible
-$this->assertTrue(is_readable($readmeFile), "message");
+$this->assertIsReadable($readmeFile, "message");
DelegateExceptionArgumentsRector
Takes setExpectedException()
2nd and next arguments to own methods in PHPUnit.
-$this->setExpectedException(Exception::class, "Message", "CODE");
+$this->setExpectedException(Exception::class);
+$this->expectExceptionMessage("Message");
+$this->expectExceptionCode("CODE");
EnsureDataProviderInDocBlockRector
Data provider annotation must be in doc block
class SomeClass extends PHPUnit\Framework\TestCase
{
- /*
+ /**
* @dataProvider testProvideData()
*/
public function test()
{
$nothing = 5;
}
}
ExceptionAnnotationRector
Takes setExpectedException()
2nd and next arguments to own methods in PHPUnit.
-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
public function test()
{
+ $this->expectException('Exception');
+ $this->expectExceptionMessage('Message');
// tested code
}
ExplicitPhpErrorApiRector
Use explicit API for expecting PHP errors, warnings, and notices
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();
}
}
FixDataProviderAnnotationTypoRector
Fix data provider annotation typos
class SomeClass extends \PHPUnit\Framework\TestCase
{
/**
- * @dataProvidor testProvideData()
+ * @dataProvider testProvideData()
*/
public function test()
{
$nothing = 5;
}
}
GetMockBuilderGetMockToCreateMockRector
Remove getMockBuilder() to createMock()
class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
- $applicationMock = $this->getMockBuilder('SomeClass')
- ->disableOriginalConstructor()
- ->getMock();
+ $applicationMock = $this->createMock('SomeClass');
}
}
GetMockRector
Turns getMock*() methods to createMock()
-$this->getMock("Class");
+$this->createMock("Class");
-$this->getMockWithoutInvokingTheOriginalConstructor("Class");
+$this->createMock("Class");
RemoveDataProviderTestPrefixRector
Data provider methods cannot start with "test" prefix
class SomeClass extends PHPUnit\Framework\TestCase
{
/**
- * @dataProvider testProvideData()
+ * @dataProvider provideData()
*/
public function test()
{
$nothing = 5;
}
- public function testProvideData()
+ public function provideData()
{
return ['123'];
}
}
RemoveEmptyTestMethodRector
Remove empty test methods
class SomeTest extends \PHPUnit\Framework\TestCase
{
- /**
- * testGetTranslatedModelField method
- *
- * @return void
- */
- public function testGetTranslatedModelField()
- {
- }
}
RemoveExpectAnyFromMockRector
Remove expect($this->any())
from mocks as it has no added value
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 }}!');
}
}
ReplaceAssertArraySubsetRector
Replace deprecated "assertArraySubset()" method with alternative methods
class SomeTest extends \PHPUnit\Framework\TestCase
{
public function test()
{
$checkedArray = [];
- $this->assertArraySubset([
- 'cache_directory' => 'new_value',
- ], $checkedArray);
+ $this->assertArrayHasKey('cache_directory', $checkedArray);
+ $this->assertSame('new_value', $checkedArray['cache_directory']);
}
}
ReplaceAssertArraySubsetWithDmsPolyfillRector
Change assertArraySubset() to static call of DMS\PHPUnitExtensions\ArraySubset\Assert
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);
}
}
SelfContainerGetMethodCallFromTestToInjectPropertyRector
- class:
Rector\PHPUnit\Rector\Class_\SelfContainerGetMethodCallFromTestToInjectPropertyRector
- test fixtures
Change $container->get() calls in PHPUnit to @inject properties autowired by jakzal/phpunit-injector
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 { }
SimplifyForeachInstanceOfRector
Simplify unnecessary foreach check of instances
-foreach ($foos as $foo) {
- $this->assertInstanceOf(\SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);
SpecificAssertContainsRector
Change assertContains()/assertNotContains() method to new string and iterable alternatives
<?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');
}
}
SpecificAssertInternalTypeRector
Change assertInternalType()/assertNotInternalType() method to new specific alternatives
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);
}
}
TestListenerToHooksRector
Refactor "*TestListener.php" to particular "*Hook.php" files
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;
}
}
TryCatchToExpectExceptionRector
Turns try/catch to expectException() call
-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();
UseSpecificWillMethodRector
Changes ->will($this->xxx()) to one specific method
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 }}!');
}
}
WithConsecutiveArgToArrayRector
Split withConsecutive() arg to array
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]);
}
}
PHPUnitSymfony
AddMessageToEqualsResponseCodeRector
Add response content to response code assert, so it is easier to debug
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()
);
}
}
PSR4
NormalizeNamespaceByPSR4ComposerAutoloadRector
Changes namespace and class names to match PSR-4 in composer.json autoload section
Phalcon
AddRequestToHandleMethodCallRector
Add $_SERVER REQUEST_URI to method call
class SomeClass {
public function run($di)
{
$application = new \Phalcon\Mvc\Application();
- $response = $application->handle();
+ $response = $application->handle($_SERVER["REQUEST_URI"]);
}
}
DecoupleSaveMethodCallWithArgumentToAssignRector
- class:
Rector\Phalcon\Rector\MethodCall\DecoupleSaveMethodCallWithArgumentToAssignRector
- test fixtures
Decouple Phalcon\Mvc\Model::save() with argument to assign()
class SomeClass
{
public function run(\Phalcon\Mvc\Model $model, $data)
{
- $model->save($data);
+ $model->save();
+ $model->assign($data);
}
}
FlashWithCssClassesToExtraCallRector
Add $cssClasses in Flash to separated method call
class SomeClass {
public function run()
{
$cssClasses = [];
- $flash = new Phalcon\Flash($cssClasses);
+ $flash = new Phalcon\Flash();
+ $flash->setCssClasses($cssClasses);
}
}
NewApplicationToToFactoryWithDefaultContainerRector
- class:
Rector\Phalcon\Rector\Assign\NewApplicationToToFactoryWithDefaultContainerRector
- test fixtures
Change new application to default factory with application
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"]);
}
}
Php52
ContinueToBreakInSwitchRector
Use break instead of continue in switch statements
function some_run($value)
{
switch ($value) {
case 1:
echo 'Hi';
- continue;
+ break;
case 2:
echo 'Hello';
break;
}
}
VarToPublicPropertyRector
Remove unused private method
final class SomeController
{
- var $name = 'Tom';
+ public $name = 'Tom';
}
Php53
DirNameFileConstantToDirConstantRector
Convert dirname(FILE) to DIR
class SomeClass
{
public function run()
{
- return dirname(__FILE__);
+ return __DIR__;
}
}
TernaryToElvisRector
Use ?: instead of ?, where useful
function elvis()
{
- $value = $a ? $a : false;
+ $value = $a ?: false;
}
Php54
RemoveReferenceFromCallRector
Remove & from function and method calls
final class SomeClass
{
public function run($one)
{
- return strlen(&$one);
+ return strlen($one);
}
}
RemoveZeroBreakContinueRector
Remove 0 from break and continue
class SomeClass
{
public function run($random)
{
- continue 0;
- break 0;
+ continue;
+ break;
$five = 5;
- continue $five;
+ continue 5;
- break $random;
+ break;
}
}
Php55
PregReplaceEModifierRector
The /e modifier is no longer supported, use preg_replace_callback instead
class SomeClass
{
public function run()
{
- $comment = preg_replace('~\b(\w)(\w+)~e', '"$1".strtolower("$2")', $comment);
+ $comment = preg_replace_callback('~\b(\w)(\w+)~', function ($matches) {
+ return($matches[1].strtolower($matches[2]));
+ }, , $comment);
}
}
StringClassNameToClassConstantRector
Replace string class names by ::class constant
class AnotherClass
{
}
class SomeClass
{
public function run()
{
- return 'AnotherClass';
+ return \AnotherClass::class;
}
}
Php56
AddDefaultValueForUndefinedVariableRector
Adds default value for undefined variable
class SomeClass
{
public function run()
{
+ $a = null;
if (rand(0, 1)) {
$a = 5;
}
echo $a;
}
}
PowToExpRector
Changes pow(val, val2) to ** (exp) parameter
-pow(1, 2);
+1**2;
Php70
BreakNotInLoopOrSwitchToReturnRector
Convert break outside for/foreach/switch context to return
class SomeClass
{
public function run()
{
$zhrs = abs($gmt)/3600;
$hrs = floor($zhrs);
if ($isphp5)
return sprintf('%s%02d%02d',($gmt<=0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60);
else
return sprintf('%s%02d%02d',($gmt<0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60);
- break;
+ return;
}
}
CallUserMethodRector
Changes call_user_method()/call_user_method_array() to call_user_func()/call_user_func_array()
-call_user_method($method, $obj, "arg1", "arg2");
+call_user_func(array(&$obj, "method"), "arg1", "arg2");
EmptyListRector
list() cannot be empty
-'list() = $values;'
+'list($unusedGenerated) = $values;'
EregToPregMatchRector
Changes ereg*() to preg*() calls
-ereg("hi")
+preg_match("#hi#");
ExceptionHandlerTypehintRector
Changes property @var
annotations from annotation to type.
-function handler(Exception $exception) { ... }
+function handler(Throwable $exception) { ... }
set_exception_handler('handler');
IfToSpaceshipRector
Changes if/else to spaceship <=> where useful
class SomeClass
{
public function run()
{
usort($languages, function ($a, $b) {
- if ($a[0] === $b[0]) {
- return 0;
- }
-
- return ($a[0] < $b[0]) ? 1 : -1;
+ return $b[0] <=> $a[0];
});
}
}
ListSplitStringRector
list() cannot split string directly anymore, use str_split()
-list($foo) = "string";
+list($foo) = str_split("string");
ListSwapArrayOrderRector
list() assigns variables in reverse order - relevant in array assign
-list($a[], $a[]) = [1, 2];
+list($a[], $a[]) = array_reverse([1, 2]);
MultiDirnameRector
Changes multiple dirname() calls to one with nesting level
-dirname(dirname($path));
+dirname($path, 2);
NonVariableToVariableOnFunctionCallRector
Transform non variable like arguments to variable where a function or method expects an argument passed by reference
-reset(a());
+$a = a(); reset($a);
Php4ConstructorRector
Changes PHP 4 style constructor to __construct.
class SomeClass
{
- public function SomeClass()
+ public function __construct()
{
}
}
RandomFunctionRector
Changes rand, srand and getrandmax by new mt_* alternatives.
-rand();
+mt_rand();
ReduceMultipleDefaultSwitchRector
Remove first default switch, that is ignored
switch ($expr) {
default:
- echo "Hello World";
-
- default:
echo "Goodbye Moon!";
break;
}
RenameMktimeWithoutArgsToTimeRector
class SomeClass
{
public function run()
{
$time = mktime(1, 2, 3);
- $nextTime = mktime();
+ $nextTime = time();
}
}
StaticCallOnNonStaticToInstanceCallRector
Changes static call to instance call, where not useful
class Something
{
public function doWork()
{
}
}
class Another
{
public function run()
{
- return Something::doWork();
+ return (new Something)->doWork();
}
}
TernaryToNullCoalescingRector
Changes unneeded null check to ?? operator
-$value === null ? 10 : $value;
+$value ?? 10;
-isset($value) ? $value : 10;
+$value ?? 10;
TernaryToSpaceshipRector
Use <=> spaceship instead of ternary with same effect
function order_func($a, $b) {
- return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
+ return $a <=> $b;
}
ThisCallOnStaticMethodToStaticCallRector
Changes $this->call() to static method to static call
class SomeClass
{
public static function run()
{
- $this->eat();
+ self::eat();
}
public static function eat()
{
}
}
Php71
AssignArrayToStringRector
String cannot be turned into array by assignment anymore
-$string = '';
+$string = [];
$string[] = 1;
BinaryOpBetweenNumberAndStringRector
Change binary operation between some number + string to PHP 7.1 compatible version
class SomeClass
{
public function run()
{
- $value = 5 + '';
- $value = 5.0 + 'hi';
+ $value = 5 + 0;
+ $value = 5.0 + 0
}
}
CountOnNullRector
Changes count() on null to safe ternary check
$values = null;
-$count = count($values);
+$count = is_array($values) || $values instanceof Countable ? count($values) : 0;
IsIterableRector
Changes is_array + Traversable check to is_iterable
-is_array($foo) || $foo instanceof Traversable;
+is_iterable($foo);
ListToArrayDestructRector
Remove & from new &X
class SomeClass
{
public function run()
{
- list($id1, $name1) = $data;
+ [$id1, $name1] = $data;
- foreach ($data as list($id, $name)) {
+ foreach ($data as [$id, $name]) {
}
}
}
MultiExceptionCatchRector
Changes multi catch of same exception to single one | separated.
try {
// Some code...
-} catch (ExceptionType1 $exception) {
- $sameCode;
-} catch (ExceptionType2 $exception) {
+} catch (ExceptionType1 | ExceptionType2 $exception) {
$sameCode;
}
PublicConstantVisibilityRector
Add explicit public constant visibility.
class SomeClass
{
- const HEY = 'you';
+ public const HEY = 'you';
}
RemoveExtraParametersRector
Remove extra parameters
-strlen("asdf", 1);
+strlen("asdf");
ReservedObjectRector
Changes reserved "Object" name to "Object" where can be configured
-class Object
+class SmartObject
{
}
Php72
BarewordStringRector
Changes unquoted non-existing constants to strings
-var_dump(VAR);
+var_dump("VAR");
CreateFunctionToAnonymousFunctionRector
Use anonymous functions instead of deprecated create_function()
class ClassWithCreateFunction
{
public function run()
{
- $callable = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);");
+ $callable = function($matches) use ($delimiter) {
+ return $delimiter . strtolower($matches[1]);
+ };
}
}
GetClassOnNullRector
Null is no more allowed in get_class()
final class SomeClass
{
public function getItem()
{
$value = null;
- return get_class($value);
+ return $value !== null ? get_class($value) : self::class;
}
}
IsObjectOnIncompleteClassRector
Incomplete class returns inverted bool on is_object()
$incompleteObject = new __PHP_Incomplete_Class;
-$isObject = is_object($incompleteObject);
+$isObject = ! is_object($incompleteObject);
ListEachRector
each() function is deprecated, use key() and current() instead
-list($key, $callback) = each($callbacks);
+$key = key($opt->option);
+$val = current($opt->option);
ParseStrWithResultArgumentRector
Use $result argument in parse_str() function
-parse_str($this->query);
-$data = get_defined_vars();
+parse_str($this->query, $result);
+$data = $result;
StringifyDefineRector
Make first argument of define() string
class SomeClass
{
public function run(int $a)
{
- define(CONSTANT_2, 'value');
+ define('CONSTANT_2', 'value');
define('CONSTANT', 'value');
}
}
StringsAssertNakedRector
String asserts must be passed directly to assert()
function nakedAssert()
{
- assert('true === true');
- assert("true === true");
+ assert(true === true);
+ assert(true === true);
}
UnsetCastRector
Removes (unset) cast
-$different = (unset) $value;
+$different = null;
-$value = (unset) $value;
+unset($value);
WhileEachToForeachRector
each() function is deprecated, use foreach() instead.
-while (list($key, $callback) = each($callbacks)) {
+foreach ($callbacks as $key => $callback) {
// ...
}
-while (list($key) = each($callbacks)) {
+foreach (array_keys($callbacks) as $key) {
// ...
}
Php73
ArrayKeyFirstLastRector
Make use of array_key_first() and array_key_last()
-reset($items);
-$firstKey = key($items);
+$firstKey = array_key_first($items);
-end($items);
-$lastKey = key($items);
+$lastKey = array_key_last($items);
IsCountableRector
Changes is_array + Countable check to is_countable
-is_array($foo) || $foo instanceof Countable;
+is_countable($foo);
JsonThrowOnErrorRector
Adds JSON_THROW_ON_ERROR to json_encode() and json_decode() to throw JsonException on error
-json_encode($content);
-json_decode($json);
+json_encode($content, JSON_THROW_ON_ERROR);
+json_decode($json, null, null, JSON_THROW_ON_ERROR);
RegexDashEscapeRector
Escape - in some cases
-preg_match("#[\w-()]#", 'some text');
+preg_match("#[\w\-()]#", 'some text');
RemoveMissingCompactVariableRector
Remove non-existing vars from compact()
class SomeClass
{
public function run()
{
$value = 'yes';
- compact('value', 'non_existing');
+ compact('value');
}
}
SensitiveConstantNameRector
Changes case insensitive constants to sensitive ones.
define('FOO', 42, true);
var_dump(FOO);
-var_dump(foo);
+var_dump(FOO);
SensitiveDefineRector
Changes case insensitive constants to sensitive ones.
-define('FOO', 42, true);
+define('FOO', 42);
SensitiveHereNowDocRector
Changes heredoc/nowdoc that contains closing word to safe wrapper name
-$value = <<<A
+$value = <<<A_WRAP
A
-A
+A_WRAP
SetcookieRector
Convert setcookie argument to PHP7.3 option array
-setcookie('name', $value, 360);
+setcookie('name', $value, ['expires' => 360]);
-setcookie('name', $name, 0, '', '', true, true);
+setcookie('name', $name, ['expires' => 0, 'path' => '', 'domain' => '', 'secure' => true, 'httponly' => true]);
StringifyStrNeedlesRector
Makes needles explicit strings
$needle = 5;
-$fivePosition = strpos('725', $needle);
+$fivePosition = strpos('725', (string) $needle);
Php74
AddLiteralSeparatorToNumberRector
Add "_" as thousands separator in numbers
class SomeClass
{
public function run()
{
- $int = 1000;
- $float = 1000500.001;
+ $int = 1_000;
+ $float = 1_000_500.001;
}
}
ArrayKeyExistsOnPropertyRector
Change array_key_exists() on property to property_exists()
class SomeClass {
public $value;
}
$someClass = new SomeClass;
-array_key_exists('value', $someClass);
+property_exists($someClass, 'value');
ArraySpreadInsteadOfArrayMergeRector
Change array_merge() to spread operator, except values with possible string key values
class SomeClass
{
public function run($iter1, $iter2)
{
- $values = array_merge(iterator_to_array($iter1), iterator_to_array($iter2));
+ $values = [...$iter1, ...$iter2];
// Or to generalize to all iterables
- $anotherValues = array_merge(
- is_array($iter1) ? $iter1 : iterator_to_array($iter1),
- is_array($iter2) ? $iter2 : iterator_to_array($iter2)
- );
+ $anotherValues = [...$iter1, ...$iter2];
}
}
ChangeReflectionTypeToStringToGetNameRector
Change string calls on ReflectionType
class SomeClass
{
public function go(ReflectionFunction $reflectionFunction)
{
$parameterReflection = $reflectionFunction->getParameters()[0];
- $paramType = (string) $parameterReflection->getType();
+ $paramType = (string) ($parameterReflection->getType() ? $parameterReflection->getType()->getName() : null);
- $stringValue = 'hey' . $reflectionFunction->getReturnType();
+ $stringValue = 'hey' . ($reflectionFunction->getReturnType() ? $reflectionFunction->getReturnType()->getName() : null);
// keep
return $reflectionFunction->getReturnType();
}
}
ClassConstantToSelfClassRector
Change CLASS to self::class
class SomeClass
{
public function callOnMe()
{
- var_dump(__CLASS__);
+ var_dump(self::class);
}
}
ClosureToArrowFunctionRector
Change closure to arrow function
class SomeClass
{
public function run($meetups)
{
- return array_filter($meetups, function (Meetup $meetup) {
- return is_object($meetup);
- });
+ return array_filter($meetups, fn(Meetup $meetup) => is_object($meetup));
}
}
ExportToReflectionFunctionRector
Change export() to ReflectionFunction alternatives
-$reflectionFunction = ReflectionFunction::export('foo');
-$reflectionFunctionAsString = ReflectionFunction::export('foo', true);
+$reflectionFunction = new ReflectionFunction('foo');
+$reflectionFunctionAsString = (string) new ReflectionFunction('foo');
FilterVarToAddSlashesRector
Change filter_var() with slash escaping to addslashes()
$var= "Satya's here!";
-filter_var($var, FILTER_SANITIZE_MAGIC_QUOTES);
+addslashes($var);
GetCalledClassToStaticClassRector
Change CLASS to self::class
class SomeClass
{
public function callOnMe()
{
- var_dump(get_called_class());
+ var_dump(static::class);
}
}
MbStrrposEncodingArgumentPositionRector
Change mb_strrpos() encoding argument position
-mb_strrpos($text, "abc", "UTF-8");
+mb_strrpos($text, "abc", 0, "UTF-8");
NullCoalescingOperatorRector
Use null coalescing operator ??=
$array = [];
-$array['user_id'] = $array['user_id'] ?? 'value';
+$array['user_id'] ??= 'value';
RealToFloatTypeCastRector
Change deprecated (real) to (float)
class SomeClass
{
public function run()
{
- $number = (real) 5;
+ $number = (float) 5;
$number = (float) 5;
$number = (double) 5;
}
}
ReservedFnFunctionRector
Change fn() function name, since it will be reserved keyword
class SomeClass
{
public function run()
{
- function fn($value)
+ function f($value)
{
return $value;
}
- fn(5);
+ f(5);
}
}
TypedPropertyRector
Changes property @var
annotations from annotation to type.
final class SomeClass
{
- /**
- * @var int
- */
- private count;
+ private int count;
}
Php80
UnionTypesRector
Change docs types to union types, where possible (properties are covered by TypedPropertiesRector)
class SomeClass {
/**
* @param array|int $number
* @return bool|float
*/
- public function go($number)
+ public function go(array|int $number): bool|float
{
}
}
PhpDeglobalize
ChangeGlobalVariablesToPropertiesRector
Change global $variables to private properties
class SomeClass
{
+ private $variable;
public function go()
{
- global $variable;
- $variable = 5;
+ $this->variable = 5;
}
public function run()
{
- global $variable;
- var_dump($variable);
+ var_dump($this->variable);
}
}
PhpSpecToPHPUnit
AddMockPropertiesRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
MockVariableToPropertyFetchRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecClassToPHPUnitClassRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecMethodToPHPUnitMethodRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecMocksToPHPUnitMocksRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
PhpSpecPromisesToPHPUnitAssertRector
Migrate PhpSpec behavior to PHPUnit test
namespace spec\SomeNamespaceForThisTest;
-use PhpSpec\ObjectBehavior;
-
class OrderSpec extends ObjectBehavior
{
- public function let(OrderFactory $factory, ShippingMethod $shippingMethod)
+ /**
+ * @var \SomeNamespaceForThisTest\Order
+ */
+ private $order;
+ protected function setUp()
{
- $factory->createShippingMethodFor(Argument::any())->shouldBeCalled()->willReturn($shippingMethod);
+ /** @var OrderFactory|\PHPUnit\Framework\MockObject\MockObject $factory */
+ $factory = $this->createMock(OrderFactory::class);
+
+ /** @var ShippingMethod|\PHPUnit\Framework\MockObject\MockObject $shippingMethod */
+ $shippingMethod = $this->createMock(ShippingMethod::class);
+
+ $factory->expects($this->once())->method('createShippingMethodFor')->willReturn($shippingMethod);
}
}
RenameSpecFileToTestFileRector
Rename "*Spec.php" file to "*Test.php" file
Polyfill
UnwrapFutureCompatibleIfFunctionExistsRector
Remove functions exists if with else for always existing
class SomeClass
{
public function run()
{
// session locking trough other addons
- if (function_exists('session_abort')) {
- session_abort();
- } else {
- session_write_close();
- }
+ session_abort();
}
}
UnwrapFutureCompatibleIfPhpVersionRector
Remove php version checks if they are passed
// current PHP: 7.2
-if (version_compare(PHP_VERSION, '7.2', '<')) {
- return 'is PHP 7.1-';
-} else {
- return 'is PHP 7.2+';
-}
+return 'is PHP 7.2+';
Refactoring
MoveAndRenameClassRector
Move class to respect new location with respect to PSR-4 + follow up with class rename
MoveAndRenameNamespaceRector
Move namespace to new location with respect to PSR-4 + follow up with files in the namespace move
RemovingStatic
NewUniqueObjectToEntityFactoryRector
Convert new X to new factories
-<?php
-
class SomeClass
{
+ public function __construct(AnotherClassFactory $anotherClassFactory)
+ {
+ $this->anotherClassFactory = $anotherClassFactory;
+ }
+
public function run()
{
- return new AnotherClass;
+ return $this->anotherClassFactory->create();
}
}
class AnotherClass
{
public function someFun()
{
return StaticClass::staticMethod();
}
}
PHPUnitStaticToKernelTestCaseGetRector
Convert static calls in PHPUnit test cases, to get() from the container of KernelTestCase
services:
Rector\RemovingStatic\Rector\Class_\PHPUnitStaticToKernelTestCaseGetRector:
staticClassTypes:
- EntityFactory
↓
-<?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');
}
}
PassFactoryToUniqueObjectRector
Convert new X/Static::call() to factories in entities, pass them via constructor to each other
services:
Rector\RemovingStatic\Rector\Class_\PassFactoryToUniqueObjectRector:
typesToServices:
- StaticClass
↓
-<?php
-
class SomeClass
{
+ public function __construct(AnotherClassFactory $anotherClassFactory)
+ {
+ $this->anotherClassFactory = $anotherClassFactory;
+ }
+
public function run()
{
- return new AnotherClass;
+ return $this->anotherClassFactory->create();
}
}
class AnotherClass
{
+ public function __construct(StaticClass $staticClass)
+ {
+ $this->staticClass = $staticClass;
+ }
+
public function someFun()
{
- return StaticClass::staticMethod();
+ return $this->staticClass->staticMethod();
+ }
+}
+
+final class AnotherClassFactory
+{
+ /**
+ * @var StaticClass
+ */
+ private $staticClass;
+
+ public function __construct(StaticClass $staticClass)
+ {
+ $this->staticClass = $staticClass;
+ }
+
+ public function create(): AnotherClass
+ {
+ return new AnotherClass($this->staticClass);
}
}
StaticTypeToSetterInjectionRector
Changes types to setter injection
services:
Rector\RemovingStatic\Rector\Class_\StaticTypeToSetterInjectionRector:
$staticTypes:
- SomeStaticClass
↓
<?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();
}
}
Renaming
RenameAnnotationRector
Turns defined annotations above properties and methods to their new values.
services:
Rector\Renaming\Rector\Annotation\RenameAnnotationRector:
$classToAnnotationMap:
PHPUnit\Framework\TestCase:
test: scenario
↓
class SomeTest extends PHPUnit\Framework\TestCase
{
/**
- * @test
+ * @scenario
*/
public function someMethod()
{
}
}
RenameClassConstantRector
Replaces defined class constants in their calls.
services:
Rector\Renaming\Rector\Constant\RenameClassConstantRector:
SomeClass:
OLD_CONSTANT: NEW_CONSTANT
OTHER_OLD_CONSTANT: 'DifferentClass::NEW_CONSTANT'
↓
-$value = SomeClass::OLD_CONSTANT;
-$value = SomeClass::OTHER_OLD_CONSTANT;
+$value = SomeClass::NEW_CONSTANT;
+$value = DifferentClass::NEW_CONSTANT;
RenameClassRector
Replaces defined classes by new ones.
services:
Rector\Renaming\Rector\Class_\RenameClassRector:
$oldToNewClasses:
App\SomeOldClass: App\SomeNewClass
↓
namespace App;
-use SomeOldClass;
+use SomeNewClass;
-function someFunction(SomeOldClass $someOldClass): SomeOldClass
+function someFunction(SomeNewClass $someOldClass): SomeNewClass
{
- if ($someOldClass instanceof SomeOldClass) {
- return new SomeOldClass;
+ if ($someOldClass instanceof SomeNewClass) {
+ return new SomeNewClass;
}
}
RenameConstantRector
Replace constant by new ones
final class SomeClass
{
public function run()
{
- return MYSQL_ASSOC;
+ return MYSQLI_ASSOC;
}
}
RenameFuncCallToStaticCallRector
Rename func call to static call
services:
Rector\Renaming\Rector\FuncCall\RenameFuncCallToStaticCallRector:
$functionsToStaticCalls:
strPee:
- Strings
- strPaa
↓
class SomeClass
{
public function run()
{
- strPee('...');
+ \Strings::strPaa('...');
}
}
RenameFunctionRector
Turns defined function call new one.
services:
Rector\Renaming\Rector\Function_\RenameFunctionRector:
$oldFunctionToNewFunction:
view: Laravel\Templating\render
↓
-view("...", []);
+Laravel\Templating\render("...", []);
RenameMethodCallRector
Turns method call names to new ones.
services:
Rector\Renaming\Rector\MethodCall\RenameMethodCallRector:
SomeExampleClass:
oldMethod: newMethod
↓
$someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();
RenameMethodRector
Turns method names to new ones.
services:
Rector\Renaming\Rector\MethodCall\RenameMethodRector:
SomeExampleClass:
$oldToNewMethodsByClass:
oldMethod: newMethod
↓
$someObject = new SomeExampleClass;
-$someObject->oldMethod();
+$someObject->newMethod();
RenameNamespaceRector
Replaces old namespace by new one.
services:
Rector\Renaming\Rector\Namespace_\RenameNamespaceRector:
$oldToNewNamespaces:
SomeOldNamespace: SomeNewNamespace
↓
-$someObject = new SomeOldNamespace\SomeClass;
+$someObject = new SomeNewNamespace\SomeClass;
RenameStaticMethodRector
Turns method names to new ones.
services:
Rector\Renaming\Rector\MethodCall\RenameStaticMethodRector:
SomeClass:
oldMethod:
- AnotherExampleClass
- newStaticMethod
↓
-SomeClass::oldStaticMethod();
+AnotherExampleClass::newStaticMethod();
services:
Rector\Renaming\Rector\MethodCall\RenameStaticMethodRector:
$oldToNewMethodByClasses:
SomeClass:
oldMethod: newStaticMethod
↓
-SomeClass::oldStaticMethod();
+SomeClass::newStaticMethod();
Restoration
CompleteImportForPartialAnnotationRector
In case you have accidentally removed use imports but code still contains partial use statements, this will save you
services:
Rector\Restoration\Rector\Namespace_\CompleteImportForPartialAnnotationRector:
$useImportToRestore:
-
- Doctrine\ORM\Mapping
- ORM
↓
+use Doctrine\ORM\Mapping as ORM;
+
class SomeClass
{
/**
* @ORM\Id
*/
public $id;
}
MissingClassConstantReferenceToStringRector
- class:
Rector\Restoration\Rector\ClassConstFetch\MissingClassConstantReferenceToStringRector
- test fixtures
Convert missing class reference to string
class SomeClass
{
public function run()
{
- return NonExistingClass::class;
+ return 'NonExistingClass';
}
}
SOLID
ChangeIfElseValueAssignToEarlyReturnRector
Change if/else value to early return
class SomeClass
{
public function run()
{
if ($this->hasDocBlock($tokens, $index)) {
- $docToken = $tokens[$this->getDocBlockIndex($tokens, $index)];
- } else {
- $docToken = null;
+ return $tokens[$this->getDocBlockIndex($tokens, $index)];
}
-
- return $docToken;
+ return null;
}
}
ChangeNestedForeachIfsToEarlyContinueRector
Change nested ifs to foreach with continue
class SomeClass
{
public function run()
{
$items = [];
foreach ($values as $value) {
- if ($value === 5) {
- if ($value2 === 10) {
- $items[] = 'maybe';
- }
+ if ($value !== 5) {
+ continue;
}
+ if ($value2 !== 10) {
+ continue;
+ }
+
+ $items[] = 'maybe';
}
}
}
ChangeNestedIfsToEarlyReturnRector
Change nested ifs to early return
class SomeClass
{
public function run()
{
- if ($value === 5) {
- if ($value2 === 10) {
- return 'yes';
- }
+ if ($value !== 5) {
+ return 'no';
+ }
+
+ if ($value2 === 10) {
+ return 'yes';
}
return 'no';
}
}
ChangeReadOnlyPropertyWithDefaultValueToConstantRector
- class:
Rector\SOLID\Rector\Property\ChangeReadOnlyPropertyWithDefaultValueToConstantRector
- test fixtures
Change property with read only status with default value to constant
class SomeClass
{
/**
* @var string[]
*/
- private $magicMethods = [
+ private const MAGIC_METHODS = [
'__toString',
'__wakeup',
];
public function run()
{
- foreach ($this->magicMethods as $magicMethod) {
+ foreach (self::MAGIC_METHODS as $magicMethod) {
echo $magicMethod;
}
}
}
ChangeReadOnlyVariableWithDefaultValueToConstantRector
- class:
Rector\SOLID\Rector\ClassMethod\ChangeReadOnlyVariableWithDefaultValueToConstantRector
- test fixtures
Change variable with read only status with default value to constant
class SomeClass
{
+ /**
+ * @var string[]
+ */
+ private const REPLACEMENTS = [
+ 'PHPUnit\Framework\TestCase\Notice' => 'expectNotice',
+ 'PHPUnit\Framework\TestCase\Deprecated' => 'expectDeprecation',
+ ];
+
public function run()
{
- $replacements = [
- 'PHPUnit\Framework\TestCase\Notice' => 'expectNotice',
- 'PHPUnit\Framework\TestCase\Deprecated' => 'expectDeprecation',
- ];
-
- foreach ($replacements as $class => $method) {
+ foreach (self::REPLACEMENTS as $class => $method) {
}
}
}
FinalizeClassesWithoutChildrenRector
Finalize every class that has no children
-class FirstClass
+final class FirstClass
{
}
class SecondClass
{
}
-class ThirdClass extends SecondClass
+final class ThirdClass extends SecondClass
{
}
MakeUnusedClassesWithChildrenAbstractRector
Classes that have no children nor are used, should have abstract
class SomeClass extends PossibleAbstractClass
{
}
-class PossibleAbstractClass
+abstract class PossibleAbstractClass
{
}
PrivatizeLocalClassConstantRector
Finalize every class constant that is used only locally
class ClassWithConstantUsedOnlyHere
{
- const LOCAL_ONLY = true;
+ private const LOCAL_ONLY = true;
public function isLocalOnly()
{
return self::LOCAL_ONLY;
}
}
RemoveAlwaysElseRector
Split if statement, when if condition always break execution flow
class SomeClass
{
public function run($value)
{
if ($value) {
throw new \InvalidStateException;
- } else {
- return 10;
}
+
+ return 10;
}
}
UseInterfaceOverImplementationInConstructorRector
- class:
Rector\SOLID\Rector\ClassMethod\UseInterfaceOverImplementationInConstructorRector
- test fixtures
Use interface instead of specific class
class SomeClass
{
- public function __construct(SomeImplementation $someImplementation)
+ public function __construct(SomeInterface $someImplementation)
{
}
}
class SomeImplementation implements SomeInterface
{
}
interface SomeInterface
{
}
Sensio
TemplateAnnotationRector
Turns @Template
annotation to explicit method call in Controller of FrameworkExtraBundle in Symfony
-/**
- * @Template()
- */
public function indexAction()
{
+ return $this->render("index.html.twig");
}
Shopware
ReplaceEnlightResponseWithSymfonyResponseRector
- class:
Rector\Shopware\Rector\MethodCall\ReplaceEnlightResponseWithSymfonyResponseRector
- test fixtures
Replace Enlight Response methods with Symfony Response methods
class FrontendController extends \Enlight_Controller_Action
{
public function run()
{
- $this->Response()->setHeader('Foo', 'Yea');
+ $this->Response()->headers->set('Foo', 'Yea');
}
}
ShopRegistrationServiceRector
Replace $shop->registerResources() with ShopRegistrationService
class SomeClass
{
public function run()
{
$shop = new \Shopware\Models\Shop\Shop();
- $shop->registerResources();
+ Shopware()->Container()->get('shopware.components.shop_registration_service')->registerShop($shop);
}
}
ShopwareVersionConstsRector
Use version from di parameter
class SomeClass
{
public function run()
{
- echo \Shopware::VERSION;
+ echo Shopware()->Container()->getParameter('shopware.release.version');
}
}
Silverstripe
ConstantToStaticCallRector
Turns defined constant to static method call.
-SS_DATABASE_NAME;
+Environment::getEnv("SS_DATABASE_NAME");
DefineConstantToStaticCallRector
Turns defined function call to static method call.
-defined("SS_DATABASE_NAME");
+Environment::getEnv("SS_DATABASE_NAME");
StrictCodeQuality
VarInlineAnnotationToAssertRector
Turn @var inline checks above code to assert() of hte type
class SomeClass
{
public function run()
{
/** @var SpecificClass $value */
+ assert($value instanceof SpecificClass);
$value->call();
}
}
Sylius
ReplaceCreateMethodWithoutReviewerRector
Turns createForSubjectWithReviewer()
with null review to standalone method in Sylius
-$this->createForSubjectWithReviewer($subject, null)
+$this->createForSubject($subject)
Symfony
ActionSuffixRemoverRector
Removes Action suffixes from methods in Symfony Controllers
class SomeController
{
- public function indexAction()
+ public function index()
{
}
}
AddFlashRector
Turns long flash adding to short helper method in Controller in Symfony
class SomeController extends Controller
{
public function some(Request $request)
{
- $request->getSession()->getFlashBag()->add("success", "something");
+ $this->addFlash("success", "something");
}
}
CascadeValidationFormBuilderRector
Change "cascade_validation" option to specific node attribute
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();
}
protected function createFormBuilder()
{
return new FormBuilder();
}
}
ConsoleExceptionToErrorEventConstantRector
Turns old event name with EXCEPTION to ERROR constant in Console in Symfony
-"console.exception"
+Symfony\Component\Console\ConsoleEvents::ERROR
-Symfony\Component\Console\ConsoleEvents::EXCEPTION
+Symfony\Component\Console\ConsoleEvents::ERROR
ConsoleExecuteReturnIntRector
Returns int from Command::execute command
class SomeCommand extends Command
{
- public function execute(InputInterface $input, OutputInterface $output)
+ public function index(InputInterface $input, OutputInterface $output): int
{
- return null;
+ return 0;
}
}
ConstraintUrlOptionRector
Turns true value to Url::CHECK_DNS_TYPE_ANY
in Validator in Symfony.
-$constraint = new Url(["checkDNS" => true]);
+$constraint = new Url(["checkDNS" => Url::CHECK_DNS_TYPE_ANY]);
ContainerBuilderCompileEnvArgumentRector
- class:
Rector\Symfony\Rector\DependencyInjection\ContainerBuilderCompileEnvArgumentRector
- test fixtures
Turns old default value to parameter in ContinerBuilder->build() method in DI in Symfony
-$containerBuilder = new Symfony\Component\DependencyInjection\ContainerBuilder(); $containerBuilder->compile();
+$containerBuilder = new Symfony\Component\DependencyInjection\ContainerBuilder(); $containerBuilder->compile(true);
ContainerGetToConstructorInjectionRector
Turns fetching of dependencies via $container->get()
in ContainerAware to constructor injection in Command and Controller in Symfony
-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;
}
}
FormIsValidRector
Adds $form->isSubmitted()
validation to all $form->isValid()
calls in Form in Symfony
-if ($form->isValid()) {
+if ($form->isSubmitted() && $form->isValid()) {
}
FormTypeGetParentRector
Turns string Form Type references to their CONSTANT alternatives in getParent()
and getExtendedType()
methods in Form in Symfony
-function getParent() { return "collection"; }
+function getParent() { return CollectionType::class; }
-function getExtendedType() { return "collection"; }
+function getExtendedType() { return CollectionType::class; }
FormTypeInstanceToClassConstRector
Changes createForm(new FormType), add(new FormType) to ones with "FormType::class"
class SomeController
{
public function action()
{
- $form = $this->createForm(new TeamType, $entity, [
+ $form = $this->createForm(TeamType::class, $entity, [
'action' => $this->generateUrl('teams_update', ['id' => $entity->getId()]),
'method' => 'PUT',
]);
}
}
GetParameterToConstructorInjectionRector
Turns fetching of parameters via getParameter()
in ContainerAware to constructor injection in Command and Controller in Symfony
-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;
}
}
GetRequestRector
Turns fetching of dependencies via $this->get()
to constructor injection in Command and Controller in Symfony
+use Symfony\Component\HttpFoundation\Request;
+
class SomeController
{
- public function someAction()
+ public function someAction(Request $request)
{
- $this->getRequest()->...();
+ $request->...();
}
}
GetToConstructorInjectionRector
Turns fetching of dependencies via $this->get()
to constructor injection in Command and Controller in Symfony
-class MyCommand extends ContainerAwareCommand
+class MyCommand extends Command
{
+ public function __construct(SomeService $someService)
+ {
+ $this->someService = $someService;
+ }
+
public function someMethod()
{
- // ...
- $this->get('some_service');
+ $this->someService;
}
}
MakeCommandLazyRector
Make Symfony commands lazy
use Symfony\Component\Console\Command\Command
class SunshineCommand extends Command
{
+ protected static $defaultName = 'sunshine';
public function configure()
{
- $this->setName('sunshine');
}
}
MakeDispatchFirstArgumentEventRector
Make event object a first argument of dispatch() method, event name as second
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class SomeClass
{
public function run(EventDispatcherInterface $eventDispatcher)
{
- $eventDispatcher->dispatch('event_name', new Event());
+ $eventDispatcher->dispatch(new Event(), 'event_name');
}
}
MergeMethodAnnotationToRouteAnnotationRector
Merge removed @Method annotation to @Route one
-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)
{
}
}
OptionNameRector
Turns old option names to new ones in FormTypes in Form in Symfony
$builder = new FormBuilder;
-$builder->add("...", ["precision" => "...", "virtual" => "..."];
+$builder->add("...", ["scale" => "...", "inherit_data" => "..."];
ParseFileRector
session > use_strict_mode is true by default and can be removed
-session > use_strict_mode: true
+session:
ProcessBuilderGetProcessRector
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.
$processBuilder = new Symfony\Component\Process\ProcessBuilder;
-$process = $processBuilder->getProcess();
-$commamdLine = $processBuilder->getProcess()->getCommandLine();
+$process = $processBuilder;
+$commamdLine = $processBuilder->getCommandLine();
ProcessBuilderInstanceRector
Turns ProcessBuilder::instance()
to new ProcessBuilder in Process in Symfony. Part of multi-step Rector.
-$processBuilder = Symfony\Component\Process\ProcessBuilder::instance($args);
+$processBuilder = new Symfony\Component\Process\ProcessBuilder($args);
ReadOnlyOptionToAttributeRector
Change "read_only" option in form to attribute
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]]);
}
RedirectToRouteRector
Turns redirect to route to short helper method in Controller in Symfony
-$this->redirect($this->generateUrl("homepage"));
+$this->redirectToRoute("homepage");
ResponseStatusCodeRector
Turns status code numbers to constants
class SomeController
{
public function index()
{
$response = new \Symfony\Component\HttpFoundation\Response();
- $response->setStatusCode(200);
+ $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
- if ($response->getStatusCode() === 200) {}
+ if ($response->getStatusCode() === \Symfony\Component\HttpFoundation\Response::HTTP_OK) {}
}
}
RootNodeTreeBuilderRector
Changes Process string argument to an array
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();
SimplifyWebTestCaseAssertionsRector
Simplify use of assertions in WebTestCase
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');
}
}
StringFormTypeToClassRector
Turns string Form Type references to their CONSTANT alternatives in FormTypes in Form in Symfony
$formBuilder = new Symfony\Component\Form\FormBuilder;
-$formBuilder->add('name', 'form.type.text');
+$formBuilder->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class);
StringToArrayArgumentProcessRector
Changes Process string argument to an array
use Symfony\Component\Process\Process;
-$process = new Process('ls -l');
+$process = new Process(['ls', '-l']);
VarDumperTestTraitMethodArgsRector
Adds a new $filter
argument in VarDumperTestTrait->assertDumpEquals()
and VarDumperTestTrait->assertDumpMatchesFormat()
in Validator in Symfony.
-$varDumperTestTrait->assertDumpEquals($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpEquals($dump, $data, $filter = 0, $message = "");
-$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $message = "");
+$varDumperTestTrait->assertDumpMatchesFormat($dump, $data, $filter = 0, $message = "");
SymfonyCodeQuality
EventListenerToEventSubscriberRector
Change Symfony Event listener class to Event Subscriber based on configuration in service.yaml file
<?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' }
+}
SymfonyPHPUnit
SelfContainerGetMethodCallFromTestToSetUpMethodRector
- class:
Rector\SymfonyPHPUnit\Rector\Class_\SelfContainerGetMethodCallFromTestToSetUpMethodRector
- test fixtures
Move self::$container service fetching from test methods up to setUp method
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();
}
}
Twig
SimpleFunctionAndFilterRector
Changes Twig_Function_Method to Twig_SimpleFunction calls in Twig_Extension.
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']),
];
}
}
TypeDeclaration
AddArrayParamDocTypeRector
Adds @param annotation to array parameters inferred from the rest of the code
class SomeClass
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @param int[] $values
+ */
public function __construct(array $values)
{
$this->values = $values;
}
}
AddArrayReturnDocTypeRector
Adds @return annotation to array parameters inferred from the rest of the code
class SomeClass
{
/**
* @var int[]
*/
private $values;
+ /**
+ * @return int[]
+ */
public function getValues(): array
{
return $this->values;
}
}
AddClosureReturnTypeRector
Add known return type to functions
class SomeClass
{
public function run($meetups)
{
- return array_filter($meetups, function (Meetup $meetup) {
+ return array_filter($meetups, function (Meetup $meetup): bool {
return is_object($meetup);
});
}
}
AddMethodCallBasedParamTypeRector
Change param type of passed getId() to UuidInterface type declaration
class SomeClass
{
- public function getById($id)
+ public function getById(\Ramsey\Uuid\UuidInterface $id)
{
}
}
class CallerClass
{
public function run()
{
$building = new Building();
$someClass = new SomeClass();
$someClass->getById($building->getId());
}
}
AddParamTypeDeclarationRector
Add param types where needed
services:
Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector:
$typehintForParameterByMethodByClass:
SomeClass:
process:
- string
↓
class SomeClass
{
- public function process($name)
+ public function process(string $name)
{
}
}
CompleteVarDocTypePropertyRector
Complete property @var
annotations or correct the old ones
final class SomeClass
{
+ /**
+ * @var EventDispatcher
+ */
private $eventDispatcher;
public function __construct(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
}
ParamTypeDeclarationRector
Change @param types to type declarations if not a BC-break
<?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)
{
}
}
PropertyTypeDeclarationRector
Add @var to properties that are missing it
ReturnTypeDeclarationRector
Change @return types and type from static analysis to type declarations if not a BC-break
<?php
class SomeClass
{
/**
* @return int
*/
- public function getCount()
+ public function getCount(): int
{
}
}
ZendToSymfony
ChangeZendControllerClassToSymfonyControllerClassRector
- class:
Rector\ZendToSymfony\Rector\Class_\ChangeZendControllerClassToSymfonyControllerClassRector
- test fixtures
Change Zend 1 controller to Symfony 4 controller
-class SomeAction extends Zend_Controller_Action
+final class SomeAction extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
}
GetParamToClassMethodParameterAndRouteRector
- class:
Rector\ZendToSymfony\Rector\ClassMethod\GetParamToClassMethodParameterAndRouteRector
- test fixtures
Change $this->getParam() calls to action method arguments + Sdd symfony @Route
-public function someAction()
+public function someAction($id)
{
- $id = $this->getParam('id');
}
RedirectorToRedirectToUrlRector
Change $redirector helper to Symfony\Controller call redirect()
public function someAction()
{
$redirector = $this->_helper->redirector;
- $redirector->goToUrl('abc');
+ $this->redirect('abc');
}
RemoveAutoloadingIncludeRector
Remove include/require statements, that supply autoloading (PSR-4 composer autolaod is going to be used instead)
-include 'SomeFile.php';
-require_once 'AnotherFile.php';
-
$values = require_once 'values.txt';
ThisHelperToServiceMethodCallRector
Change magic $this->_helper->calls() to constructor injection of helper services
class SomeController
{
/**
* @var Zend_Controller_Action_HelperBroker
*/
private $_helper;
+
+ /**
+ * @var Zend_Controller_Action_Helper_OnlinePayment
+ */
+ private $onlinePaymentHelper;
+ public function __construct(Zend_Controller_Action_Helper_OnlinePayment $onlinePaymentHelper)
+ {
+ $this->onlinePaymentHelper = onlinePaymentHelper;
+ }
+
public function someAction()
{
- $this->_helper->onlinePayment(1000);
-
- $this->_helper->onlinePayment()->isPaid();
+ $this->onlinePaymentHelper->direct(1000);
+
+ $this->onlinePaymentHelper->direct()->isPaid();
}
}
ThisRequestToRequestParameterRector
Change $this->_request in action method to $request parameter
-public function someAction()
+public function someAction(\Symfony\Component\HttpFoundation\Request $request)
{
- $isGet = $this->_request->isGet();
+ $isGet = $request->isGet();
}
ThisViewToThisRenderResponseRector
Change $this->_view->assign = 5; to $this->render("...", $templateData);
public function someAction()
{
- $this->_view->value = 5;
+ $templateData = [];
+ $templateData['value']; = 5;
+
+ return $this->render("...", $templateData);
}
General
Core
ActionInjectionToConstructorInjectionRector
- class:
Rector\Core\Rector\Architecture\DependencyInjection\ActionInjectionToConstructorInjectionRector
- test fixtures
Turns action injection in Controllers to constructor injection
final class SomeController
{
- public function default(ProductRepository $productRepository)
+ /**
+ * @var ProductRepository
+ */
+ private $productRepository;
+ public function __construct(ProductRepository $productRepository)
{
- $products = $productRepository->fetchAll();
+ $this->productRepository = $productRepository;
+ }
+
+ public function default()
+ {
+ $products = $this->productRepository->fetchAll();
}
}
AddInterfaceByTraitRector
Add interface by used trait
services:
Rector\Core\Rector\Class_\AddInterfaceByTraitRector:
$interfaceByTrait:
SomeTrait: SomeInterface
↓
-class SomeClass
+class SomeClass implements SomeInterface
{
use SomeTrait;
}
AddMethodParentCallRector
Add method parent call, in case new parent method is added
class SunshineCommand extends ParentClassWithNewConstructor
{
public function __construct()
{
$value = 5;
+
+ parent::__construct();
}
}
AddReturnTypeDeclarationRector
Changes defined return typehint of method and class.
services:
Rector\Core\Rector\ClassMethod\AddReturnTypeDeclarationRector:
$typehintForMethodByClass:
SomeClass:
getData: array
↓
class SomeClass
{
- public getData()
+ public getData(): array
{
}
}
AnnotatedPropertyInjectToConstructorInjectionRector
- class:
Rector\Core\Rector\Architecture\DependencyInjection\AnnotatedPropertyInjectToConstructorInjectionRector
- test fixtures
Turns non-private properties with @annotation
to private properties and constructor injection
/**
* @var SomeService
- * @inject
*/
-public $someService;
+private $someService;
+
+public function __construct(SomeService $someService)
+{
+ $this->someService = $someService;
+}
ArgumentAdderRector
This Rector adds new default arguments in calls of defined methods and class types.
services:
Rector\Core\Rector\Argument\ArgumentAdderRector:
$positionWithDefaultValueByMethodNamesByClassTypes:
SomeExampleClass:
someMethod:
-
name: someArgument
default_value: 'true'
type: SomeType
↓
$someObject = new SomeExampleClass;
-$someObject->someMethod();
+$someObject->someMethod(true);
services:
Rector\Core\Rector\Argument\ArgumentAdderRector:
$positionWithDefaultValueByMethodNamesByClassTypes:
SomeExampleClass:
someMethod:
-
name: someArgument
default_value: 'true'
type: SomeType
↓
class MyCustomClass extends SomeExampleClass
{
- public function someMethod()
+ public function someMethod($value = true)
{
}
}
ArgumentDefaultValueReplacerRector
Replaces defined map of arguments in defined methods and their calls.
services:
Rector\Core\Rector\Argument\ArgumentDefaultValueReplacerRector:
SomeExampleClass:
someMethod:
-
-
before: 'SomeClass::OLD_CONSTANT'
after: 'false'
↓
$someObject = new SomeClass;
-$someObject->someMethod(SomeClass::OLD_CONSTANT);
+$someObject->someMethod(false);'
ArgumentRemoverRector
Removes defined arguments in defined methods and their calls.
services:
Rector\Core\Rector\Argument\ArgumentRemoverRector:
ExampleClass:
someMethod:
-
value: 'true'
↓
$someObject = new SomeClass;
-$someObject->someMethod(true);
+$someObject->someMethod();'
ChangeConstantVisibilityRector
Change visibility of constant from parent class.
services:
Rector\Core\Rector\Visibility\ChangeConstantVisibilityRector:
ParentObject:
SOME_CONSTANT: protected
↓
class FrameworkClass
{
protected const SOME_CONSTANT = 1;
}
class MyClass extends FrameworkClass
{
- public const SOME_CONSTANT = 1;
+ protected const SOME_CONSTANT = 1;
}
ChangeMethodVisibilityRector
Change visibility of method from parent class.
services:
Rector\Core\Rector\Visibility\ChangeMethodVisibilityRector:
$methodToVisibilityByClass:
FrameworkClass:
someMethod: protected
↓
class FrameworkClass
{
protected someMethod()
{
}
}
class MyClass extends FrameworkClass
{
- public someMethod()
+ protected someMethod()
{
}
}
ChangePropertyVisibilityRector
Change visibility of property from parent class.
services:
Rector\Core\Rector\Visibility\ChangePropertyVisibilityRector:
FrameworkClass:
someProperty: protected
↓
class FrameworkClass
{
protected $someProperty;
}
class MyClass extends FrameworkClass
{
- public $someProperty;
+ protected $someProperty;
}
FluentReplaceRector
Turns fluent interface calls to classic ones.
services:
Rector\Core\Rector\MethodBody\FluentReplaceRector:
$classesToDefluent:
- SomeExampleClass
↓
$someClass = new SomeClass();
-$someClass->someFunction()
- ->otherFunction();
+$someClass->someFunction();
+$someClass->otherFunction();
FunctionToMethodCallRector
Turns defined function calls to local method calls.
services:
Rector\Core\Rector\Function_\FunctionToMethodCallRector:
view:
- this
- render
↓
-view("...", []);
+$this->render("...", []);
FunctionToNewRector
Change configured function calls to new Instance
class SomeClass
{
public function run()
{
- $array = collection([]);
+ $array = new \Collection([]);
}
}
FunctionToStaticCallRector
Turns defined function call to static method call.
services:
Rector\Core\Rector\Function_\FunctionToStaticCallRector:
view:
- SomeStaticClass
- render
↓
-view("...", []);
+SomeClass::render("...", []);
GetAndSetToMethodCallRector
Turns defined __get
/__set
to specific method calls.
services:
Rector\Core\Rector\MagicDisclosure\GetAndSetToMethodCallRector:
SomeContainer:
set: addService
↓
$container = new SomeContainer;
-$container->someService = $someService;
+$container->setService("someService", $someService);
services:
Rector\Core\Rector\MagicDisclosure\GetAndSetToMethodCallRector:
$typeToMethodCalls:
SomeContainer:
get: getService
↓
$container = new SomeContainer;
-$someService = $container->someService;
+$someService = $container->getService("someService");
InjectAnnotationClassRector
Changes properties with specified annotations class to constructor injection
services:
Rector\Core\Rector\Property\InjectAnnotationClassRector:
$annotationClasses:
- DI\Annotation\Inject
- JMS\DiExtraBundle\Annotation\Inject
↓
use JMS\DiExtraBundle\Annotation as DI;
class SomeController
{
/**
- * @DI\Inject("entity.manager")
+ * @var EntityManager
*/
private $entityManager;
+
+ public function __construct(EntityManager $entityManager)
+ {
+ $this->entityManager = entityManager;
+ }
}
MergeInterfacesRector
Merges old interface to a new one, that already has its methods
services:
Rector\Core\Rector\Interface_\MergeInterfacesRector:
SomeOldInterface: SomeInterface
↓
-class SomeClass implements SomeInterface, SomeOldInterface
+class SomeClass implements SomeInterface
{
}
MethodCallToAnotherMethodCallWithArgumentsRector
Turns old method call with specific types to new one with arguments
services:
Rector\Core\Rector\MethodCall\MethodCallToAnotherMethodCallWithArgumentsRector:
Nette\DI\ServiceDefinition:
setInject:
-
- addTag
-
- inject
↓
$serviceDefinition = new Nette\DI\ServiceDefinition;
-$serviceDefinition->setInject();
+$serviceDefinition->addTag('inject');
MethodCallToReturnRector
Wrap method call to return
services:
Rector\Core\Rector\MethodCall\MethodCallToReturnRector:
$methodNamesByType:
SomeClass:
- deny
↓
class SomeClass
{
public function run()
{
- $this->deny();
+ return $this->deny();
}
public function deny()
{
return 1;
}
}
MultipleClassFileToPsr4ClassesRector
Turns namespaced classes in one file to standalone PSR-4 classes.
+// new file: "app/Exceptions/FirstException.php"
namespace App\Exceptions;
use Exception;
final class FirstException extends Exception
{
}
+
+// new file: "app/Exceptions/SecondException.php"
+namespace App\Exceptions;
+
+use Exception;
final class SecondException extends Exception
{
}
NewObjectToFactoryCreateRector
Replaces creating object instances with "new" keyword with factory method.
services:
Rector\Core\Rector\Architecture\Factory\NewObjectToFactoryCreateRector:
MyClass:
class: MyClassFactory
method: create
↓
class SomeClass
{
+ /**
+ * @var \MyClassFactory
+ */
+ private $myClassFactory;
+
public function example() {
- new MyClass($argument);
+ $this->myClassFactory->create($argument);
}
}
NewToStaticCallRector
Change new Object to static call
services:
Rector\Core\Rector\New_\NewToStaticCallRector:
$typeToStaticCalls:
Cookie:
- Cookie
- create
↓
class SomeClass
{
public function run()
{
- new Cookie($name);
+ Cookie::create($name);
}
}
NormalToFluentRector
Turns fluent interface calls to classic ones.
services:
Rector\Core\Rector\MethodBody\NormalToFluentRector:
SomeClass:
- someFunction
- otherFunction
↓
$someObject = new SomeClass();
-$someObject->someFunction();
-$someObject->otherFunction();
+$someObject->someFunction()
+ ->otherFunction();
ParentClassToTraitsRector
Replaces parent class to specific traits
services:
Rector\Core\Rector\Class_\ParentClassToTraitsRector:
Nette\Object:
- Nette\SmartObject
↓
-class SomeClass extends Nette\Object
+class SomeClass
{
+ use Nette\SmartObject;
}
PropertyAssignToMethodCallRector
Turns property assign of specific type and property name to method call
services:
Rector\Core\Rector\Assign\PropertyAssignToMethodCallRector:
$oldPropertiesToNewMethodCallsByType:
SomeClass:
oldPropertyName: oldProperty
newMethodName: newMethodCall
↓
$someObject = new SomeClass;
-$someObject->oldProperty = false;
+$someObject->newMethodCall(false);
PropertyToMethodRector
Replaces properties assign calls be defined methods.
services:
Rector\Core\Rector\Property\PropertyToMethodRector:
$perClassPropertyToMethods:
SomeObject:
property:
get: getProperty
set: setProperty
↓
-$result = $object->property;
-$object->property = $value;
+$result = $object->getProperty();
+$object->setProperty($value);
services:
Rector\Core\Rector\Property\PropertyToMethodRector:
$perClassPropertyToMethods:
SomeObject:
property:
get:
method: getConfig
arguments:
- someArg
↓
-$result = $object->property;
+$result = $object->getProperty('someArg');
PseudoNamespaceToNamespaceRector
Replaces defined Pseudo_Namespaces by Namespace\Ones.
services:
Rector\Core\Rector\Namespace_\PseudoNamespaceToNamespaceRector:
$namespacePrefixesWithExcludedClasses:
Some_:
- Some_Class_To_Keep
↓
-/** @var Some_Chicken $someService */
-$someService = new Some_Chicken;
+/** @var Some\Chicken $someService */
+$someService = new Some\Chicken;
$someClassToKeep = new Some_Class_To_Keep;
RemoveInterfacesRector
Removes interfaces usage from class.
services:
Rector\Core\Rector\Interface_\RemoveInterfacesRector:
- SomeInterface
↓
-class SomeClass implements SomeInterface
+class SomeClass
{
}
RemoveTraitRector
Remove specific traits from code
class SomeClass
{
- use SomeTrait;
}
RenameClassConstantsUseToStringsRector
Replaces constant by value
services:
Rector\Core\Rector\Constant\RenameClassConstantsUseToStringsRector:
Nette\Configurator:
DEVELOPMENT: development
PRODUCTION: production
↓
-$value === Nette\Configurator::DEVELOPMENT
+$value === "development"
RenamePropertyRector
Replaces defined old properties by new ones.
services:
Rector\Core\Rector\Property\RenamePropertyRector:
$oldToNewPropertyByTypes:
SomeClass:
someOldProperty: someNewProperty
↓
-$someObject->someOldProperty;
+$someObject->someNewProperty;
ReplaceVariableByPropertyFetchRector
Turns variable in controller action to property fetch, as follow up to action injection variable to property change.
final class SomeController
{
/**
* @var ProductRepository
*/
private $productRepository;
public function __construct(ProductRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public function default()
{
- $products = $productRepository->fetchAll();
+ $products = $this->productRepository->fetchAll();
}
}
ReturnThisRemoveRector
Removes "return $this;" from fluent interfaces for specified classes.
services:
Rector\Core\Rector\MethodBody\ReturnThisRemoveRector:
-
- SomeExampleClass
↓
class SomeClass
{
public function someFunction()
{
- return $this;
}
public function otherFunction()
{
- return $this;
}
}
ServiceGetterToConstructorInjectionRector
Get service call to constructor injection
services:
Rector\Core\Rector\MethodCall\ServiceGetterToConstructorInjectionRector:
$methodNamesByTypesToServiceTypes:
FirstService:
getAnotherService: AnotherService
↓
final class SomeClass
{
/**
* @var FirstService
*/
private $firstService;
- public function __construct(FirstService $firstService)
- {
- $this->firstService = $firstService;
- }
-
- public function run()
- {
- $anotherService = $this->firstService->getAnotherService();
- $anotherService->run();
- }
-}
-
-class FirstService
-{
/**
* @var AnotherService
*/
private $anotherService;
- public function __construct(AnotherService $anotherService)
+ public function __construct(FirstService $firstService, AnotherService $anotherService)
{
+ $this->firstService = $firstService;
$this->anotherService = $anotherService;
}
- public function getAnotherService(): AnotherService
+ public function run()
{
- return $this->anotherService;
+ $anotherService = $this->anotherService;
+ $anotherService->run();
}
}
StaticCallToFunctionRector
Turns static call to function call.
services:
Rector\Core\Rector\StaticCall\StaticCallToFunctionRector:
$staticCallToFunction:
OldClass:
oldMethod: new_function
↓
-OldClass::oldMethod("args");
+new_function("args");
StringToClassConstantRector
Changes strings to specific constants
services:
Rector\Core\Rector\String_\StringToClassConstantRector:
compiler.post_dump:
- Yet\AnotherClass
- CONSTANT
↓
final class SomeSubscriber
{
public static function getSubscribedEvents()
{
- return ['compiler.post_dump' => 'compile'];
+ return [\Yet\AnotherClass::CONSTANT => 'compile'];
}
}
SwapClassMethodArgumentsRector
Reorder class method arguments, including their calls
services:
Rector\Core\Rector\StaticCall\SwapClassMethodArgumentsRector:
$newArgumentPositionsByMethodAndClass:
SomeClass:
run:
- 1
- 0
↓
class SomeClass
{
- public static function run($first, $second)
+ public static function run($second, $first)
{
- self::run($first, $second);
+ self::run($second, $first);
}
}
SwapFuncCallArgumentsRector
Swap arguments in function calls
final class SomeClass
{
public function run($one, $two)
{
- return some_function($one, $two);
+ return some_function($two, $one);
}
}
ToStringToMethodCallRector
Turns defined code uses of "__toString()" method to specific method calls.
services:
Rector\Core\Rector\MagicDisclosure\ToStringToMethodCallRector:
SomeObject: getPath
↓
$someValue = new SomeObject;
-$result = (string) $someValue;
-$result = $someValue->__toString();
+$result = $someValue->getPath();
+$result = $someValue->getPath();
UnsetAndIssetToMethodCallRector
Turns defined __isset
/__unset
calls to specific method calls.
services:
Rector\Core\Rector\MagicDisclosure\UnsetAndIssetToMethodCallRector:
SomeContainer:
isset: hasService
↓
$container = new SomeContainer;
-isset($container["someKey"]);
+$container->hasService("someKey");
services:
Rector\Core\Rector\MagicDisclosure\UnsetAndIssetToMethodCallRector:
SomeContainer:
unset: removeService
↓
$container = new SomeContainer;
-unset($container["someKey"]);
+$container->removeService("someKey");
WrapReturnRector
Wrap return value of specific method
services:
Rector\Core\Rector\ClassMethod\WrapReturnRector:
SomeClass:
getItem: array
↓
final class SomeClass
{
public function getItem()
{
- return 1;
+ return [1];
}
}