Add a target-document class name to resolve to a new class name.

@param string           $originalDocument
@param string           $newDocument
@param PropertyMetadata $mapping

@return void
504506
public function addResolveTargetDocument($originalDocument, $newDocument, PropertyMetadata $mapping)
    {
        $mapping->targetDocument = ltrim($newDocument, "\\");

        $this->resolveTargetDocuments[ltrim($originalDocument, "\\")] = $mapping;
    }
474596
protected static function setAliasedProperties(array &$mappedClass, Mapping $mapping, string $className)
    {
        if (false === empty($mappedClass[static::ALIASED_PROPERTIES_KEY])) {
            $mapping->setPropertyNameAliases($mappedClass[static::ALIASED_PROPERTIES_KEY]);
            foreach (\array_keys($mapping->getAliasedProperties()) as $propertyName) {
                if (false === \in_array($propertyName, static::getClassProperties($className), true)) {
                    throw new MappingException(
                        \sprintf(
                            'Could not alias property %s in class %s because it does not exist.',
                            $propertyName,
                            $className
                        )
                    );
                }
            }
        }
    }
434041
public function generate($document, ClassMetadata $class, DocumentManagerInterface $dm, $parent = null)
    {
        if (null === $parent) {
            $parent = $class->parentMapping ? $class->getFieldValue($document, $class->parentMapping) : null;
        }

        $name = $class->nodename ? $class->getFieldValue($document, $class->nodename) : null;
        $id = $class->getFieldValue($document, $class->identifier);

        if (empty($id)) {
            if (empty($name) && empty($parent)) {
                throw IdException::noIdentificationParameters($document, $class->parentMapping, $class->nodename);
            }

            if (empty($parent)) {
                throw IdException::noIdNoParent($document, $class->parentMapping);
            }

            if (empty($name)) {
                throw IdException::noIdNoName($document, $class->nodename);
            }
        }

        // use assigned ID by default
        if (empty($parent) || empty($name)) {
            return $id;
        }

        if ($exception = $class->isValidNodename($name)) {
            throw IdException::illegalName($document, $class->nodename, $name);
        }

        // determine ID based on the path and the node name
        return $this->buildName($document, $class, $dm, $parent, $name);
    }
713308
public function setParentAssociation(object $document, array $mapping, ?object $parent, string $propertyPath) : void
    {
        $oid                                   = spl_object_hash($document);
        $this->embeddedDocumentsRegistry[$oid] = $document;
        $this->parentAssociations[$oid]        = [$mapping, $parent, $propertyPath];
    }
1305009
private function cascadePreUpdate(ClassMetadata $class, $document)
    {
        $hasPreUpdateListeners = $this->evm->hasListeners(Events::preUpdate);

        foreach ($class->fieldMappings as $mapping) {
            if (isset($mapping['embedded'])) {
                $value = $class->reflFields[$mapping['fieldName']]->getValue($document);
                if ($value === null) {
                    continue;
                }
                if ($mapping['type'] === 'one') {
                    $value = array($value);
                }
                foreach ($value as $entry) {
                    $entryOid = spl_object_hash($entry);
                    $entryClass = $this->dm->getClassMetadata(get_class($entry));
                    if ( ! isset($this->documentChangeSets[$entryOid])) {
                        continue;
                    }
                    if ( ! isset($this->documentInsertions[$entryOid])) {
                        if ( ! empty($entryClass->lifecycleCallbacks[Events::preUpdate])) {
                            $entryClass->invokeLifecycleCallbacks(Events::preUpdate, $entry);
                            $this->recomputeSingleDocumentChangeSet($entryClass, $entry);
                        }
                        if ($hasPreUpdateListeners) {
                            $this->evm->dispatchEvent(Events::preUpdate, new Event\PreUpdateEventArgs(
                                $entry, $this->dm, $this->documentChangeSets[$entryOid])
                            );
                        }
                    }
                    $this->cascadePreUpdate($entryClass, $entry);
                }
            }
        }
    }
427900
public function setPropertyOverride(Property $property) : void
    {
        $fieldName = $property->getName();

        if (! isset($this->declaredProperties[$fieldName])) {
            throw MappingException::invalidOverrideFieldName($this->className, $fieldName);
        }

        $originalProperty          = $this->getProperty($fieldName);
        $originalPropertyClassName = get_class($originalProperty);

        // If moving from transient to persistent, assume it's a new property
        if ($originalPropertyClassName === TransientMetadata::class) {
            unset($this->declaredProperties[$fieldName]);

            $this->addProperty($property);

            return;
        }

        // Do not allow to change property type
        if ($originalPropertyClassName !== get_class($property)) {
            throw MappingException::invalidOverridePropertyType($this->className, $fieldName);
        }

        // Do not allow to change version property
        if ($originalProperty instanceof VersionFieldMetadata) {
            throw MappingException::invalidOverrideVersionField($this->className, $fieldName);
        }

        unset($this->declaredProperties[$fieldName]);

        if ($property instanceof FieldMetadata) {
            // Unset defined fieldName prior to override
            unset($this->fieldNames[$originalProperty->getColumnName()]);

            // Revert what should not be allowed to change
            $property->setDeclaringClass($originalProperty->getDeclaringClass());
            $property->setPrimaryKey($originalProperty->isPrimaryKey());
        } elseif ($property instanceof AssociationMetadata) {
            // Unset all defined fieldNames prior to override
            if ($originalProperty instanceof ToOneAssociationMetadata && $originalProperty->isOwningSide()) {
                foreach ($originalProperty->getJoinColumns() as $joinColumn) {
                    unset($this->fieldNames[$joinColumn->getColumnName()]);
                }
            }

            // Override what it should be allowed to change
            if ($property->getInversedBy()) {
                $originalProperty->setInversedBy($property->getInversedBy());
            }

            if ($property->getFetchMode() !== $originalProperty->getFetchMode()) {
                $originalProperty->setFetchMode($property->getFetchMode());
            }

            if ($originalProperty instanceof ToOneAssociationMetadata && $property->getJoinColumns()) {
                $originalProperty->setJoinColumns($property->getJoinColumns());
            } elseif ($originalProperty instanceof ManyToManyAssociationMetadata && $property->getJoinTable()) {
                $originalProperty->setJoinTable($property->getJoinTable());
            }

            $property = $originalProperty;
        }

        $this->addProperty($property);
    }
118766
private function createRepository(DocumentManager $documentManager, $documentName)
    {
        /* @var $metadata \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */
        $metadata = $documentManager->getClassMetadata($documentName);
        $repositoryClassName = $metadata->customRepositoryClassName
            ?: $documentManager->getDefaultRepositoryClassName();

        return new $repositoryClassName($documentManager, $metadata);
    }
807132
private function bind(CustomUrlDocument $document, $data)
    {
        $document->setTitle($data['title']);
        unset($data['title']);

        $metadata = $this->metadataFactory->getMetadataForAlias('custom_url');

        $accessor = PropertyAccess::createPropertyAccessor();

        foreach ($metadata->getFieldMappings() as $fieldName => $mapping) {
            if (!array_key_exists($fieldName, $data)) {
                continue;
            }

            $value = $data[$fieldName];
            if (array_key_exists('type', $mapping) && 'reference' === $mapping['type']) {
                $value = $this->documentManager->find($value, LOCALE, ['load_ghost_content' => true]);
            }

            $accessor->setValue($document, $fieldName, $value);
        }
    }
319008
private function executeDeletions(ClassMetadata $class, array $documents, array $options = []) : void
    {
        $persister = $this->getDocumentPersister($class->name);

        foreach ($documents as $oid => $document) {
            if (! $class->isEmbeddedDocument) {
                $persister->delete($document, $options);
            }
            unset(
                $this->documentDeletions[$oid],
                $this->documentIdentifiers[$oid],
                $this->originalDocumentData[$oid]
            );

            // Clear snapshot information for any referenced PersistentCollection
            // http://www.doctrine-project.org/jira/browse/MODM-95
            foreach ($class->associationMappings as $fieldMapping) {
                if (! isset($fieldMapping['type']) || $fieldMapping['type'] !== ClassMetadata::MANY) {
                    continue;
                }

                $value = $class->reflFields[$fieldMapping['fieldName']]->getValue($document);
                if (! ($value instanceof PersistentCollectionInterface)) {
                    continue;
                }

                $value->clearSnapshot();
            }

            // Document with this $oid after deletion treated as NEW, even if the $oid
            // is obtained by a new document because the old one went out of scope.
            $this->documentStates[$oid] = self::STATE_NEW;

            $this->lifecycleEventManager->postRemove($class, $document);
        }
    }
