DEV Community

Robert Radošić for Bornfight

Posted on

Refactoring type annotations to PHP 7.4 type declarations with Rector

The problem

So, you have an older PHP project that uses type hinting via annotations and you would like to move away from those ugly annotations to nice inline type declarations.

From this:

<?php

declare(strict_types=1);

class SomeClass 
{
    /**
    * @var string
    */
    private $someProperty;
}
Enter fullscreen mode Exit fullscreen mode

To this:

<?php

declare(strict_types=1);

class SomeClass 
{
    private string $someProperty;
}
Enter fullscreen mode Exit fullscreen mode

Sure, you could do it manually but depending on the size of the project this could take anywhere from a day to a couple of weeks.

The solution

Well, worry not, this is where Rector comes in. Rector is a "tool for automated refactoring" that will make changes in your code based on pre-defined rules. One of those many rules will help us to automatically move type declarations from annotations to inline declarations and that rule is called TypedPropertyRector. So now that we know what Rector is and what rule to use, how do we use it?

First of all install Rector using composer
composer require rector/rector --dev

Next, use the init command to create the rector.php config file
vendor/bin/rector init

Now it's time to modify the config file to suit our use case

<?php
//rector.php

declare(strict_types=1);

use Rector\Php74\Rector\Property\TypedPropertyRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $services = $containerConfigurator->services();
    $services->set(TypedPropertyRector::class);
};
Enter fullscreen mode Exit fullscreen mode

Finally, you can either run Rector to process your files in the src directory
vendor/bin/rector process src or do a dry run to catch any errors that might pop up beforehand vendor/bin/rector process src --dry-run

Conclusion

Rector is an amazing tool that will let you do all sorts of improvements on your code and automate a lot of work when migrating to other PHP versions. It's also not a bad idea to consider using it as a part of your CI pipeline for automated code refactoring or even automated code review.

Top comments (0)