Map timestamps to the search document.

@param Document $document
@param \DateTime $created
@param \DateTime $changed
430539
private function mapTimestamp(Document $document, \DateTime $created = null, \DateTime $changed = null)
    {
        $document->addField(
            $this->factory->createField('created', $created ? $created->format('c') : null, 'string')
        );

        $document->addField(
            $this->factory->createField('changed', $changed ? $changed->format('c') : null, 'string')
        );
    }
572409
public function setTimestampsOnNodeForPersist(PersistEvent $event)
    {
        $document = $event->getDocument();

        if (!$this->supports($document)) {
            return;
        }

        $this->setTimestampsOnNode(
            $document,
            $event->getNode(),
            $event->getAccessor(),
            $this->documentInspector->getOriginalLocale($document),
            new \DateTime()
        );
    }
1034221
public function computeChangeSets()
    {
        $this->computeScheduleInsertsChangeSets();
        $this->computeScheduleUpsertsChangeSets();

        // Compute changes for other MANAGED documents. Change tracking policies take effect here.
        foreach ($this->identityMap as $className => $documents) {
            $class = $this->dm->getClassMetadata($className);
            if ($class->isEmbeddedDocument) {
                /* we do not want to compute changes to embedded documents up front
                 * in case embedded document was replaced and its changeset
                 * would corrupt data. Embedded documents' change set will
                 * be calculated by reachability from owning document.
                 */
                continue;
            }

            // If change tracking is explicit or happens through notification, then only compute
            // changes on document of that type that are explicitly marked for synchronization.
            switch (true) {
                case ($class->isChangeTrackingDeferredImplicit()):
                    $documentsToProcess = $documents;
                    break;

                case (isset($this->scheduledForDirtyCheck[$className])):
                    $documentsToProcess = $this->scheduledForDirtyCheck[$className];
                    break;

                default:
                    $documentsToProcess = [];
            }

            foreach ($documentsToProcess as $document) {
                // Ignore uninitialized proxy objects
                if ($document instanceof Proxy && !$document->__isInitialized__) {
                    continue;
                }
                // Only MANAGED documents that are NOT SCHEDULED FOR INSERTION, UPSERT OR DELETION are processed here.
                $oid = spl_object_hash($document);
                if (isset($this->documentInsertions[$oid])
                    || isset($this->documentUpserts[$oid])
                    || isset($this->documentDeletions[$oid])
                    || !isset($this->documentStates[$oid])
                ) {
                    continue;
                }

                $this->computeChangeSet($class, $document);
            }
        }
    }
739252
public function withTimestamps($createdAt = null, $updatedAt = null)
    {
        $this->pivotCreatedAt = $createdAt;
        $this->pivotUpdatedAt = $updatedAt;

        return $this->withPivot($this->createdAt(), $this->updatedAt());
    }
1306110
private List<DocumentChange> computeSnapshot(Timestamp readTime) {
    List<DocumentChange> appliedChanges = new ArrayList<>();

    ChangeSet changeSet = extractChanges(readTime);

    // Process the sorted changes in the order that is expected by our clients (removals, additions,
    // and then modifications). We also need to sort the individual changes to assure that
    // oldIndex/newIndex keep incrementing.
    Collections.sort(changeSet.deletes, comparator);
    for (QueryDocumentSnapshot delete : changeSet.deletes) {
      appliedChanges.add(deleteDoc(delete));
    }

    Collections.sort(changeSet.adds, comparator);
    for (QueryDocumentSnapshot add : changeSet.adds) {
      appliedChanges.add(addDoc(add));
    }

    Collections.sort(changeSet.updates, comparator);
    for (QueryDocumentSnapshot update : changeSet.updates) {
      DocumentChange change = modifyDoc(update);
      if (change != null) {
        appliedChanges.add(change);
      }
    }

    return appliedChanges;
  }
1174455
public function prepareUpdateData($document)
    {
        $class = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);

        $updateData = array();
        foreach ($changeset as $fieldName => $change) {
            $mapping = $class->fieldMappings[$fieldName];

            // skip non embedded document identifiers
            if ( ! $class->isEmbeddedDocument && ! empty($mapping['id'])) {
                continue;
            }

            list($old, $new) = $change;

            // @Inc
            if ($mapping['type'] === 'increment') {
                if ($new === null) {
                    if ($mapping['nullable'] === true) {
                        $updateData['$set'][$mapping['name']] = null;
                    } else {
                        $updateData['$unset'][$mapping['name']] = true;
                    }
                } elseif ($new >= $old) {
                    $updateData['$inc'][$mapping['name']] = $new - $old;
                } else {
                    $updateData['$inc'][$mapping['name']] = ($old - $new) * -1;
                }

            // @Field, @String, @Date, etc.
            } elseif ( ! isset($mapping['association'])) {
                if (isset($new) || $mapping['nullable'] === true) {
                    $updateData['$set'][$mapping['name']] = (is_null($new) ? null : Type::getType($mapping['type'])->convertToDatabaseValue($new));
                } else {
                    $updateData['$unset'][$mapping['name']] = true;
                }

            // @EmbedOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_ONE) {
                // If we have a new embedded document then lets set the whole thing
                if ($new && $this->uow->isScheduledForInsert($new)) {
                    $updateData['$set'][$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new);

                // If we don't have a new value then lets unset the embedded document
                } elseif ( ! $new) {
                    $updateData['$unset'][$mapping['name']] = true;

                // Update existing embedded document
                } else {
                    $update = $this->prepareUpdateData($new);
                    foreach ($update as $cmd => $values) {
                        foreach ($values as $key => $value) {
                            $updateData[$cmd][$mapping['name'] . '.' . $key] = $value;
                        }
                    }
                }

            // @EmbedMany
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_MANY) {
                if (null !== $new) {
                    foreach ($new as $key => $embeddedDoc) {
                        if ( ! $this->uow->isScheduledForInsert($embeddedDoc)) {
                            $update = $this->prepareUpdateData($embeddedDoc);
                            foreach ($update as $cmd => $values) {
                                foreach ($values as $name => $value) {
                                    $updateData[$cmd][$mapping['name'] . '.' . $key . '.' . $name] = $value;
                                }
                            }
                        }
                    }
                }

            // @ReferenceOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isOwningSide']) {
                if (isset($new) || $mapping['nullable'] === true) {
                    $updateData['$set'][$mapping['name']] = (is_null($new) ? null : $this->prepareReferencedDocumentValue($mapping, $new));
                } else {
                    $updateData['$unset'][$mapping['name']] = true;
                }

            // @ReferenceMany
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_MANY) {
                // Do nothing right now
            }
        }
        return $updateData;
    }
532098
function(document, callback) {
          parentId = document.parentId
          collectionName = document.parentType

          var collection = db.collection(collectionName)
            , push = {}
          push[embeddedCollectionName] = document
          collection.findAndModify({ query: { _id: parentId }, update: { $push: push }, new: true}, function(err, oldDoc) {
            callback(document)
            ChangeDispatch.notifyIdChange(parentId, document, "insert", collectionName, embeddedCollectionName)
          })
        }
1158131
public function setOriginalDocumentData($document, array $data)
    {
        $oid                              = spl_object_hash($document);
        $this->originalDocumentData[$oid] = $data;

        unset($this->documentChangeSets[$oid]);
    }
519602
public function refresh(object $document) : void
    {
        assert($this->collection instanceof Collection);
        $query = $this->getQueryForDocument($document);
        $data  = $this->collection->findOne($query);
        if ($data === null) {
            throw MongoDBException::cannotRefreshDocument();
        }
        $data = $this->hydratorFactory->hydrate($document, (array) $data);
        $this->uow->setOriginalDocumentData($document, $data);
    }
267239
public function markChanged(): void
    {
        $this->changed = true;
        $this->xliff->setDate(new \DateTime());
        if (!$this->buffering) {
            $this->xliff->save($this->filename);
        }
    }