800377
public function addClass(DocumentMetadata $metadata): void
    {
        $this->graph->addNode($metadata->name);

        $assocNames = $metadata->getAssociationNames();
        foreach ($assocNames as $assocName) {
            $targetClass = $metadata->getAssociationTargetClass($assocName);
            $this->graph->addNode($targetClass);
            $this->graph->connect($metadata->name, $targetClass);
        }
    }
823717
private function addInheritedAttributes(ClassMetadata $subClass, ClassMetadata $parentClass)
    {
        $propertyFactory = new PropertyMetadataFactory($subClass);

        foreach ($parentClass->propertyMetadata as $attributeName => $parentMapping) {
            //in case of inheritance from superclass, otherwise this would be caught by the mapping driver:
            if ($subClass->isEmbeddedDocument && $parentMapping->strategy === PropertyMetadata::STORAGE_STRATEGY_ADD_TO_SET) {
                throw MappingException::addToSetOnEmbeddedDocument($subClass->name, $parentMapping->name);
            }

            $mapping = $propertyFactory->createInherited($parentClass, $parentMapping);

            $subClass->addAttributeMapping($mapping);
        }
    }
1016071
private function cascadePostUpdate(ClassMetadata $class, $document)
    {
        foreach ($class->getEmbeddedAttributesMappings() as $mapping) {
            $value = $class->getPropertyMetadata($mapping->attributeName)->getValue($document);
            if ($value === null) {
                continue;
            }
            $values = $mapping->isOne() ? [$value] : $value;

            foreach ($values as $entry) {
                if (empty($this->uow->getDocumentChangeSet($entry)) && !$this->uow->hasScheduledCollections($entry)) {
                    continue;
                }
                $entryClass = $this->dm->getClassMetadata(get_class($entry));
                $event      = $this->uow->isScheduledForInsert($entry) ? Event::postPersist : Event::postUpdate;
                $entryClass->invokeLifecycleCallbacks($event, $entry, [new LifecycleEventArgs($entry, $this->dm)]);
                $this->evm->dispatchEvent($event, new LifecycleEventArgs($entry, $this->dm));

                $this->cascadePostUpdate($entryClass, $entry);
            }
        }
    }
