Skip to content

Handle annotation default property #396

@Vincz

Description

@Vincz

It would be great to be able to define the default property for annotation. At the moment, it always target the property named value. The ability to change this behaviour could lead to more explicit variables names and a better compatibility with PHP8 attributes.

See the following example.

use Attribute;
use Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation;

/**
 * @Annotation
 * @Target({"CLASS"})
 */
#[Attribute(Attribute::TARGET_CLASS)]
class Foo implements NamedArgumentConstructorAnnotation
{
    /**
     * The field name.
     *
     * @var string
     */
    public ?string $name;

    public function __construct(?string $name)
    {
        $this->name = $name;
    }
}

The supported syntax are:

#[Foo("ok")]
class TestClass{}

#[Foo(name: "ok")]
class TestClass{}

/** @Foo(name="ok") */
class TestClass{}

but this one is not supported as it expects a value property.

/** @Foo("not ok") */
class TestClass{}

Note that this is already handled in the Doc Parser for annotation like @Annotation\Attribute, as the default property in this case is name.

Annotation\Attribute::class => [
    'is_annotation'    => true,
    'has_constructor'  => false,
    'targets_literal'  => 'ANNOTATION_ANNOTATION',
    'targets'          => Target::TARGET_ANNOTATION,
    'default_property' => 'name',
     ...
]

We could support the attribute default_property in many ways:

  1. Add it to the @Annotation annotation, like @Annotation(defaultProperty="name"). But as explained here Introduced annotation NamedArgumentConstructor #391 , this annotation is kind of special as it is detected through str_pos.
  2. Add a new annotation @DefaultProperty, like @DefaultPropety("name")
  3. Add this attribute with NamedArgumentConstructorAnnotation only.

Another path would be to force the DocParser to respect argument constructor arguments order if there is a mix of named / not named arguments.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions