PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 23, 2022

[FIXED] How to declare typed Collection inside Symfony Entity in PHP 8.1

 November 23, 2022     doctrine-orm, php, phpstan     No comments   

Issue

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?


Solution

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.



Answered By - Can Vural
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing