/**
* Hydrate array of MongoDB document data into the given document object
* based on the mapping information provided in the ClassMetadata instance.
*
* @param ClassMetadata $metadata The ClassMetadata instance for mapping information.
* @param string $document The document object to hydrate the data into.
* @param array $data The array of document data.
* @return array $values The array of hydrated values.
*/
public function hydrate(ClassMetadata $metadata, $document, $data)
{
$values = array();
foreach ($metadata->fieldMappings as $mapping) {
$rawValue = $this->_getFieldValue($mapping, $document, $data);
if (!isset($rawValue)) {
continue;
}
if (isset($mapping['embedded'])) {
$embeddedMetadata = $this->_dm->getClassMetadata($mapping['targetDocument']);
$embeddedDocument = $embeddedMetadata->newInstance();
if ($mapping['type'] === 'many') {
$documents = new ArrayCollection();
foreach ($rawValue as $docArray) {
$doc = clone $embeddedDocument;
$this->hydrate($embeddedMetadata, $doc, $docArray);
$documents->add($doc);
}
$metadata->setFieldValue($document, $mapping['fieldName'], $documents);
$value = $documents;
} else {
$value = clone $embeddedDocument;
$this->hydrate($embeddedMetadata, $value, $rawValue);
$metadata->setFieldValue($document, $mapping['fieldName'], $value);
}
} elseif (isset($mapping['reference'])) {
$targetMetadata = $this->_dm->getClassMetadata($mapping['targetDocument']);
$targetDocument = $targetMetadata->newInstance();
if ($mapping['type'] === 'one' && isset($rawValue[$this->_cmd . 'id'])) {
$id = $targetMetadata->getPHPIdentifierValue($rawValue[$this->_cmd . 'id']);
$proxy = $this->_dm->getReference($mapping['targetDocument'], $id);
$metadata->setFieldValue($document, $mapping['fieldName'], $proxy);
} elseif ($mapping['type'] === 'many' && (is_array($rawValue) || $rawValue instanceof Collection)) {
$documents = new PersistentCollection($this->_dm, $targetMetadata, new ArrayCollection());
$documents->setInitialized(false);
foreach ($rawValue as $v) {
$id = $targetMetadata->getPHPIdentifierValue($v[$this->_cmd . 'id']);
$proxy = $this->_dm->getReference($mapping['targetDocument'], $id);
$documents->add($proxy);
}
$metadata->setFieldValue($document, $mapping['fieldName'], $documents);
}
} else {
$value = Type::getType($mapping['type'])->convertToPHPValue($rawValue);
$metadata->setFieldValue($document, $mapping['fieldName'], $value);
}
if (isset($value)) {
$values[$mapping['fieldName']] = $value;
}
}
if (isset($data['_id'])) {
$metadata->setIdentifierValue($document, $data['_id']);
}
return $values;
}