Store document to pool

@param array $document
@return \Sokil\Mongo\Collection
196601
public function addDocumentToDocumentPool(Document $document)
    {
        $documentId = (string) $document->getId();

        if (!isset($this->documentPool[$documentId])) {
            $this->documentPool[$documentId] = $document;
        } else {
            // merging because document after
            // load and before getting in second place may be changed
            // and this changes must be preserved:
            //
            // 1. Document loads and modifies in current session
            // 2. Document loads modified in another session
            // 3. Document loads once again in current session. Changes from stage 2 merges as unmodified

            $this->documentPool[$documentId]->mergeUnmodified($document->toArray());
        }

        return $this;
    }
96793
protected function addDocumentsToSolrIndex(array $documents)
    {
        $documentsAdded = false;

        if (!count($documents)) {
            return $documentsAdded;
        }

        try {
            $this->logger->log(SolrLogManager::INFO, 'Adding ' . count($documents) . ' documents.', $documents);

            // chunk adds by 20
            $documentChunks = array_chunk($documents, 20);
            foreach ($documentChunks as $documentChunk) {
                $response = $this->solrConnection->getWriteService()->addDocuments($documentChunk);
                if ($response->getHttpStatus() != 200) {
                    throw new \RuntimeException('Solr Request failed.', 1331834983);
                }
            }

            $documentsAdded = true;
        } catch (\Exception $e) {
            $this->logger->log(SolrLogManager::ERROR, $e->getMessage() . ' Error code: ' . $e->getCode());

            if ($this->configuration->getLoggingExceptions()) {
                $this->logger->log(SolrLogManager::ERROR, 'Exception while adding documents', [$e->__toString()]);
            }
        }

        return $documentsAdded;
    }
932541
public function prepareInsertData($document)
    {
        $class     = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);

        $insertData = [];
        foreach ($class->fieldMappings as $mapping) {
            $new = $changeset[$mapping['fieldName']][1] ?? null;

            if ($new === null && $mapping['nullable']) {
                $insertData[$mapping['name']] = null;
            }

            /* Nothing more to do for null values, since we're either storing
             * them (if nullable was true) or not.
             */
            if ($new === null) {
                continue;
            }

            // @Field, @String, @Date, etc.
            if (! isset($mapping['association'])) {
                $insertData[$mapping['name']] = Type::getType($mapping['type'])->convertToDatabaseValue($new);

            // @ReferenceOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE) {
                $insertData[$mapping['name']] = $this->prepareReferencedDocumentValue($mapping, $new);

            // @EmbedOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_ONE) {
                $insertData[$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new);

            // @ReferenceMany, @EmbedMany
            // We're excluding collections using addToSet since there is a risk
            // of duplicated entries stored in the collection
            } elseif ($mapping['type'] === ClassMetadata::MANY && ! $mapping['isInverseSide']
                    && $mapping['strategy'] !== ClassMetadata::STORAGE_STRATEGY_ADD_TO_SET && ! $new->isEmpty()) {
                $insertData[$mapping['name']] = $this->prepareAssociatedCollectionValue($new, true);
            }
        }

        // add discriminator if the class has one
        if (isset($class->discriminatorField)) {
            $discriminatorValue = $class->discriminatorValue;

            if ($discriminatorValue === null) {
                if (! empty($class->discriminatorMap)) {
                    throw MappingException::unlistedClassInDiscriminatorMap($class->name);
                }

                $discriminatorValue = $class->name;
            }

            $insertData[$class->discriminatorField] = $discriminatorValue;
        }

        return $insertData;
    }
1066700
public static function bulkUpdate($documents)
    {
        $instance = new static();

        $primaryKey = $instance->getPrimaryKey();
        $allowNull = $instance->isAllowNullValue();
        $fieldTypes = $instance->getFieldTypes();
        foreach ($documents as $i => $document) {
            if (!isset($document[$primaryKey])) {
                throw new InvalidValueException(['bulkUpdate `:model` model must set primary value', 'model' => static::class]);
            }
            foreach ((array)$document as $field => $value) {
                if ($value === null) {
                    $document[$field] = $allowNull ? null : $instance->normalizeValue($fieldTypes[$field], '');
                } else {
                    $document[$field] = $instance->normalizeValue($fieldTypes[$field], $value);
                }
            }
        }

        /**
         * @var \ManaPHP\MongodbInterface $connection
         */
        $connection = $instance->getConnection();
        return $connection->bulkUpdate($instance->getSource(), $documents, $primaryKey);
    }
