public function createDBRef($document, array $referenceMapping = null)
{
if (!is_object($document)) {
throw new \InvalidArgumentException('Cannot create a DBRef, the document is not an object');
}
$class = $this->getClassMetadata(get_class($document));
$id = $this->unitOfWork->getDocumentIdentifier($document);
if ($id === null) {
throw new \RuntimeException(sprintf('Cannot create a DBRef for class %s without an identifier. Have you forgotten to persist/merge the document first?', $class->name));
}
if ($referenceMapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
if ($class->inheritanceType === ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_COLLECTION) {
throw MappingException::simpleReferenceMustNotTargetDiscriminatedDocument($referenceMapping['targetDocument']);
}
return $class->getDatabaseIdentifierValue($id);
}
$dbRef = array('$ref' => $class->getCollection(), '$id' => $class->getDatabaseIdentifierValue($id));
if ($referenceMapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB) {
$dbRef['$db'] = $this->getDocumentDatabase($class->name)->getName();
}
/* If the class has a discriminator (field and value), use it. A child
* class that is not defined in the discriminator map may only have a
* discriminator field and no value, so default to the full class name.
*/
if (isset($class->discriminatorField)) {
$dbRef[$class->discriminatorField] = isset($class->discriminatorValue) ? $class->discriminatorValue : $class->name;
}
/* Add a discriminator value if the referenced document is not mapped
* explicitly to a targetDocument class.
*/
if ($referenceMapping !== null && !isset($referenceMapping['targetDocument'])) {
$discriminatorField = $referenceMapping['discriminatorField'];
$discriminatorValue = isset($referenceMapping['discriminatorMap']) ? array_search($class->name, $referenceMapping['discriminatorMap']) : $class->name;
/* If the discriminator value was not found in the map, use the full
* class name. In the future, it may be preferable to throw an
* exception here (perhaps based on some strictness option).
*
* @see PersistenceBuilder::prepareEmbeddedDocumentValue()
*/
if ($discriminatorValue === false) {
$discriminatorValue = $class->name;
}
$dbRef[$discriminatorField] = $discriminatorValue;
}
return $dbRef;
}