595298
public function loadMetadataForClass($className, ClassMetadata $metadata)
    {
        $reflClass = $metadata->getReflectionClass();

        $documentAnnots = [];
        foreach ($this->reader->getClassAnnotations($reflClass) as $annot) {
            foreach ($this->entityAnnotationClasses as $annotClass => $i) {
                if ($annot instanceof $annotClass) {
                    $documentAnnots[$i] = $annot;
                }
            }
        }
        if (!$documentAnnots) {
            throw MappingException::classIsNotAValidDocument($className);
        }

        // find the winning document annotation
        ksort($documentAnnots);

        $documentAnnot = reset($documentAnnots);

        if ($documentAnnot instanceof ODM\MappedSuperclass) {
            $metadata->isMappedSuperclass = true;
        }
        if (null !== $documentAnnot->referenceable) {
            $metadata->setReferenceable($documentAnnot->referenceable);
        }

        if (null !== $documentAnnot->versionable) {
            $metadata->setVersioned($documentAnnot->versionable);
        }

        if (null !== $documentAnnot->uniqueNodeType) {
            $metadata->setUniqueNodeType($documentAnnot->uniqueNodeType);
        }

        if (null !== $documentAnnot->mixins) {
            $metadata->setMixins($documentAnnot->mixins);
        }

        if (null !== $documentAnnot->inheritMixins) {
            $metadata->setInheritMixins($documentAnnot->inheritMixins);
        }

        if (null !== $documentAnnot->nodeType) {
            $metadata->setNodeType($documentAnnot->nodeType);
        }

        if (null !== $documentAnnot->repositoryClass) {
            $metadata->setCustomRepositoryClassName($documentAnnot->repositoryClass);
        }

        if (null !== $documentAnnot->translator) {
            $metadata->setTranslator($documentAnnot->translator);
        }

        if ([] !== $documentAnnot->childClasses) {
            $metadata->setChildClasses($documentAnnot->childClasses);
        }

        $metadata->setIsLeaf($documentAnnot->isLeaf);

        foreach ($reflClass->getProperties() as $property) {
            if ($metadata->isInheritedField($property->name)
                && $metadata->name !== $property->getDeclaringClass()->getName()
            ) {
                continue;
            }

            $mapping = [];
            $mapping['fieldName'] = $property->getName();

            foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) {
                if ($fieldAnnot instanceof ODM\Property) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapField($mapping);
                } elseif ($fieldAnnot instanceof ODM\Id) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapId($mapping);
                } elseif ($fieldAnnot instanceof ODM\Node) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapNode($mapping);
                } elseif ($fieldAnnot instanceof ODM\Nodename) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapNodename($mapping);
                } elseif ($fieldAnnot instanceof ODM\ParentDocument) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade);
                    $metadata->mapParentDocument($mapping);
                } elseif ($fieldAnnot instanceof ODM\Child) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade);
                    $metadata->mapChild($mapping);
                } elseif ($fieldAnnot instanceof ODM\Children) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade);
                    $metadata->mapChildren($mapping);
                } elseif ($fieldAnnot instanceof ODM\ReferenceOne) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade);
                    $metadata->mapManyToOne($mapping);
                } elseif ($fieldAnnot instanceof ODM\ReferenceMany) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade);
                    $metadata->mapManyToMany($mapping);
                } elseif ($fieldAnnot instanceof ODM\Referrers) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $mapping['cascade'] = $this->getCascadeMode($fieldAnnot->cascade);
                    $metadata->mapReferrers($mapping);
                } elseif ($fieldAnnot instanceof ODM\MixedReferrers) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapMixedReferrers($mapping);
                } elseif ($fieldAnnot instanceof ODM\Locale) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapLocale($mapping);
                } elseif ($fieldAnnot instanceof ODM\Depth) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapDepth($mapping);
                } elseif ($fieldAnnot instanceof ODM\VersionName) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapVersionName($mapping);
                } elseif ($fieldAnnot instanceof ODM\VersionCreated) {
                    $mapping = array_merge($mapping, (array) $fieldAnnot);
                    $metadata->mapVersionCreated($mapping);
                }
            }
        }

        foreach ($reflClass->getMethods() as $method) {
            if ($method->isPublic() && $method->getDeclaringClass()->getName() == $metadata->name) {
                foreach ($this->reader->getMethodAnnotations($method) as $annot) {
                    if ($annot instanceof ODM\PrePersist) {
                        $metadata->addLifecycleCallback($method->getName(), Event::prePersist);
                    } elseif ($annot instanceof  ODM\PostPersist) {
                        $metadata->addLifecycleCallback($method->getName(), Event::postPersist);
                    } elseif ($annot instanceof ODM\PreUpdate) {
                        $metadata->addLifecycleCallback($method->getName(), Event::preUpdate);
                    } elseif ($annot instanceof ODM\PostUpdate) {
                        $metadata->addLifecycleCallback($method->getName(), Event::postUpdate);
                    } elseif ($annot instanceof ODM\PreRemove) {
                        $metadata->addLifecycleCallback($method->getName(), Event::preRemove);
                    } elseif ($annot instanceof ODM\PostRemove) {
                        $metadata->addLifecycleCallback($method->getName(), Event::postRemove);
                    } elseif ($annot instanceof  ODM\PostLoad) {
                        $metadata->addLifecycleCallback($method->getName(), Event::postLoad);
                    }
                }
            }
        }

        $metadata->validateClassMapping();
    }