753834
public function get_document_recordset($modifiedfrom = 0, \context $context = null) {
        global $DB;

        // Prepare query conditions.
        $where = 'timemodified >= ? AND deleted = ? AND confirmed = ?';
        $params = [$modifiedfrom, 0, 1];

        // Handle context types.
        if (!$context) {
            $context = \context_system::instance();
        }
        switch ($context->contextlevel) {
            case CONTEXT_MODULE:
            case CONTEXT_BLOCK:
            case CONTEXT_COURSE:
            case CONTEXT_COURSECAT:
                // These contexts cannot contain any users.
                return null;

            case CONTEXT_USER:
                // Restrict to specific user.
                $where .= ' AND id = ?';
                $params[] = $context->instanceid;
                break;

            case CONTEXT_SYSTEM:
                break;

            default:
                throw new \coding_exception('Unexpected contextlevel: ' . $context->contextlevel);
        }

        return $DB->get_recordset_select('user', $where, $params);
    }
1236000
public function references($document)
    {
        if ($this->currentField) {
            $mapping = $this->class->getFieldMapping($this->currentField);
            $dbRef = $this->dm->createDBRef($document, $mapping);

            if (isset($mapping['simple']) && $mapping['simple']) {
                $this->query[$mapping['name']] = $dbRef;
            } else {
                $keys = array('ref' => true, 'id' => true, 'db' => true);

                if (isset($mapping['targetDocument'])) {
                    unset($keys['ref'], $keys['db']);
                }

                foreach ($keys as $key => $value) {
                    $this->query[$this->currentField . '.$' . $key] = $dbRef['$' . $key];
                }
            }
        } else {
            $dbRef = $this->dm->createDBRef($document);
            $this->query = $dbRef;
        }

        return $this;
    }
842402
private function computeAssociationChanges($document, $class, $oid, $isNew, $changeSet, $assocType)
    {
        switch ($assocType) {
            case 'reference':
                $mappings = $class->referenceMappings;
                $computeMethod = 'computeReferenceChanges';
                break;
            case 'referrer':
                $mappings = $class->referrersMappings;
                $computeMethod = 'computeReferrerChanges';
                break;
            default:
                throw new InvalidArgumentException('Unsupported association type used: '.$assocType);
        }

        foreach ($mappings as $fieldName) {
            $mapping = $class->mappings[$fieldName];

            if ((ClassMetadata::MANY_TO_MANY === $mapping['type'] && 'reference' === $assocType)
                || ('referrers' === $mapping['type'] && 'referrer' === $assocType)
            ) {
                if ($changeSet[$fieldName] instanceof PersistentCollection) {
                    if (!$changeSet[$fieldName]->isInitialized()) {
                        continue;
                    }
                } else {
                    if (null === $changeSet[$fieldName]) {
                        $changeSet[$fieldName] = [];
                    }

                    if (!is_array($changeSet[$fieldName]) && !$changeSet[$fieldName] instanceof Collection) {
                        throw PHPCRException::associationFieldNoArray(
                            self::objToStr($document, $this->dm),
                            $fieldName
                        );
                    }

                    // convert to a PersistentCollection
                    switch ($assocType) {
                        case 'reference':
                            $targetDocument = $mapping['targetDocument'] ?? null;
                            $changeSet[$fieldName] = ReferenceManyCollection::createFromCollection(
                                $this->dm,
                                $document,
                                $mapping['property'],
                                $changeSet[$fieldName],
                                $targetDocument,
                                !$isNew
                            );
                            break;
                        case 'referrer':
                            $referringMeta = $this->dm->getClassMetadata($mapping['referringDocument']);
                            $referringField = $referringMeta->mappings[$mapping['referencedBy']];

                            $changeSet[$fieldName] = ReferrersCollection::createFromCollection(
                                $this->dm,
                                $document,
                                $changeSet[$fieldName],
                                $referringField['strategy'],
                                $referringField['property'],
                                $mapping['referringDocument'],
                                !$isNew
                            );
                            break;
                    }

                    $class->setFieldValue($document, $fieldName, $changeSet[$fieldName]);
                    $this->originalData[$oid][$fieldName] = $changeSet[$fieldName];
                }

                $coid = spl_object_hash($changeSet[$fieldName]);
                $this->visitedCollections[$coid] = $changeSet[$fieldName];

                foreach ($changeSet[$fieldName] as $association) {
                    if ($association !== null) {
                        $this->$computeMethod($mapping, $association);
                    }
                }

                if (!$isNew && $mapping['cascade'] & ClassMetadata::CASCADE_REMOVE) {
                    if (!$this->originalData[$oid][$fieldName] instanceof PersistentCollection) {
                        throw new RuntimeException('OriginalData for a collection association contains something else than a PersistentCollection.');
                    }

                    $associations = $this->originalData[$oid][$fieldName]->getOriginalPaths();
                    foreach ($associations as $association) {
                        $association = $this->getDocumentById($association);
                        if ($association && !$this->originalData[$oid][$fieldName]->contains($association)) {
                            $this->scheduleRemove($association);
                        }
                    }
                }
            } elseif ($changeSet[$fieldName] && ClassMetadata::MANY_TO_ONE === $mapping['type'] && 'reference' === $assocType) {
                $this->computeReferenceChanges($mapping, $changeSet[$fieldName]);
            }
        }
    }
