Find the best Rector rule to solve your problem



Configurable

RenameClassRector

Replaces defined classes by new ones.

 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;
     }
 }

Configurable

RenameAnnotationRector

Turns defined annotations above properties and methods to their new values.

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     /**
-     * @test
+     * @scenario
      */
     public function someMethod()
     {
     }
 }

Configurable

AnnotationToAttributeRector

Change annotation to attribute

 use Symfony\Component\Routing\Annotation\Route;

 class SymfonyRoute
 {
-    /**
-     * @Route("/path", name="action") api route
-     */
+    #[Route(path: '/path', name: 'action')] // api route
     public function action()
     {
     }
 }

Configurable

AddParamTypeDeclarationRector

Add param types where needed

 class SomeClass
 {
-    public function process($name)
+    public function process(string $name)
     {
     }
 }

Configurable

AddReturnTypeDeclarationRector

Changes defined return typehint of method and class.

 class SomeClass
 {
-    public function getData()
+    public function getData(): array
     {
     }
 }

TicketAnnotationToAttributeRector

Change annotations with value to attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\Ticket;

-/**
- * @ticket 123
- */
+#[Ticket('123')]
 final class SomeTest extends TestCase
 {
 }

CoversAnnotationWithValueToAttributeRector

Change covers annotations with value to attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversFunction;

-/**
- * @covers SomeClass
- */
+#[CoversClass(SomeClass::class)]
+#[CoversFunction('someFunction')]
 final class SomeTest extends TestCase
 {
-    /**
-     * @covers ::someFunction()
-     */
     public function test()
     {
     }
 }

Configurable

AnnotationWithValueToAttributeRector

Change annotations with value to attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\BackupGlobals;

-/**
- * @backupGlobals enabled
- */
+#[BackupGlobals(true)]
 final class SomeTest extends TestCase
 {
 }

DependsAnnotationWithValueToAttributeRector

Change depends annotations with value to attribute

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function testOne() {}

-    /**
-     * @depends testOne
-     */
+    #[\PHPUnit\Framework\Attributes\Depends('testOne')]
     public function testThree(): void
     {
     }
 }

TestWithAnnotationToAttributeRector

Change @testWith() annotation to #[TestWith] attribute

 use PHPUnit\Framework\TestCase;
+use PHPUnit\Framework\Attributes\TestWith;

 final class SomeFixture extends TestCase
 {
-    /**
-     * @testWith ["foo"]
-     *           ["bar"]
-     */
+    #[TestWith(['foo'])]
+    #[TestWith(['bar'])]
     public function test(): void
     {
     }
 }

DataProviderAnnotationToAttributeRector

Change dataProvider annotations to attribute

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
-    /**
-     * @dataProvider someMethod()
-     */
+    #[\PHPUnit\Framework\Attributes\DataProvider('someMethod')]
     public function test(): void
     {
     }
 }

GetMockRector

Turns getMock*() methods to createMock()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $classMock = $this->getMock("Class");
+        $classMock = $this->createMock("Class");
     }
 }

SpecificAssertContainsWithoutIdentityRector

Change assertContains()/assertNotContains() with non-strict comparison to new specific alternatives

-final class SomeTest extends \PHPUnit\Framework\TestCase
+final class SomeTest extends TestCase
 {
     public function test()
     {
         $objects = [ new \stdClass(), new \stdClass(), new \stdClass() ];
-        $this->assertContains(new \stdClass(), $objects, 'message', false, false);
-        $this->assertNotContains(new \stdClass(), $objects, 'message', false, false);
+        $this->assertContainsEquals(new \stdClass(), $objects, 'message');
+        $this->assertNotContainsEquals(new \stdClass(), $objects, 'message');
     }
 }

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();
     }
 }

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;
     }
 }

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'];
     }
 }

SpecificAssertContainsRector

Change assertContains()/assertNotContains() method to new string and iterable alternatives

 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');
     }
 }

AssertEqualsParameterToSpecificMethodsTypeRector

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');
     }
 }

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);
     }
 }

RemoveSetMethodsMethodCallRector

Remove "setMethods()" method as never used, move methods to "addMethods()" if non-existent or @method magic

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $someMock = $this->getMockBuilder(SomeClass::class)
-            ->setMethods(['run'])
             ->getMock();
     }
 }

AssertIssetToAssertObjectHasPropertyRector

Change "isset()" property check, to assertObjectHasProperty() method

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $object = new stdClass();
-        $this->assertTrue(isset($object->someProperty));
+        $this->assertObjectHasProperty('someProperty', $object);
     }
 }

PublicDataProviderClassMethodRector

Change data provider methods to public

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function test()
     {
     }

-    protected static function provideData()
+    public static function provideData()
     {
         yield [1];
     }
 }

AddProphecyTraitRector

Add Prophecy trait for method using $this->prophesize()

 use PHPUnit\Framework\TestCase;
