How to convert annotations to attributes in PHP
Table of Contents
Introduction
With the release of PHP 8.0, many PHP libraries started deprecating annotations in favor of native attributes. In Symfony 7.0+, attributes are the recommended and default approach.
Install dependencies
First, let's install Rector library.
NOTE
Rector is a PHP tool that you can run on any PHP project to get an instant upgrade or automated refactoring.
composer require rector/rector --dev
Run command to generate configuration
./vendor/bin/rector
Configure
Put the following code into the rector.php file.
rector.php
<?php
use Rector\Config\RectorConfig;
use Rector\Php80\Rector\Class_\AnnotationToAttributeRector;
use Rector\Php80\ValueObject\AnnotationToAttribute;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->paths([
__DIR__ . '/src/',
]);
$rectorConfig->ruleWithConfiguration(AnnotationToAttributeRector::class, [
new AnnotationToAttribute(
\App\Annotations\RequestParam::class, // Annotation class
\App\Attributes\RequestParam::class // Attribute class
),
]);
};
Run command
./vendor/bin/rector process --dry-run
This allows you to review all planned changes before applying them to your codebase. When you are ready, run
./vendor/bin/rector process
Result
Before:
/**
* @RequestParam(name="id", type="int")
*/
public function action() {}
After:
#[RequestParam(name: 'id', type: 'int')]
public function action() {}
That's it - your annotations are now safely converted to PHP attributes using Rector.