annotations icon indicating copy to clipboard operation
annotations copied to clipboard

Annotation imports are not parsed for nested traits

Open villermen opened this issue 6 years ago • 3 comments

Bug Report

When an entity uses a trait that itself also uses a trait with a doctrine annotation the mapper failes to recognize the imported annotation. Code example below if it's not clear.

Q A
BC Break no
Version 1.6.1

How to reproduce

Create the following class and traits using doctrine/orm:

// ClassA.php

use Doctrine\Orm\Mapping\Entity;

/**
 * @Entity
 */
class ClassA
{
    use TraitA;
}
// TraitA.php

trait TraitA
{
    use TraitB;
}
// TraitB.php

use Doctrine\ORM\Mapping\Column;

trait TraitB
{
    /**
     * @Column(name="column", type="string")
     */
    protected $column;
}

Trying to create a mapping for this setup will throw an AnnotationException:

[Semantical Error] The annotation "@Column" in property Search\Model\ClassA::$column was never imported. Did you maybe forget to add a "use" statement for this annotation?

This will fail on any Doctrine annotation that is used in TraitB but not imported in TraitA or ClassA.

I expect the @Column-annotation imported in TraitB to stay also be valid for ClassA where it ends up in.

villermen avatar Apr 09 '19 12:04 villermen

Having the same issue (in my case with Gedmo). Cannot use a basic fixer PhpCsFixer\Fixer\Import\NoUnusedImportsFixer because of it. Problem does not exist when annotation is imported inside first level trait.

javaDeveloperKid avatar Jul 08 '19 15:07 javaDeveloperKid

I put this comment in my class to be able to import Gedmo without PHPCS error :

    /**
     * @phpstan-ignore-next-line
     *
     * Use Gedmo var to be able to import it due to issue with Doctrine Annnotations and Traits
     *
     * @see https://github.com/doctrine/annotations/issues/268
     *
     * @var Gedmo
     */

So my class is like this :

<?php

declare(strict_types=1);

namespace App\Entity

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 * @ORM\Table(name="app_myentity")
 */
class MyEntity implements MyEntityInterface
{
    /**
     * @phpstan-ignore-next-line
     *
     * Use Gedmo var to be able to import it due to issue with Doctrine Annnotations and Traits
     *
     * @see https://github.com/doctrine/annotations/issues/268
     *
     * @var Gedmo
     */
    use MyEntityTrait;
}

maximehuran avatar Apr 23 '22 10:04 maximehuran

It could be solved with FQN for annotation or php8 attributes instead of annotation

KovalMax avatar Jan 19 '23 13:01 KovalMax