Insert document

@param  array $document
@return mixed
178108
protected function _insert(&$document) {

        $table           = $this->name;
        $document['_id'] = isset($document['_id']) ? $document['_id'] : createMongoDbLikeId();
        $data            = ['document' => \json_encode($document, JSON_UNESCAPED_UNICODE)];

        $fields = [];
        $values = [];

        foreach($data as $col=>$value){
            $fields[] = "`{$col}`";
            $values[] = (\is_null($value) ? 'NULL' : $this->database->connection->quote($value));
        }

        $fields = \implode(',', $fields);
        $values = \implode(',', $values);

        $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
        $res = $this->database->connection->exec($sql);

        if ($res){
            return $this->database->connection->lastInsertId();
        } else {
            trigger_error('SQL Error: '.\implode(', ', $this->database->connection->errorInfo()).":\n".$sql);
            return false;
        }
    }
1034095
public function prepareUpdateData($document)
    {
        $class     = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);

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

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

            [$old, $new] = $change;

            // Scalar fields
            if (! isset($mapping['association'])) {
                if ($new === null && $mapping['nullable'] !== true) {
                    $updateData['$unset'][$mapping['name']] = true;
                } else {
                    if ($new !== null && isset($mapping['strategy']) && $mapping['strategy'] === ClassMetadata::STORAGE_STRATEGY_INCREMENT) {
                        $operator = '$inc';
                        $value    = Type::getType($mapping['type'])->convertToDatabaseValue($new - $old);
                    } else {
                        $operator = '$set';
                        $value    = $new === null ? null : Type::getType($mapping['type'])->convertToDatabaseValue($new);
                    }

                    $updateData[$operator][$mapping['name']] = $value;
                }

            // @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;
                        }
                    }
                }

            // @ReferenceMany, @EmbedMany
            } elseif (isset($mapping['association']) && $mapping['type'] === 'many' && $new) {
                if (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForUpdate($new)) {
                    $updateData['$set'][$mapping['name']] = $this->prepareAssociatedCollectionValue($new, true);
                } elseif (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForDeletion($new)) {
                    $updateData['$unset'][$mapping['name']] = true;
                    $this->uow->unscheduleCollectionDeletion($new);
                } elseif (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForDeletion($old)) {
                    $updateData['$unset'][$mapping['name']] = true;
                    $this->uow->unscheduleCollectionDeletion($old);
                } elseif ($mapping['association'] === ClassMetadata::EMBED_MANY) {
                    foreach ($new as $key => $embeddedDoc) {
                        if ($this->uow->isScheduledForInsert($embeddedDoc)) {
                            continue;
                        }

                        $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) {
                if (isset($new) || $mapping['nullable'] === true) {
                    $updateData['$set'][$mapping['name']] = $new === null ? null : $this->prepareReferencedDocumentValue($mapping, $new);
                } else {
                    $updateData['$unset'][$mapping['name']] = true;
                }
            }
        }
        // collections that aren't dirty but could be subject to update are
        // excluded from change set, let's go through them now
        foreach ($this->uow->getScheduledCollections($document) as $coll) {
            $mapping = $coll->getMapping();
            if (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForUpdate($coll)) {
                $updateData['$set'][$mapping['name']] = $this->prepareAssociatedCollectionValue($coll, true);
            } elseif (CollectionHelper::isAtomic($mapping['strategy']) && $this->uow->isCollectionScheduledForDeletion($coll)) {
                $updateData['$unset'][$mapping['name']] = true;
                $this->uow->unscheduleCollectionDeletion($coll);
            }
            // @ReferenceMany is handled by CollectionPersister
        }
        return $updateData;
    }
813881
public function attach($document)
    {
        if (isset($this->connection)) {
            $document = $this->connection->unmarshall($document);
        }

        // wrap document as NObject instance to make sure it can be override by hooks
        $document = new NObject($document);

        $this->applyHook('attaching', $document);

        if (isset($this->options['model'])) {
            $Model = $this->options['model'];
            $model = new $Model($document->toArray(), array(
                'collection' => $this,
            ));
        } else {
            $model = new Model($document->toArray(), array(
                'collection' => $this,
            ));
        }

        $this->applyHook('attached', $model);

        return $model;
    }
1315666
public function add($documents)
    {
        if (!is_array($documents)) {
            $documents = array($documents);
        }

        $add =& Archive::getByRef($this, 'add', array());
        foreach ($documents as $document) {
            $add[] = $document;
        }
    }
364394
public function updateDocument(\Document $document)
  {
    $arrSet = $this->buildDocumentDataArray($document, false);
    
    $this->Database->prepare("UPDATE tl_dms_documents %s WHERE id=?")->set($arrSet)->execute($document->id);
    
    return $document;
  }
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;
    }
322791
def insert(self, **kwargs):
        
        if self.is_valid:
            before = self.before_insert()
            if before:
                return before

            try:
                self._document['_id'] = self.insert_one(self._document)

                self.after_insert()

                return self._document
            except PyMongoException as exc:
                return PyMongoError(
                    error_message=exc.details.get(
                        'errmsg', exc.details.get('err', 'PyMongoError.')
                    ),
                    operation='insert', collection=type(self).__name__,
                    document=self._document,
                )

        return self._errors
369721
public function includeFiles($document)
    {
        $environment = $this->getEnvironment();
        $parser = $this;

        return preg_replace_callback('/^\.\. include:: (.+)$/m', function($match) use ($parser, $environment) {
            $path = $environment->absoluteRelativePath($match[1]);
            if ($parser->includeFileAllowed($path)) {
                return $parser->includeFiles(file_get_contents($path));
            } else {
                return '';
            }
        }, $document);
    }
1245897
public function insertFileUploadFolders(array $collection) {
		$timeStamp = microtime(true);

		$countInserts = 0;
		$insertedItems = [];
		foreach($collection as $data){
			if($data instanceof BundleEntity\FileUploadFolder){
				$entity = $data;
				$this->em->persist($entity);
				$insertedItems[] = $entity;
				$countInserts++;
			}
			else if(is_object($data)){
				$entity = new BundleEntity\FileUploadFolder();
				foreach($data as $column => $value){
					$set = 'set'.$this->translateColumnName($column);
					switch($column){
						case 'site':
							$sModel = $this->kernel->getContainer()->get('sitemanagement.model');
							$response = $sModel->getSite($value);
							if(!$response->error->exist){
								$entity->$set($response->result->set);
							}
							unset($response, $sModel);
							break;
						default:
							$entity->$set($value);
							break;
					}
				}
				$this->em->persist($entity);
				$insertedItems[] = $entity;
				$countInserts++;
			}
		}
		if($countInserts > 0){
			$this->em->flush();
			return new ModelResponse($insertedItems, $countInserts, 0, null, false, 'S:D:003', 'Selected entries have been successfully inserted into database.', $timeStamp, microtime(true));
		}
		return new ModelResponse(null, 0, 0, null, true, 'E:D:003', 'One or more entities cannot be inserted into database.', $timeStamp, microtime(true));
	}
1247901
protected function writeMultipartDocument( array $document )
    {
        $body = json_encode( $document );

        $boundary = $this->getBoundary();
        fwrite( $this->stream, "Content-ID: " . $document['_id'] . "\r\n" );
        fwrite( $this->stream, "Content-Type: multipart/mixed; boundary=\"" . $boundary . "\"\r\n\r\n" );
 
        $attachments = $document['_attachments'];
        unset( $document['_attachments'] );

        // Write document first
        fwrite( $this->stream, "--" . $boundary . "\r\n" );
        $body = json_encode( $document );

        fwrite( $this->stream, "Content-Length: " . strlen( $body ) . "\r\n" );
        fwrite( $this->stream, "Content-Type: application/json\r\n" );
        fwrite( $this->stream, "\r\n" );
        fwrite( $this->stream, "$body\r\n" );

        // Write all attachments
        foreach ( $attachments as $name => $attachment )
        {
            fwrite( $this->stream, "--" . $boundary . "\r\n" );
            $body = $attachment['data'];

            fwrite( $this->stream, "Content-ID: " . $name . "\r\n" );
            fwrite( $this->stream, "Content-Length: " . strlen( $body ) . "\r\n" );
            fwrite( $this->stream, "Content-Type: " . $attachment['content_type'] . "\r\n" );
            fwrite( $this->stream, "\r\n" );
            fwrite( $this->stream, "$body\r\n" );
        }

        // End of multipart/mixed data
        fwrite( $this->stream, "--" . $boundary . "--\r\n" );
    }