1210253
public function getObjectPropertyAnnotations($document)
    {
        $cacheKey = "object_property_annotations_" . get_class($document);
        if (!$this->cache->contains($cacheKey)) {
            $refObject   = new \ReflectionObject($document);
            $annotations = array();
            foreach ($refObject->getProperties() as $property) {
                $annotation = $this->getPropertyAnnotation($property);
                if ($annotation) {
                    $annotations[$property->getName()] = $annotation;
                }
            }
            $this->cache->save($cacheKey, $annotations);
        }
        return $this->cache->fetch($cacheKey);
    }
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;
    }
677457
private function buildAggregateAsArray($document)
    {
        $returnArray = [];

        foreach ($document as $event) {
            $returnArray[] = [
                'uuid' => (string) $event->uuid,
                'version' => $event->version,
                'payload' => $event->payload,
                'type' => $event->type,
                'body' => unserialize($event->body),
                'occurred_on' => $event->occurred_on
            ];
        }

        return $returnArray;
    }
418429
public static function bulkUpsert($documents)
    {
        $instance = new static();

        $primaryKey = $instance->getPrimaryKey();
        $allowNull = $instance->isAllowNullValue();
        $fieldTypes = $instance->getFieldTypes();
        foreach ($documents as $i => $document) {
            if (!isset($document[$primaryKey])) {
                $document[$primaryKey] = $instance->getNextAutoIncrementId();
            }
            foreach ((array)$fieldTypes as $field => $type) {
                if (isset($document[$field])) {
                    $document[$field] = $instance->normalizeValue($type, $document[$field]);
                } elseif ($field !== '_id') {
                    $document[$field] = $allowNull ? null : $instance->normalizeValue($type, '');
                }
            }
            $documents[$i] = $document;
        }

        /**
         * @var \ManaPHP\MongodbInterface $connection
         */
        $connection = $instance->getConnection();
        return $connection->bulkUpsert($instance->getSource(), $documents, $primaryKey);
    }
999125
private function generate(array $doc)
    {
        $this->xml->openMemory();
        $this->xml->setIndentString(str_repeat(' ', 4));
        $this->xml->setIndent(true);

        $this->xml->startDocument('1.0', 'UTF-8');

        foreach ($doc as $name => $element) {
            $this->buildElement($this->xml, $name, $element);
        }

        $this->xml->endElement();
        return $this->xml->outputMemory();
    }
553017
public function setDocument(\Innova\CollecticielBundle\Entity\Document $document)
    {
        $this->document = $document;

        return $this;
    }
137592
public function insertOne($document, $options = [])
    {
        $query = new InsertOne($this->documentManager, $this, $document, $options);
        if (isset($options['getQuery']) && $options['getQuery']) {
            return $query;
        } else {
            return $query->execute();
        }
    }
282449
protected function docToArray(array $doc)
    {
        $values = [];

        foreach ($doc as $key => $value) {

            if ( ! is_array($value)) {
                $values[$key][] = $value;

                continue;
            }

            $values[$key] = $value;
        }

        return $values;
    }
881747
public function createDocument(array $data = null)
    {
        $className = $this->getDocumentClassName($data);

        /* @var $document \Sokil\Mongo\Document */
        $document = new $className(
            $this,
            $data,
            array('stored' => false) + $this->definition->getOptions()
        );

        // store document to identity map
        if ($this->isDocumentPoolEnabled()) {
            $collection = $this;
            $document->onAfterInsert(function (\Sokil\Mongo\Event $event) use ($collection) {
                $collection->addDocumentToDocumentPool($event->getTarget());
            });
        }

        return $document;
    }
