Open janedbal opened 2 years ago
@janedbal \Doctrine\Common\Collections\ReadableCollection::contains
has conditional return statement using template. Returns false if the contains
parameter type does not match type of collection items. You need to specify type for $accounts
collection.
/** @var ArrayCollection<Account> $accounts */
$accounts = new ArrayCollection();
Thanks for explanation, that works. Although it is a bit questionable behaviour.
/**
* @psalm-param TMaybeContained $element
* @psalm-return (TMaybeContained is T ? bool : false)
*
* @template TMaybeContained
*/
public function contains($element);
So it means Account is MixedType
is evaluated as false. I'd expect evaluation to Maybe... which is hard to decide which return type to use :)
Wondering if phpstan-doctrine should not raise an error if Collection is created without known template type (no constructor argument). That should prevent those problems.
$accounts = new ArrayCollection(); // error
$accounts = new ArrayCollection($knownList); // ok
I think this needs https://github.com/phpstan/phpstan/issues/6732#issuecomment-1062029088 to be solved...
Isn't this fixed thanks to https://github.com/phpstan/phpstan-doctrine/pull/401 ?
No, just tested on 1.3.29
// __construct - Works
$collection = new ArrayCollection(['foo']);
if ($collection->contains('foo')) {}
// add - False positive
$collection = new ArrayCollection();
$collection->add('foo');
if ($collection->contains('foo')) {} # ERROR: If condition is always false.PHPStan
// Workaround - Works
/** @var ArrayCollection<int, string> $collection */
$collection = new ArrayCollection();
$collection->add('foo');
if ($collection->contains('foo')) {}
Following error appeared after upgrading from 1.3.14 to 1.3.15. Easily fixable by using array and creating collection later, so I assume this is minor issue.