861786
def add_insert(self, document):
        
        validate_is_document_type("document", document)
        # Generate ObjectId client side.
        if not (isinstance(document, RawBSONDocument) or '_id' in document):
            document['_id'] = ObjectId()
        self.ops.append((_INSERT, document))
1237054
public function add(array $data) {

        try {

            $document = (new Visitor($data))->toArray();

            $this->collection->insert($document, ['w' => true]);

            return new \MongoId($document['_id']);
        }
        catch (\MongoCursorException $e) {
            throw new MongoMapperException($e->getMessage());
        }
        catch (\MongoException $e) {
            throw new MongoMapperException($e->getMessage());
        }
    }
1195152
protected function toTableRow(array $doc)
    {
        $result = isset($doc['value']) ? $doc['value'] : [];
        if (isset($result[_IMPACT_INDEX])) {
            unset($result[_IMPACT_INDEX]);
        }
        return $result;
    }
510787
private function buildAggregateAsObject($document)
    {
        $returnObject = [];

        foreach ($document as $event) {
            $returnObject[] = new Event(
                new AggregateUuid($event->uuid),
                $event->type,
                unserialize($event->body),
                $event->version,
                $event->occurred_on
            );
        }

        return $returnObject;
    }
856477
public function insertFiles(array $collection)	{
		$timeStamp = microtime(true);
		/** Parameter must be an array */
		$countInserts = 0;
		$countLocalizations = 0;
		$insertedItems = [];
		$localizations = [];
		foreach ($collection as $data) {
			if ($data instanceof BundleEntity\File) {
				$entity = $data;
				$this->em->persist($entity);
				$insertedItems[] = $entity;
				$countInserts++;
			}
			else if (is_object($data)) {
				$entity = new BundleEntity\File;
				if(!property_exists($data, 'site')){
					$data->site = 1;
				}
				if(!property_exists($data, 'folder')){
					$data->folder = 1;
				}
				foreach ($data as $column => $value) {
					$localeSet = false;
					$set = 'set' . $this->translateColumnName($column);
					switch ($column) {
						case 'local':
							$localizations[$countInserts]['localizations'] = $value;
							$localeSet = true;
							$countLocalizations++;
							break;
						case 'site':
							$sModel = $this->kernel->getContainer()->get('sitemanagement.model');
							$response = $sModel->getSite($value);
							if(!$response->error->exist){
								$entity->$set($response->result->set);
							}
							unset($response, $sModel);
							break;
						case 'folder':
							$response = $this->getFileUploadFolder($value);
							if(!$response->error->exist){
								$entity->$set($response->result->set);
							}
							unset($response);
							break;
						default:
							$entity->$set($value);
							break;
					}
					if ($localeSet) {
						$localizations[$countInserts]['entity'] = $entity;
					}
				}
				$this->em->persist($entity);
				$insertedItems[] = $entity;

				$countInserts++;
			}
		}
		if ($countInserts > 0) {
			$this->em->flush();
		}
		/** Now handle localizations */
		if ($countInserts > 0 && $countLocalizations > 0) {
			$response = $this->insertFileLocalizations($localizations);
		}
		if($countInserts > 0){
			$this->em->flush();
			return new ModelResponse($insertedItems, $countInserts, 0, null, false, 'S:D:003', 'Selected entries have been successfully inserted into database.', $timeStamp, microtime(true));
		}
		return new ModelResponse(null, 0, 0, null, true, 'E:D:003', 'One or more entities cannot be inserted into database.', $timeStamp, microtime(true));
	}
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();
    }
96917
public function writeDocument( array $document )
    {
        fwrite( $this->stream, "--" . $this->boundary . "\r\n" );
        if ( isset( $document['_attachments'] ) )
        {
            $this->writeMultipartDocument( $document );
        }
        else
        {
            $this->writeSimpleDocument( $document );
        }
    }