How to declare typed Collection inside Symfony Entity in PHP 8.1

2.3k Views Asked by At

I receive an error from PHPStan:

Property App\Entity\Product::$productArticles type mapping mismatch: property can contain Doctrine\Common\Collections\Collection but database  
         expects Doctrine\Common\Collections\Collection&iterable<App\Entity\ProductArticle>

My variable declaration:

#[ORM\OneToMany(mappedBy: 'product', targetEntity: ProductArticle::class)]
    /** @var  Collection<int, ProductArticle> */
    private Collection $productArticles;

How can I use both: annotation to declare variable for ORM and PHPDoc comment to declare Collection type?

1

There are 1 best solutions below

0
On BEST ANSWER

PHPDoc needs to be above the attribute.

class Foo
{
    /** @var  Collection<int, ProductArticle> */
    #[ORM\OneToMany(mappedBy: 'product', targetEntity: ProductArticle::class)]
    private Collection $productArticles;
}

This is a bug with the parser library (nikic/php-parser) PHPStan uses. So it has to be this way for now.