Find the best Rector rule to solve your problem. Searching through 728 rules.

Found 55 rules:

Configurable

RenameMethodRector

Turn method names to new ones


Configurable

RenameClassConstFetchRector

Replaces defined class constants in their calls.

-$value = SomeClass::OLD_CONSTANT;
-$value = SomeClass::OTHER_OLD_CONSTANT;
+$value = SomeClass::NEW_CONSTANT;
+$value = DifferentClass::NEW_CONSTANT;

AddArrayResultColumnNamesRector

Add column names argument to ArrayResult object

 use Doctrine\DBAL\Cache\ArrayResult;

 final class SomeClass
 {
     public function create(array $items)
     {
-        $result = new ArrayResult($items);
+        $result = new ArrayResult(array_keys($items[0] ?? []), $items);

         return $result;
     }
 }

AddGetReferenceTypeRector

Change $this->getReference() in data fixtures to fill reference class directly

 use Doctrine\Common\DataFixtures\AbstractDataFixture;

 final class SomeFixture extends AbstractDataFixture
 {
     public function run(SomeEntity $someEntity)
     {
-        $someEntity->setSomePassedEntity($this->getReference('some-key'));
+        $someEntity->setSomePassedEntity($this->getReference('some-key'), SomeReference::class);
     }
 }

ReplaceFetchAllMethodCallRector

Change Doctrine\DBAL\Connection and Doctrine\DBAL\Driver\ResultStatement ->fetchAll() to ->fetchAllAssociative() and other replacements

 use Doctrine\DBAL\Connection;

 class SomeClass
 {
     public function run(Connection $connection)
     {
-        return $connection->fetchAll();
+        return $connection->fetchAllAssociative();
     }
 }

ExtractArrayArgOnQueryBuilderSelectRector

Extract array arg on QueryBuilder select, addSelect, groupBy, addGroupBy

 function query(\Doctrine\DBAL\Query\QueryBuilder $queryBuilder)
 {
-    $query = $queryBuilder->select(['u.id', 'p.id']);
+    $query = $queryBuilder->select('u.id', 'p.id');
 }

SetParametersArrayToCollectionRector

Change the argument type for setParameters from array to ArrayCollection and Parameter calls

-$entityManager->createQueryBuilder()->setParameters([
-    'foo' => 'bar'
-]);
+$entityManager->createQueryBuilder()->setParameters(new \Doctrine\Common\Collections\ArrayCollection([
+    new \Doctrine\ORM\Query\Parameter('foo', 'bar')
+]));

CastDoctrineExprToStringRector

Casts Doctrine Expr\x to string where necessary.

 $statements->add(
     $builder->expr()->like(
-        $builder->expr()->lower($column),
-        $builder->expr()->lower($builder->expr()->literal('%'.$like.'%'))
+        (string) $builder->expr()->lower($column),
+        (string) $builder->expr()->lower($builder->expr()->literal('%'.$like.'%'))
     )
 );

AddAnnotationToRepositoryRector

Add @extends ServiceEntityRepository annotation to repository classes

 use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;

+/**
+ * @extends ServiceEntityRepository<\SomeEntity>
+ */
 final class SomeRepository extends ServiceEntityRepository
 {
     public function __construct(ManagerRegistry $registry)
     {
         parent::__construct($registry, SomeEntity::class);
     }
 }

CriteriaOrderingConstantsDeprecationRector

Replace ASC/DESC with enum Ordering in Criteria::orderBy method call, and remove usage of Criteria::ASC and Criteria::DESC constants elsewhere

 use Doctrine\Common\Collections\Criteria;

 $criteria = new Criteria();
-$criteria->orderBy(['someProperty' => 'ASC', 'anotherProperty' => 'DESC']);
+$criteria->orderBy(['someProperty' => \Doctrine\Common\Collections\Order::Ascending, 'anotherProperty' => \Doctrine\Common\Collections\Order::Descending]);

SetArrayToNewCollectionRector

Change array to new ArrayCollection() on collection typed property

 use Doctrine\Common\Collections\ArrayCollection;
+use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     /**
-     * @var ArrayCollection<int, string>
+     * @var Collection<int, string>
      */
     public $items;

     public function someMethod()
     {
-        $this->items = [];
+        $this->items = new ArrayCollection([]);
     }
 }

AssertNullOnCollectionToAssertEmptyRector

Change $this->assertNull() on Collection object to $this->assertEmpty() in tests

 use Doctrine\Common\Collections\Collection;

 final class SomeClass extends \PHPUnit\Framework\TestCase
 {
     private Collection $items;

     public function test(): void
     {
-        $this->assertNull($this->items);
+        $this->assertEmpty($this->items);
     }
 }

AssertSameCountOnCollectionToAssertCountRector

Change $this->assertSame(5, $collection->count()) to $this->assertCount(5, $collection) in tests

 use Doctrine\Common\Collections\Collection;

 final class SomeClass extends \PHPUnit\Framework\TestCase
 {
     private Collection $items;

     public function test(): void
     {
-        $this->assertSame(5, $this->items->count());
+        $this->assertCount(5, $this->items);
     }
 }

InArrayOnCollectionToContainsCallRector

Change in_array() on Collection typed property to ->contains() call

 use Doctrine\Common\Collections\Collection;

 final class InArrayOnAssignedVariable
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

     public function run()
     {
-        return in_array('item', $this->items);
+        return $this->items->contains('item');
     }
 }

ArrayMergeOnCollectionToArrayRector

Change array_merge() on Collection to ->toArray()

 use Doctrine\Common\Collections\Collection;

 final class SetFirstParameterArray
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

     public function merge()
     {
-        return array_merge([], $this->items);
+        return array_merge([], $this->items->toArray());
     }
 }

CurrentOnCollectionToArrayRector

Change current() on Collection typed property to ->toArray() call, to always provide an array

 use Doctrine\Common\Collections\Collection;

 final class SimpleClass
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

     public function merge()
     {
-        return current($this->items);
+        return current($this->items->toArray());
     }
 }

ArrayMapOnCollectionToArrayRector

Change array_map() and array_filter() on Collection typed property to ->toArray() call, to always provide an array

 use Doctrine\Common\Collections\Collection;

 final class ArrayMapOnAssignedVariable
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

     public function merge()
     {
         $items = $this->items;

-        return array_map(fn ($item) => $item, $items);
+        return array_map(fn ($item) => $item, $items->toArray());
     }
 }

NarrowPropertyUnionToCollectionRector

Narrow union type to Collection type in property docblock and native type declaration

 use Doctrine\Common\Collections\Collection;

 class SomeClass
 {
     /**
-     * @var Collection|array
+     * @var Collection
      */
     private $property;
 }

TypedPropertyFromToManyRelationTypeRector

Add "Doctrine\Common\Collections\Collection" type declaration, based on @ORM\*toMany and @ODM\*toMany annotations/attributes

 use Doctrine\ORM\Mapping as ORM;
 use Doctrine\ORM\Mapping\ManyToMany;
+use Doctrine\Common\Collections\Collection;

 class SimpleColumn
 {
     /**
      * @ORM\OneToMany(targetEntity="App\Product")
      */
-    private $products;
+    private Collection $products;

     #[ManyToMany(targetEntity: 'App\Car')]
-    private $cars;
+    private Collection $cars;
 }

ArrayOffsetSetToSetCollectionCallRector

Change dim assign on a Collection to clear ->set() call

 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

     public function setItem()
     {
-        $this->items['key'] = 'value';
+        $this->items->set('key', 'value');
     }
 }

ArrayDimFetchAssignToAddCollectionCallRector

Change add dim assign on collection to an->add() call

 use Doctrine\Common\Collections\Collection;

 final class SetFirstParameterArray
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

     public function setItems($item)
     {
-        $this->items[] = $item;
+        $this->items->add($item);
     }
 }

RemoveNullsafeOnCollectionRector

Remove nullsafe check on method call on a Collection type

 use Doctrine\Common\Collections\Collection;

 class SomeClass
 {
     private Collection $collection;

     public function run()
     {
-        return $this->collection?->empty();
+        return $this->collection->empty();
     }
 }

EmptyOnCollectionToIsEmptyCallRector

Convert empty() on a Collection to ->isEmpty() call

 class SomeClass
 {
     /**
      * @var Collection<int, string>
      */
     private $collection;

     public function someMethod()
     {
-        if (empty($this->collection)) {
+        if ($this->collection->isEmpty()) {
             // ...
         }
     }
 }

RemoveNewArrayCollectionWrapRector

Remove new ArrayCollection wrap on collection typed property, as it is always assigned in the constructor

-use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     public ?Collection $items;

     public function someMethod()
     {
-        $values = new ArrayCollection($this->items);
+        $values = $this->items;
     }
 }

