AbstractCollection->pluck() should always return collection when $collectionOnEmpty=true

Rasmus Vind

Well-known member
I just had a case where I did $entity->TagRelations->pluckNamed('Tag', 'tag_id')->toArray().

In rare circumstances I would get a "could not call toArray() on array" error.

This was puzzling as the call uses pluck() in the implementation and because Tag is uppercase, it will have $collectionOnEmpty=true so it should return a collection. That's the name of the variable.

In rare circumstances this would NOT return a collection because the Tag pointed at by the TagRelation would be missing from the database. I know, my data is not perfect apparently.

I found that inside of pluck() there is the following:
PHP:
                if (!($res[1] instanceof Entity))
                {
                    $newCollection = false;
                }

Which forces the function to suddenly return an array instead of what you asked for because one of the Tag instances is actually null and thus not an entity.

This feels unstable to me. I think it could be designed better.

I now have to go through everywhere where I use pluckNamed() or pluck() to make sure that if it plucks for a relation, I have to either check the return value to be array or stop using pluck.

EDIT: A work-around would be this, but I still feel like AbstractCollection is wrong.

PHP:
			$this->getRelationFinder('TagRelations')
				->with('Tag', true)
				->fetch()
				->pluckNamed('Tag')
				->toArray(),
It would ensure that no Tag is null.
 
Last edited:
Upvote 0
Back
Top Bottom