181545
private function cascadePreUpdate(ClassMetadata $class, object $document) : void
    {
        foreach ($class->getEmbeddedFieldsMappings() as $mapping) {
            $value = $class->reflFields[$mapping['fieldName']]->getValue($document);
            if ($value === null) {
                continue;
            }
            $values = $mapping['type'] === ClassMetadata::ONE ? [$value] : $value;

            foreach ($values as $entry) {
                if ($this->uow->isScheduledForInsert($entry) || empty($this->uow->getDocumentChangeSet($entry))) {
                    continue;
                }
                $this->preUpdate($this->dm->getClassMetadata(get_class($entry)), $entry);
            }
        }
    }
7843
public function addChangeSet($tracked,$eventMask)
    {
        if($tracked instanceof TrackedObject){
            $path = $tracked->getResource();
            if($this->fileOnly && !$tracked->getResource() instanceof FileResource){
                return;
            }
        }else{
            $path = $tracked;
        }
        $event = new FilesystemEvent($path,$eventMask);
        $id = md5($path);
        $this->changeSet[$id] = $event;
    }
273004
private function doRefresh($document, array &$visited)
    {
        $oid = spl_object_hash($document);
        if (isset($visited[$oid])) {
            return; // Prevent infinite recursion
        }

        $visited[$oid] = $document; // mark visited

        $class = $this->dm->getClassMetadata(get_class($document));

        if (!$class->isEmbeddedDocument) {
            if ($this->getDocumentState($document) !== self::STATE_MANAGED) {
                throw new \InvalidArgumentException('Document is not MANAGED.');
            }

            $identifier = $this->documentIdentifiers[$oid];
            $this->getDocumentPersister($class->name)->refresh($identifier, $document);
        }

        $this->cascadeRefresh($document, $visited);
    }
495989
public function scheduleForUpsert(ClassMetadata $class, object $document) : void
    {
        $oid = spl_object_hash($document);

        if ($class->isEmbeddedDocument) {
            throw new InvalidArgumentException('Embedded document can not be scheduled for upsert.');
        }
        if (isset($this->documentUpdates[$oid])) {
            throw new InvalidArgumentException('Dirty document can not be scheduled for upsert.');
        }
        if (isset($this->documentDeletions[$oid])) {
            throw new InvalidArgumentException('Removed document can not be scheduled for upsert.');
        }
        if (isset($this->documentUpserts[$oid])) {
            throw new InvalidArgumentException('Document can not be scheduled for upsert twice.');
        }

        $this->documentUpserts[$oid]     = $document;
        $this->documentIdentifiers[$oid] = $class->getIdentifierValue($document);
        $this->addToIdentityMap($document);
    }