RemoveCoalesceAssignOnCollectionRector

Remove coalesce assign on collection typed property, as it is always assigned in the constructor

-use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;

 /**
  * @ORM\Entity
  */
 class SomeEntity
 {
     private $collection;

     public function run()
     {
-        $items = $this->collection ?? new ArrayCollection();
+        $items = $this->collection;
     }
 }

RemoveAssertNotNullOnCollectionRector

Remove RectorPrefix202507\PHPUnit\Framework\Assert::assertNotNull() on a Collection type

 use Doctrine\Common\Collections\Collection;

 class SomeClass
 {
     public function run(Collection $collection): void
     {
-        Assert::assertNotNull($collection);
     }
 }

RemoveIfCollectionIdenticalToNullRector

Remove collection identical to null from if || condition

 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     private Collection $collection;

     public function someMethod()
     {
-        if ($this->collection === null || $this->collection->isEmpty()) {
+        if ($this->collection->isEmpty()) {
             return true;
         }

         return false;
     }
 }

RemoveIsArrayOnCollectionRector

Remove if instance of collection on already known Collection type

 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     public ?Collection $items;

     public function someMethod()
     {
-        $items = is_array($this->items) ? $this->items : $this->items->toArray();
+        $items = $this->items->toArray();
     }
 }

RemoveUselessIsEmptyAssignRector

Remove useless isEmpty() check on collection with following new ArrayCollection() instance

 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     private Collection $collection;

     public function someMethod()
     {
-        if ($this->collection->isEmpty()) {
-            $this->collection = new ArrayCollection();
-        }
-
         return $this->collection;
     }
 }

RemoveIfInstanceofCollectionRector

Remove if instance of collection on already known Collection type

 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     public ?Collection $items;

     public function someMethod()
     {
-        if ($this->items instanceof Collection) {
-            $values = $this->items;
-        }
+        $values = $this->items;
     }
 }

CompleteParamDocblockFromSetterToCollectionRector

Improve @param Doctrine collection types to make them useful both for PHPStan and PHPStorm

 use Doctrine\Common\Collections\Collection;
 use Doctrine\ORM\Mapping as ORM;

 /**
  * @ORM\Entity
  */
 class SomeClass
 {
     /**
      * @ORM\OneToMany(targetEntity=Trainer::class, mappedBy="trainer")
      * @var Collection|Trainer[]
      */
     private $trainings = [];

+    /**
+     * @param Collection<int, Trainer> $trainings
+     */
     public function setTrainings($trainings)
     {
         $this->trainings = $trainings;
     }
 }

RemoveNullFromInstantiatedArrayCollectionPropertyRector

Remove nullability from instantiated ArrayCollection properties, set it to Collection

 use Doctrine\Common\Collections\Collection;
 use Doctrine\Common\Collections\ArrayCollection;

 class SomeClass
 {
-    private ?Collection $trainings = null;
+    private Collection $trainings;

     public function __construct()
     {
         $this->trainings = new ArrayCollection();
     }
 }

InitializeCollectionInConstructorRector

Initialize Collection property in entity/ODM __construct()

+use Doctrine\ORM\Mapping\Entity;
 use Doctrine\ORM\Mapping\OneToMany;
-use Doctrine\ORM\Mapping\Entity;
+use Doctrine\Common\Collections\ArrayCollection;
+use Doctrine\Common\Collections\Collection;

 #[Entity]
 class SomeClass
 {
     #[OneToMany(targetEntity: 'SomeClass')]
     private $items;
+
+    public function __construct()
+    {
+        $this->items = new ArrayCollection();
+    }
 }

CompletePropertyDocblockFromToManyRector

Improve Doctrine property @var collections type to make them useful both for PHPStan and PHPStorm

 use Doctrine\Common\Collections\Collection;
 use Doctrine\ORM\Mapping as ORM;

 /**
  * @ORM\Entity
  */
 class SomeClass
 {
     /**
      * @ORM\OneToMany(targetEntity=Trainer::class, mappedBy="trainer")
-     * @var Collection|Trainer[]
+     * @var Collection<int, Trainer>
      */
     private $trainings = [];

     public function setTrainings($trainings)
     {
         $this->trainings = $trainings;
     }
 }

CompleteReturnDocblockFromToManyRector

Adds @return PHPDoc type to Collection property getter by *ToMany annotation/attribute

