Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 8, 2021 02:11 pm GMT

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:

<?phpdeclare(strict_types=1);class SomeClass {    /**    * @var string    */    private $someProperty;}

To this:

<?phpdeclare(strict_types=1);class SomeClass {    private string $someProperty;}

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

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.


Original Link: https://dev.to/bornfightcompany/refactoring-type-annotations-to-php-7-4-type-declarations-with-rector-50a4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To