+use Prophecy\PhpUnit\ProphecyTrait;

 final class ExampleTest extends TestCase
 {
+    use ProphecyTrait;
+
     public function testOne(): void
     {
         $prophecy = $this->prophesize(\AnInterface::class);
     }
 }

StaticDataProviderClassMethodRector

Change data provider methods to static

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function test()
     {
     }

-    public function provideData()
+    public static function provideData()
     {
         yield [1];
     }
 }

GetMockBuilderGetMockToCreateMockRector

Remove getMockBuilder() to createMock()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
-        $applicationMock = $this->getMockBuilder('SomeClass')
-           ->disableOriginalConstructor()
-           ->getMock();
+        $applicationMock = $this->createMock('SomeClass');
     }
 }

DelegateExceptionArgumentsRector

Takes setExpectedException() 2nd and next arguments to own methods in PHPUnit.

 use PHPUnit\Framework\TestCase;

 class SomeTest extends TestCase
 {
     public function test()
     {
-        $this->setExpectedException(SomeException::class, "Message", "CODE");
+        $this->setExpectedException(SomeException::class);
+        $this->expectExceptionMessage('Message');
+        $this->expectExceptionCode('CODE');
     }
 }

ExceptionAnnotationRector

Changes @expectedException annotations to expectException*()` methods

-/**
- * @expectedException Exception
- * @expectedExceptionMessage Message
- */
 public function test()
 {
+    $this->expectException('Exception');
+    $this->expectExceptionMessage('Message');
     // tested code
 }

AddDoesNotPerformAssertionToNonAssertingTestRector

Tests without assertion will have @doesNotPerformAssertion

 use PHPUnit\Framework\TestCase;

 class SomeClass extends TestCase
 {
+    /**
+     * @doesNotPerformAssertions
+     */
     public function test()
     {
         $nothing = 5;
     }
 }

AssertEqualsOrAssertSameFloatParameterToSpecificMethodsTypeRector

Change assertEquals()/assertSame() method using float on expected argument to new specific alternatives.

-$this->assertSame(10.20, $value);
-$this->assertEquals(10.20, $value);
-$this->assertEquals(10.200, $value);
+$this->assertEqualsWithDelta(10.20, $value, PHP_FLOAT_EPSILON);
+$this->assertEqualsWithDelta(10.20, $value, PHP_FLOAT_EPSILON);
+$this->assertEqualsWithDelta(10.200, $value, PHP_FLOAT_EPSILON);
 $this->assertSame(10, $value);
SETS:  Code Quality

AssertFalseStrposToContainsRector

Turns strpos/stripos comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertFalse(strpos($anything, "foo"), "message");
+$this->assertNotContains("foo", $anything, "message");
SETS:  Code Quality

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 }}!');
     }
 }
SETS:  Code Quality

AssertNotOperatorRector

Turns not-operator comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue(!$foo, "message");
+$this->assertFalse($foo, "message");
SETS:  Code Quality

AssertCompareOnCountableWithMethodToAssertCountRector

Replaces use of assertSame and assertEquals on Countable objects with count method

-$this->assertSame(1, $countable->count());
+$this->assertCount(1, $countable);
SETS:  Code Quality

AssertPropertyExistsRector

Turns property_exists comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertFalse(property_exists(new Class, "property"));
-$this->assertTrue(property_exists(new Class, "property"));
+$this->assertClassHasAttribute("property", "Class");
+$this->assertClassNotHasAttribute("property", "Class");
SETS:  Code Quality

UseSpecificWithMethodRector

Changes ->with() to more specific method

 class SomeClass extends PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $translator = $this->createMock('SomeClass');

         $translator->expects($this->any())
             ->method('trans')
-            ->with($this->equalTo('old max {{ max }}!'));
+            ->with('old max {{ max }}!');
     }
 }
SETS:  Code Quality

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");
SETS:  Code Quality

UseSpecificWillMethodRector

Changes $mock->will() call to more specific method

 class SomeClass extends PHPUnit\Framework\TestCase
 {
     public function test()
     {
         $translator = $this->createMock('SomeClass');
         $translator->expects($this->any())
             ->method('trans')
-            ->will($this->returnValue('translated max {{ max }}!'));
+            ->willReturnValue('translated max {{ max }}!');
     }
 }
SETS:  Code Quality

AssertCompareToSpecificMethodRector

Turns vague php-only method in PHPUnit TestCase to more specific

-$this->assertSame(10, count($anything), "message");
+$this->assertCount(10, $anything, "message");
SETS:  Code Quality

AssertEqualsToSameRector

Turns assertEquals() into stricter assertSame() for scalar values in PHPUnit TestCase

-$this->assertEquals(2, $result);
+$this->assertSame(2, $result);
SETS:  Code Quality

AssertInstanceOfComparisonRector

Turns instanceof comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertTrue($foo instanceof Foo, "message");
+$this->assertInstanceOf("Foo", $foo, "message");
SETS:  Code Quality

AssertEmptyNullableObjectToAssertInstanceofRector

Change assertNotEmpty() on an object to more clear assertInstanceof()

 use PHPUnit\Framework\TestCase;

 class SomeClass extends TestCase
 {
     public function test()
     {
         $someObject = new stdClass();

-        $this->assertNotEmpty($someObject);
+        $this->assertInstanceof(stdClass::class, $someObject);
     }
 }
SETS:  Code Quality

AssertIssetToSpecificMethodRector

Turns assertTrue() + isset() comparisons to more precise assertArrayHasKey() method

-$this->assertTrue(isset($anything["foo"]), "message");
+$this->assertArrayHasKey("foo", $anything, "message");
SETS:  Code Quality

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);
SETS:  Code Quality

AssertSameBoolNullToSpecificMethodRector

Turns same bool and null comparisons to their method name alternatives in PHPUnit TestCase

-$this->assertSame(null, $anything);
+$this->assertNull($anything);
SETS:  Code Quality

AssertComparisonToSpecificMethodRector

Turns comparison operations to their method name alternatives in PHPUnit TestCase

-$this->assertTrue($foo === $bar, "message");
+$this->assertSame($bar, $foo, "message");
SETS:  Code Quality

AssertSameTrueFalseToAssertTrueFalseRector

Change $this->assertSame(true, ...) to assertTrue()

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     public function test()
     {
         $value = (bool) mt_rand(0, 1);
-        $this->assertSame(true, $value);
+        $this->assertTrue($value);
     }
 }
SETS:  Code Quality

SimplifyForeachInstanceOfRector

Simplify unnecessary foreach check of instances

-foreach ($foos as $foo) {
-    $this->assertInstanceOf(SplFileInfo::class, $foo);
-}
+$this->assertContainsOnlyInstancesOf(\SplFileInfo::class, $foos);
SETS:  Code Quality

PreferPHPUnitThisCallRector

Changes PHPUnit calls from self::assert*() to $this->assert*()

 use PHPUnit\Framework\TestCase;

 final class SomeClass extends TestCase
 {
     public function run()
     {
-        self::assertEquals('expected', $result);
+        $this->assertEquals('expected', $result);
     }
 }
SETS:  Code Quality

TestWithToDataProviderRector

Replace testWith annotation to data provider.

+public function dataProviderSum()
+{
+    return [
+        [0, 0, 0],
+        [0, 1, 1],
+        [1, 0, 1],
+        [1, 1, 3]
+    ];
+}
+
 /**
- * @testWith    [0, 0, 0]
- * @testWith    [0, 1, 1]
- * @testWith    [1, 0, 1]
- * @testWith    [1, 1, 3]
+ * @dataProvider dataProviderSum
  */
-public function testSum(int $a, int $b, int $expected)
+public function test(int $a, int $b, int $expected)
 {
     $this->assertSame($expected, $a + $b);
 }
SETS:  Code Quality

YieldDataProviderRector

Turns array return to yield in data providers

 use PHPUnit\Framework\TestCase;

 final class SomeTest implements TestCase
 {
     public static function provideData()
     {
-        return [
-            ['some text']
-        ];
+        yield ['some text'];
     }
 }
SETS:  Code Quality

ConstructClassMethodToSetUpTestCaseRector

Change __construct() method in tests of PHPUnit\Framework\TestCase to setUp(), to prevent dangerous override

 use PHPUnit\Framework\TestCase;

 final class SomeTest extends TestCase
 {
     private $someValue;

-    public function __construct(?string $name = null, array $data = [], string $dataName = '')
+    protected function setUp()
     {
+        parent::setUp();
+
         $this->someValue = 1000;
-        parent::__construct($name, $data, $dataName);
     }
 }
SETS:  Code Quality

RemoveEmptyTestMethodRector

Remove empty test methods

 class SomeTest extends \PHPUnit\Framework\TestCase
 {
-    /**
-     * testGetTranslatedModelField method
-     *
-     * @return void
-     */
-    public function testGetTranslatedModelField()
-    {
-    }
 }
SETS:  Code Quality

ReplaceTestAnnotationWithPrefixedFunctionRector

Replace @test with prefixed function

 class SomeTest extends \PHPUnit\Framework\TestCase
 {
-    /**
-     * @test
-     */
-    public function onePlusOneShouldBeTwo()
+    public function testOnePlusOneShouldBeTwo()
     {
         $this->assertSame(2, 1+1);
     }
 }
SETS:  Code Quality

DataProviderArrayItemsNewLinedRector

Change data provider in PHPUnit test case to newline per item

 use PHPUnit\Framework\TestCase;

 final class ImageBinaryTest extends TestCase
 {
     /**
      * @dataProvider provideData()
      */
     public function testGetBytesSize(string $content, int $number): void
     {
         // ...
     }

     public static function provideData(): array
     {
-        return [['content', 8], ['content123', 11]];
+        return [
+            ['content', 8],
+            ['content123', 11]
+        ];
     }
 }
SETS:  Code Quality