823576
public function commit($document = null)
    {
        $this->invokeGlobalEvent(Event::preFlush, new ManagerEventArgs($this->dm));

        if ($document === null) {
            $this->computeChangeSets();
        } elseif (is_object($document)) {
            $this->computeSingleDocumentChangeSet($document);
        } elseif (is_array($document)) {
            foreach ($document as $object) {
                $this->computeSingleDocumentChangeSet($object);
            }
        }

        $this->invokeGlobalEvent(Event::onFlush, new ManagerEventArgs($this->dm));

        if (empty($this->scheduledInserts)
            && empty($this->scheduledUpdates)
            && empty($this->scheduledRemovals)
            && empty($this->scheduledReorders)
            && empty($this->documentTranslations)
            && empty($this->scheduledMoves)
        ) {
            $this->invokeGlobalEvent(Event::postFlush, new ManagerEventArgs($this->dm));
            $this->changesetComputed = [];

            return; // Nothing to do.
        }

        try {
            $utx = $this->session->getWorkspace()->getTransactionManager();
            if ($utx->inTransaction()) {
                $utx = null;
            } else {
                $utx->begin();
            }
        } catch (UnsupportedRepositoryOperationException $e) {
            $utx = null;
        }

        try {
            $this->executeInserts($this->scheduledInserts);

            $this->executeUpdates($this->scheduledUpdates);

            $this->executeRemovals($this->scheduledRemovals);

            $this->executeReorders($this->scheduledReorders);

            $this->executeMoves($this->scheduledMoves);

            $this->session->save();

            if ($utx) {
                $utx->commit();
            }
        } catch (\Exception $e) {
            try {
                $this->dm->close();

                if ($utx) {
                    $utx->rollback();
                }
            } catch (\Exception $innerException) {
                //TODO: log error while closing dm after error: $innerException->getMessage
            }

            throw $e;
        }

        foreach ($this->visitedCollections as $col) {
            $col->takeSnapshot();
        }

        $this->invokeGlobalEvent(Event::postFlush, new ManagerEventArgs($this->dm));

        if (null === $document) {
            foreach ($this->documentLocales as $oid => $locales) {
                $this->documentLocales[$oid]['original'] = $locales['current'];
            }
        } else {
            $documents = is_array($document) ? $document : [$document];
            foreach ($documents as $doc) {
                $oid = spl_object_hash($doc);
                if (isset($this->documentLocales[$oid])) {
                    $this->documentLocales[$oid]['original'] = $this->documentLocales[$oid]['current'];
                }
            }
        }

        $this->scheduledUpdates =
        $this->scheduledRemovals =
        $this->scheduledMoves =
        $this->scheduledReorders =
        $this->scheduledInserts =
        $this->visitedCollections =
        $this->documentChangesets =
        $this->changesetComputed = [];

        $this->invokeGlobalEvent(Event::endFlush, new ManagerEventArgs($this->dm));
    }
201676
function(mongo_host, db, collection) {

    var arrayMongo = function() {
    };

    arrayMongo.prototype = Array.prototype;

    extend(arrayMongo.prototype, {
        /**
         * Store the parameters
         */
        host: function() {
            return mongo_host;
        },
        db: function() {
            return db;
        },
        mongoCollection: function() {
            return collection;
        },
        load: function(finished) {
            console.log('HERE');
            var self = this;
            var cname = this.mongoCollection();
            mongoCache.getConnection(this.host(), this.db(), (function(err, db) {
                if(err) return;
                var collection = db.collection(cname);
                collection.find().toArray(function(err, docs) {
                    if(err || docs.length < 1) {
                        finished();
                        return;
                    }

                    // Copy all the documents in the array
                    docs.forEach(function(doc) {
                        self.push(doc);
                    });
                    finished();
                }.bind(this));
            }).bind(this));
        },
        save: function() {
            var self = this;
            var cname = this.mongoCollection();
            mongoCache.getConnection(this.host(), this.db(), (function(err, db) {
                if(err) return;
                var collection = db.collection(cname);
                self.forEach(function(element) {
                    if(element['_id']) {
                        collection.update({_id: element['_id']}, element, function(){
                        });
                    }
                    else {
                        collection.insert(element, function(){
                        });
                    }
                });
            }).bind(this));
        }
    });

    // Create instance and return it
    return new arrayMongo();
}
114222
public function deserialize($document)
    {
        $goalStateInfo = Utilities::unserialize($document);

        return new GoalState(
            $goalStateInfo['Incarnation'],
            $goalStateInfo['ExpectedState'],
            $goalStateInfo['RoleEnvironmentPath'],
            new \DateTime($goalStateInfo['Deadline']),
            $goalStateInfo['CurrentStateEndpoint']
        );
    }
523163
protected function convertDirectives(DocumentAST $document): Collection
    {
        return $document->directiveDefinitions()
            ->map(function (DirectiveDefinitionNode $directive) {
                return new Directive([
                    'name' => $directive->name->value,
                    'description' => data_get($directive->description, 'value'),
                    'locations' => (new Collection($directive->locations))
                        ->map(function ($location) {
                            return $location->value;
                        })
                        ->toArray(),
                    'args' => (new Collection($directive->arguments))
                        ->map(function (InputValueDefinitionNode $argument) {
                            $fieldArgumentConfig = [
                                'name' => $argument->name->value,
                                'description' => data_get($argument->description, 'value'),
                                'type' => $this->definitionNodeConverter->toType($argument->type),
                            ];

                            if ($defaultValue = $argument->defaultValue) {
                                $fieldArgumentConfig += [
                                    'defaultValue' => $defaultValue,
                                ];
                            }

                            return new FieldArgument($fieldArgumentConfig);
                        })
                        ->toArray(),
                    'astNode' => $directive,
                ]);
            });
    }