Process might quite take long, thanks for your patience

Symfony: Annotation to Attribute

Created at: 2023-10-14

Php Version 8 brought a new way of commenting and adding overhead informations over functions or components: the attributes before it was made in Symfony using annotation. Symfony uses attributes since version 5.2, plugin, recipes (make:entity) migrate later on. 

This article describes a way to fastly migrate from annotation to attributes using Rector. Rector is quite a powerful tool helping you to automatically correct your code, especially usefull when you get an old project or a project developped by a third party. Some parts of the codes might not use the common coding rules.

Rector update your php code to meet new standards

Rector proposes you following automated upgrades of your code. It basically look for a certain pattern in each file of your code and correct / transform it. Basically a preg_replace. But the developpers made it usefull where the community defined the set of rules. 

- import names: 
- anything

Rector has even some rules especially made for symfony. Some of them are usefull when you are migrating from an old version of symfony. 

Upgrade annotation to attributes using Rector

I lately updated the Symfony version of my application, believing that everything would run smoothly. AND IT WAS A FRIDAY, such a bad mistake. the newly created entites were not recongnized by the system. Old ones were having annotations, new one attributes.

Here are the steps to migrate your entites, and most part of your code:

1- install Rector: composer require rector/rector --dev

2- init Rector: vendor/bin/rector

a new rector php file has been created, this is where you give your indication for the updates

3- you want to migrate from annotation to attributes, just replace the code in your rector.php file:

<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Doctrine\Set\DoctrineSetList;
use Rector\Symfony\Set\SymfonySetList;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__ . '/config',
        __DIR__ . '/public',
        __DIR__ . '/src',
        __DIR__ . '/tests',
    ]);

    // register a single rule
    $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);
    $rectorConfig->sets([
        DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES,
        SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES,
    ]);
    // define sets of rules
    //    $rectorConfig->sets([
    //        LevelSetList::UP_TO_PHP_81
    //    ]);
};

4- run rector with vendor/bin/rector process

that's it, you just migrate all your annotation to attributes, within less than one minute.

 

 

 

 

back to list