-use App\Entity\Training;
 use Doctrine\ORM\Mapping as ORM;

 /**
  * @ORM\Entity
  */
 final class Trainer
 {
     /**
      * @ORM\OneToMany(targetEntity=Training::class)
      */
     private $trainings;

+    /**
+     * @return \Doctrine\Common\Collections\Collection<int, \App\Entity\Training>
+     */
     public function getTrainings()
     {
         return $this->trainings;
     }
 }

ReturnCollectionDocblockRector

Add return Collection docblock to method that returns a collection property

 use Doctrine\Common\Collections\Collection;

 final class OverrideMix
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

     /**
-     * @return Collection|string[]
+     * @return Collection<int, string>
      */
     public function getItems()
     {
         return $this->items;
     }
 }

DefaultCollectionKeyRector

Add default key to Collection generic type if missing in @param or @return of class method

 use Doctrine\Common\Collections\Collection;

 final class ReturnSimpleCollection
 {
     /**
-     * @return Collection<string>
+     * @return Collection<int, string>
      */
     public function someMethod()
     {
     }
 }

RemoveNullFromNullableCollectionTypeRector

Remove null from a nullable Collection, as empty ArrayCollection is preferred instead to keep property/class method type strict and always a collection

 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     private $items;

-    public function setItems(?Collection $items): void
+    public function setItems(Collection $items): void
     {
         $this->items = $items;
     }
 }

NarrowReturnUnionToCollectionRector

Narrow union type to Collection type in method docblock

 use Doctrine\Common\Collections\Collection;
+use Doctrine\Common\Collections\ArrayCollection;

 final class SomeClass
 {
     /**
-     * @return Collection|array
+     * @return Collection
      */
     public function getItems()
     {
         return [];
     }
 }

CollectionParamTypeSetterToCollectionPropertyRector

Add property collection type based on param type setter

 use Doctrine\Common\Collections\Collection;

 final class SetFirstParameterArray
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

-    public function setItems(array $items)
+    public function setItems(\Doctrine\Common\Collections\Collection $items)
     {
         $this->items = $items;
     }
 }

CollectionGetterNativeTypeRector

Add native return type to a Collection getter

 use Doctrine\Common\Collections\Collection;

 final class ReturnPropertyCollectionWithArrayTypeDeclaration
 {
     /**
      * @var Collection<int, string>
      */
     public $items;

-    public function getItems(): array
+    public function getItems(): Collection
     {
         return $this->items;
     }
 }

CollectionSetterParamNativeTypeRector

Add native param type to a Collection setter

 use Doctrine\Common\Collections\Collection;

 final class SomeClass
 {
     private $items;

     /**
      * @param Collection<int, string> $items
      */
-    public function setItems($items): void
+    public function setItems(Collection $items): void
     {
         $this->items = $items;
     }
 }

RemoveNewArrayCollectionOutsideConstructorRector

Remove new ArrayCollection() assigns outside constructor

+namespace Rector\Doctrine\Tests\TypedCollections\Rector\ClassMethod\RemoveNewArrayCollectionOutsideConstructorRector\Fixture;
+
 use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;

 final class NoAssignOutsideConstructor
 {
     public Collection $items;

     public function anotherMethod()
     {
-        $this->items = new ArrayCollection();
     }
 }

ReturnArrayToNewArrayCollectionRector

Change return [] to return new ArrayCollection([]) in a method, that returns Collection type

+use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;

 final class ReturnArrayItems
 {
     public function getItems(): Collection
     {
         $items = [1, 2, 3];
         $items[] = 4;

-        return $items;
+        return new ArrayCollection($items);
     }
 }

NarrowArrayCollectionToCollectionRector

Narrow ArrayCollection to Collection in class method and property

 use Doctrine\Common\Collections\ArrayCollection;

 final class ArrayCollectionGeneric
 {
     /**
-     * @return ArrayCollection<int, string>
+     * @return \Doctrine\Common\Collections\Collection<int, string>
      */
     public function someMethod()
     {
     }
 }

NarrowParamUnionToCollectionRector

Narrow union param docblock type to Collection type in class method

 use Doctrine\Common\Collections\Collection;

 class SomeClass
 {
     /**
-     * @param Collection|array $items
+     * @param Collection $items
      */
     public function run($items)
     {
     }
 }

ChangeCompositeExpressionAddMultipleWithWithRector