960183
@Override
    public boolean updatePolicy(String name, String newDocument)
            throws PolicyIndexException {
        log.debug("Updating document: " + name);

        // FIXME:  DBXML container.updateDocument is failing to update document metadata (this tested on DBXML ver 2.5.13)
        // specifically anySubject, anyResource metadata elements are not changing
        // if Subjects and Resources elements are added/deleted from document.


        // FIXME: this will acquire and release write locks for each operation
        // should instead do this just once for an update
        deletePolicy(name);
        addPolicy(name, newDocument);

        // FIXME:  code below would also need updating for transactions, deadlocks, single thread updates...

        /* original code below works apart from metadata update not happening
        try {
            utils.validate(newDocument, name);
        } catch (MelcoePDPException e) {
            throw new PolicyIndexException(e);
        }

        XmlTransaction txn = null;

        try {
            try {
                txn = dbXmlManager.manager.createTransaction();
                XmlDocument doc = makeDocument(name, newDocument);
                dbXmlManager.container.updateDocument(txn, doc, dbXmlManager.updateContext);
                txn.commit();
                setLastUpdate(System.currentTimeMillis());
            } catch (XmlException xe) {
                txn.abort();
                throw new PolicyIndexException("Error updating document: "
                                                             + name,
                                                     xe);
            }
        } catch (XmlException xe) {
            throw new PolicyIndexException("Error aborting transaction: "
                    + xe.getMessage(), xe);
        }
        */

        return true;
    }
372710
private function executeQuery(object $document, array $newObj, array $options) : void
    {
        $className = get_class($document);
        $class     = $this->dm->getClassMetadata($className);
        $id        = $class->getDatabaseIdentifierValue($this->uow->getDocumentIdentifier($document));
        $query     = ['_id' => $id];
        if ($class->isVersioned) {
            $query[$class->fieldMappings[$class->versionField]['name']] = $class->reflFields[$class->versionField]->getValue($document);
        }
        $collection = $this->dm->getDocumentCollection($className);
        $result     = $collection->updateOne($query, $newObj, $options);
        if ($class->isVersioned && ! $result->getMatchedCount()) {
            throw LockException::lockFailed($document);
        }
    }
251417
private function executeInserts(ClassMetadata $class, array $documents, array $options = []) : void
    {
        $persister = $this->getDocumentPersister($class->name);

        foreach ($documents as $oid => $document) {
            $persister->addInsert($document);
            unset($this->documentInsertions[$oid]);
        }

        $persister->executeInserts($options);

        foreach ($documents as $document) {
            $this->lifecycleEventManager->postPersist($class, $document);
        }
    }
738519
protected void addEntityClassToDocument(EntityMetadata metadata, Object entity, Document document,
        final MetamodelImpl metaModel) {
        try {
            Field luceneField;
            Object id;
            id = PropertyAccessorHelper.getId(entity, metadata);

            // Indexing composite keys
            if (metaModel != null && metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
                id = KunderaCoreUtils.prepareCompositeKey(metadata.getIdAttribute(), metaModel, id);
            }

            luceneField =
                new Field(IndexingConstants.ENTITY_ID_FIELD, id.toString(), Field.Store.YES, Field.Index.ANALYZED);

            // luceneField.set
            // adding class
            // namespace
            // /*Field.Store.YES, Field.Index.ANALYZED_NO_NORMS*/);
            document.add(luceneField);

            // index namespace for unique deletion
            luceneField =
                new Field(IndexingConstants.KUNDERA_ID_FIELD, getKunderaId(metadata, id), Field.Store.YES,
                    Field.Index.ANALYZED); // adding
            // class
            // namespace
            // Field.Store.YES/*, Field.Index.ANALYZED_NO_NORMS*/);
            document.add(luceneField);

            // index entity class
            luceneField =
                new Field(IndexingConstants.ENTITY_CLASS_FIELD, metadata.getEntityClazz().getCanonicalName()
                    .toLowerCase(), Field.Store.YES, Field.Index.ANALYZED);
            document.add(luceneField);
            //
            luceneField = new Field("timestamp", System.currentTimeMillis() + "", Field.Store.YES, Field.Index.NO);
            document.add(luceneField);

            // index index name
            luceneField =
                new Field(IndexingConstants.ENTITY_INDEXNAME_FIELD, metadata.getIndexName(), Field.Store.NO,
                    Field.Index.ANALYZED_NO_NORMS);
            document.add(luceneField);

            luceneField =
                new Field(getCannonicalPropertyName(metadata.getEntityClazz().getSimpleName(),
                    ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()), id.toString(),
                    Field.Store.YES, Field.Index.ANALYZED_NO_NORMS);
            document.add(luceneField);
        } catch (PropertyAccessException e) {
            throw new IllegalArgumentException("Id could not be read from object " + entity);
        }
    }