0

I have to help me convert an entity to array but I have issues resolving associated records, which I need.

However, this gives me an error

The class 'Doctrine\ORM\PersistentCollection' was not found in the chain configured namespaces ...

The code follows:

public function serialize($entityObject)
{
$data = array();

$className = get_class($entityObject);
$metaData = $this->entityManager->getClassMetadata($className);

foreach ($metaData->fieldMappings as $field => $mapping)
{
    $method = "get" . ucfirst($field);
    $data[$field] = call_user_func(array($entityObject, $method));
}

foreach ($metaData->associationMappings as $field => $mapping)
{

    // Sort of entity object
    $object = $metaData->reflFields[$field]->getValue($entityObject);

        if ($object instanceof ArrayCollection) {
            $object = $object->toArray();
        }
        else {
            $data[$field] = $this->serialize($object);
        }

}

return $data;
}

How can I resolve the associated fields into their respective arrays.

I have tried using the built-in, and JMS serialiser, but this gives me issues of nestedness limits, so this is not an option for me.

UPDATE: I have updated the code to handle instance of ArrayCollection as per @ScayTrase's suggestion. However, the error above is still reported with a one-to-many field map. In debug, the variable $object is of type "Doctrine\ORM\PersistentCollection"

0

1 Answer 1

1

For *toMany association properties implemented with ArrayCollection you should call ArrayCollection::toArray() first. Just check it with instanceof before, like this

if ($object instanceof ArrayCollection) {
    $object = $object->toArray();
} 
Sign up to request clarification or add additional context in comments.

2 Comments

That worked. I also had to add a check for PersistentCollection"if ($object instanceof PersistentCollection) { $data[$field] = $object->toArray(); }"
@crafter I think it would better to check if for Collection interface to be sure. Documentations examples ArrayCollection usage, but I think any Collection suits, so check the interface instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.