Change CompositeExpression ->addMultiple($parts) to ->with(...$parts)

 use Doctrine\ORM\EntityRepository;
 use Doctrine\DBAL\Query\Expression\CompositeExpression;

 class SomeRepository extends EntityRepository
 {
     public function getSomething($parts)
     {
         $compositeExpression = CompositeExpression::and('', ...$parts);
-        $compositeExpression->addMultiple($parts);
+        $compositeExpression->with(...$parts);
     }
 }

ExecuteQueryParamsToBindValueRector

Change executeQuery() with parameters to bindValue() with explicit values

 use Doctrine\DBAL\Statement;

 class SomeClass
 {
     public function run(Statement $statement, array $params): void
     {
-        $result = $statement->executeQuery($params)
+        foreach ($params as $key=> $value) {
+            $statement->bindValue($key + 1, $value);
+        }
+
+        $result = $statement->executeQuery();
     }
 }

EventSubscriberInterfaceToAttributeRector

Replace EventSubscriberInterface with #[AsDoctrineListener] attribute

+use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
 use Doctrine\ORM\Event\PrePersistEventArgs;
 use Doctrine\ORM\Event\PostUpdateEventArgs;
-use Doctrine\Common\EventSubscriberInterface;
 use Doctrine\ORM\Events;

-class MyEventSubscriber implements EventSubscriberInterface
+#[AsDoctrineListener(event: Events::postUpdate)]
+#[AsDoctrineListener(event: Events::prePersist)]
+class MyEventSubscriber
 {
-    public function getSubscribedEvents()
-    {
-        return array(
-            Events::postUpdate,
-            Events::prePersist,
-        );
-    }
-
     public function postUpdate(PostUpdateEventArgs $args)
     {
         // ...
     }

     public function prePersist(PrePersistEventArgs $args)
     {
         // ...
     }
 }

ReplaceLifecycleEventArgsByDedicatedEventArgsRector

Replace Doctrine\ORM\Event\LifecycleEventArgs with specific event classes based on the function call

-use Doctrine\ORM\Event\LifecycleEventArgs;
+use Doctrine\ORM\Event\PrePersistEventArgs;

 class PrePersistExample
 {
-    public function prePersist(LifecycleEventArgs $args)
+    public function prePersist(PrePersistEventArgs $args)
     {
         // ...
     }
 }

CorrectDefaultTypesOnEntityPropertyRector

Change default value types to match Doctrine annotation type

 use Doctrine\ORM\Mapping as ORM;

 /**
  * @ORM\Entity()
  */
 class User
 {
     /**
      * @ORM\Column(name="is_old", type="boolean")
      */
-    private $isOld = '0';
+    private $isOld = false;
 }
SETS:  Code Quality

TypedPropertyFromColumnTypeRector

Complete @var annotations or types based on @ORM\Column

 use Doctrine\ORM\Mapping as ORM;

 class SimpleColumn
 {
     /**
      * @ORM\Column(type="string")
      */
-    private $name;
+    private string|null $name = null;
 }
SETS:  Code Quality

Configurable

TypedPropertyFromToOneRelationTypeRector

Complete @var annotations or types based on @ORM\*toOne annotations or attributes

 use Doctrine\ORM\Mapping as ORM;

 class SimpleColumn
 {
     /**
      * @ORM\OneToOne(targetEntity="App\Company\Entity\Company")
      * @ORM\JoinColumn(nullable=false)
      */
-    private $company;
+    private ?\App\Company\Entity\Company $company = null;
 }
SETS:  Code Quality

MoveCurrentDateTimeDefaultInEntityToConstructorRector

Move default value for entity property to constructor, the safest place

 use Doctrine\ORM\Mapping as ORM;

 /**
  * @ORM\Entity()
  */
 class User
 {
     /**
      * @var DateTimeInterface
      *
-     * @ORM\Column(type="datetime", nullable=false, options={"default"="now()"})
+     * @ORM\Column(type="datetime", nullable=false)
      */
-    private $when = 'now()';
+    private $when;
+
+    public function __construct()
+    {
+        $this->when = new \DateTime();
+    }
 }
SETS:  Code Quality

RemoveEmptyTableAttributeRector

Remove empty Table attribute on entities because it's useless

 <?php

 namespace RectorPrefix202507;

 use RectorPrefix202507\Doctrine\ORM\Mapping as ORM;
-#[ORM\Table]
 #[ORM\Entity]
 class Product
 {
 }
 \class_alias('Product', 'Product', \false);
SETS:  Code Quality