Inserts a document into the chunks collection.

@param array|object $chunk Chunk document
774543
public function insertChunk($chunk)
    {
        if ( ! $this->checkedIndexes) {
            $this->ensureIndexes();
        }

        $this->chunksCollection->insertOne($chunk);
    }
835122
public function setDocuments(array $documents)
    {
        if (count($documents) > 0) {
            foreach ($documents as $document) {
                if ($document instanceof PagSeguroSenderDocument) {
                    $this->documents[] = $document;
                } else if (is_array($document)) {
                        $this->addDocument($document['type'], $document['value']);
                }
            }
        }
    }
398638
private function validateRowInProgress(CellChunk $chunk)
    {
        $this->validateResetRow($chunk);
        $newRowKey = $chunk->getRowKey();
        $this->isError(
            $chunk->getRowKey() && $newRowKey !== $this->rowKey,
            'A commit is required between row keys.'
        );
        $this->isError(
            $chunk->getFamilyName() && !$chunk->getQualifier(),
            'A qualifier must be specified.'
        );
        $this->validateValueSizeAndCommitRow($chunk);
    }
47243
private function insertNewLine(array $token): void
    {
        $fixer = $this->file->getFixer();
        $lineStartPadding = str_pad('', $token['column'] - 3, ' ');

        $fixer->beginChangeset();

        // Remove the whitespace between the tag and the comments star.
        $fixer->replaceToken($token['pointer'] - 1, '');

        $fixer->addContentBefore(
            $token['pointer'],
            $this->file->getEolChar() . $lineStartPadding . '* '
        );

        $fixer->endChangeset();
    }
1073734
public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){

		//ignore adding empty strings
		if( $chunk === '' ){
			return;
		}


		$sourceLines = array();
		$sourceColumns = ' ';


		if( $fileInfo ){

			$url = $fileInfo['currentUri'];

			if( isset($this->contentsMap[$url]) ){
				$inputSource = substr($this->contentsMap[$url], 0, $index);
				$sourceLines = explode("\n", $inputSource);
				$sourceColumns = end($sourceLines);
			}else{
				throw new Exception('Filename '.$url.' not in contentsMap');
			}

		}

		$lines = explode("\n", $chunk);
		$columns = end($lines);

		if($fileInfo){

			if(!$mapLines){
				$this->generator->addMapping(
						$this->lineNumber + 1,					// generated_line
						$this->column,							// generated_column
						count($sourceLines),					// original_line
						strlen($sourceColumns),					// original_column
						$fileInfo
				);
			}else{
				for($i = 0, $count = count($lines); $i < $count; $i++){
					$this->generator->addMapping(
						$this->lineNumber + $i + 1,				// generated_line
						$i === 0 ? $this->column : 0,			// generated_column
						count($sourceLines) + $i,				// original_line
						$i === 0 ? strlen($sourceColumns) : 0, 	// original_column
						$fileInfo
					);
				}
			}
		}

		if(count($lines) === 1){
			$this->column += strlen($columns);
		}else{
			$this->lineNumber += count($lines) - 1;
			$this->column = strlen($columns);
		}

		// add only chunk
		parent::add($chunk);
	}
1163126
protected function addToDocument($document)
    {
        parent::addToDocument($document);

        $this->getRangeKey()->getPropertyMetadata()->setValue(
            $document,
            $this->getRangeValue()
        );
    }
187017
public function add($documents)
    {

        $pendingRemove = $this->getRemove();
        if ($this->getRemove()) {
            if ($this->all()) {
                throw new \RuntimeException('Adding to group with pending remove is not permitted');
            } else {
                $this->clearAdd();
                $this->clearRemove();
                $this->saved = array();
            }
        }
        if (!is_array($documents)) {
            $documents = array($documents);
        }

        $add =& $this->getArchive()->getByRef('add', array());
        foreach ($documents as $document) {
            $add[] = $document;
        }
    }
568883
public function insert(&$document) {

        if (isset($document[0])) {

            $this->database->connection->beginTransaction();

            foreach ($document as &$doc) {

                if (!\is_array($doc)) continue;

                $res = $this->_insert($doc);

                if (!$res) {
                    $this->database->connection->rollBack();
                    return $res;
                }
            }
            $this->database->connection->commit();
            return \count($document);
        } else {
            return $this->_insert($document);
        }
    }
387790
void insertMany(final MongoNamespace namespace,
                  final List<BsonDocument> documents) {
    this.waitUntilInitialized();

    try {
      ongoingOperationsGroup.enter();
      // Remove forbidden fields from the documents before inserting them into the local collection.
      final List<BsonDocument> docsForStorage = new ArrayList<>(documents.size());

      for (final BsonDocument document : documents) {
        docsForStorage.add(sanitizeDocument(document));
      }

      final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);
      final Lock lock = nsConfig.getLock().writeLock();
      lock.lock();
      final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();
      try {
        getLocalCollection(namespace).insertMany(docsForStorage);
        for (final BsonDocument document : docsForStorage) {
          final BsonValue documentId = BsonUtils.getDocumentId(document);
          final ChangeEvent<BsonDocument> event =
              ChangeEvents.changeEventForLocalInsert(namespace, document, true);
          final CoreDocumentSynchronizationConfig config = syncConfig.addAndGetSynchronizedDocument(
              namespace,
              documentId
          );
          config.setSomePendingWritesAndSave(logicalT, event);
          eventsToEmit.add(event);
        }
      } finally {
        lock.unlock();
      }
      checkAndInsertNamespaceListener(namespace);
      for (final ChangeEvent<BsonDocument> event : eventsToEmit) {
        eventDispatcher.emitEvent(nsConfig, event);
      }
    } finally {
      ongoingOperationsGroup.exit();
    }
  }
54823
private function internalInsert()
    {
        if ($this->triggerEvent(self::EVENT_NAME_BEFORE_INSERT)->isCancelled()) {
            return;
        }

        $document = $this->toArray();

        // try write document
        try {
            $this
                ->collection
                ->getMongoCollection()
                ->insert($document);
        } catch (\Exception $e) {
            throw new WriteException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }

        // set id
        $this->defineId($document['_id']);

        // after insert event
        $this->triggerEvent(self::EVENT_NAME_AFTER_INSERT);
    }
434162
private function executeInserts($documents)
    {
        // sort the documents to insert parents first but maintain child order
        $oids = [];
        foreach ($documents as $oid => $document) {
            if (!$this->contains($oid)) {
                continue;
            }

            $oids[$oid] = $this->getDocumentId($document);
        }

        $order = array_flip(array_values($oids));
        uasort($oids, function ($a, $b) use ($order) {
            // compute the node depths
            $aCount = substr_count($a, '/');
            $bCount = substr_count($b, '/');

            // ensure that the original order is maintained for nodes with the same depth
            if ($aCount === $bCount) {
                return ($order[$a] < $order[$b]) ? -1 : 1;
            }

            return ($aCount < $bCount) ? -1 : 1;
        }
        );

        $associationChangesets = $associationUpdates = [];

        foreach ($oids as $oid => $id) {
            $document = $documents[$oid];
            /** @var ClassMetadata $class */
            $class = $this->dm->getClassMetadata(get_class($document));

            // PHPCR does not validate nullable unless we would start to
            // generate custom node types, which we at the moment don't.
            // the ORM can delegate this validation to the relational database
            // that is using a strict schema
            foreach ($class->fieldMappings as $fieldName) {
                if (!isset($this->documentChangesets[$oid]['fields'][$fieldName]) // empty string is ok
                    && !$class->isNullable($fieldName)
                    && !$this->isAutocreatedProperty($class, $fieldName)
                ) {
                    throw new PHPCRException(sprintf('Field "%s" of class "%s" is not nullable', $fieldName, $class->name));
                }
            }

            $parentNode = $this->session->getNode(PathHelper::getParentPath($id));
            $this->validateChildClass($parentNode, $class);

            $nodename = PathHelper::getNodeName($id);
            $node = $parentNode->addNode($nodename, $class->nodeType);
            if ($class->node) {
                $this->originalData[$oid][$class->node] = $node;
            }
            if ($class->nodename) {
                $this->originalData[$oid][$class->nodename] = $nodename;
            }

            try {
                $node->addMixin('phpcr:managed');
            } catch (NoSuchNodeTypeException $e) {
                throw new PHPCRException('Register phpcr:managed node type first. See https://github.com/doctrine/phpcr-odm/wiki/Custom-node-type-phpcr:managed');
            }

            foreach ($class->mixins as $mixin) {
                $node->addMixin($mixin);
            }

            if ($class->identifier) {
                $class->setIdentifierValue($document, $id);
            }
            if ($class->node) {
                $class->reflFields[$class->node]->setValue($document, $node);
            }
            if ($class->nodename) {
                // make sure this reflects the id generator strategy generated id
                $class->reflFields[$class->nodename]->setValue($document, $node->getName());
            }
            // make sure this reflects the id generator strategy generated id
            if ($class->parentMapping && !$class->reflFields[$class->parentMapping]->getValue($document)) {
                $class->reflFields[$class->parentMapping]->setValue($document, $this->getOrCreateProxyFromNode($parentNode, $this->getCurrentLocale($document, $class)));
            }

            if ($this->writeMetadata) {
                $this->documentClassMapper->writeMetadata($this->dm, $node, $class->name);
            }

            $this->setMixins($class, $node, $document);

            $fields = $this->documentChangesets[$oid]['fields'] ?? [];
            foreach ($fields as $fieldName => $fieldValue) {
                // Ignore translatable fields (they will be persisted by the translation strategy)
                if (in_array($fieldName, $class->translatableFields)) {
                    continue;
                }

                if (in_array($fieldName, $class->fieldMappings)) {
                    $mapping = $class->mappings[$fieldName];
                    $type = PropertyType::valueFromName($mapping['type']);
                    if (null === $fieldValue) {
                        continue;
                    }

                    if ($mapping['multivalue'] && $fieldValue) {
                        $fieldValue = (array) $fieldValue;
                        if (isset($mapping['assoc'])) {
                            $fieldValue = $this->processAssoc($node, $mapping, $fieldValue);
                        }
                    }

                    $node->setProperty($mapping['property'], $fieldValue, $type);
                } elseif (in_array($fieldName, $class->referenceMappings) || in_array($fieldName, $class->referrersMappings)) {
                    $associationUpdates[$oid] = $document;

                    //populate $associationChangesets to force executeUpdates($associationUpdates)
                    //to only update association fields
                    $data = $associationChangesets[$oid]['fields'] ?? [];
                    $data[$fieldName] = [null, $fieldValue];
                    $associationChangesets[$oid] = ['fields' => $data];
                }
            }

            $this->doSaveTranslation($document, $node, $class);

            if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::postPersist)) {
                $this->eventListenersInvoker->invoke(
                    $class,
                    Event::postPersist,
                    $document,
                    new LifecycleEventArgs($document, $this->dm),
                    $invoke
                );
            }
        }

        $this->documentChangesets = array_merge($this->documentChangesets, $associationChangesets);

        $this->executeUpdates($associationUpdates, false);
    }
846677
protected function processJunks(array $chunk): int
    {
        $processed = 0;

        while (!empty($chunk)) {
            $processed++;
            $file = array_shift($chunk);

            list($errors, $warnings) = $this->processFile($file);

            if ($this->format !== 'json') {
                $this->printLegend($errors, $warnings);
            }
        }

        return $processed;
    }
1226128
function chunk(int $numitems, bool $preserve_keys = false) {
        return (new self(\array_chunk($this->data, $numitems, $preserve_keys)));
    }
1229328
public function push($document)
    {
        $this->initialize();
        $this->currentPosition++;

        if (isset($this->metadata['count']) && $this->currentPosition > $this->metadata['count']) {
            throw new \OverflowException(
                sprintf('This writer was set up to write %d documents, got more.', $this->metadata['count'])
            );
        }

        fwrite($this->handle, ",\n");
        fwrite($this->handle, json_encode($document));

        if (isset($this->metadata['count']) && $this->currentPosition == $this->metadata['count']) {
            $this->finalize();
        }
    }
194442
public function handleCollections($document)
    {
        // Collection deletions (deletions of complete collections)
        foreach ($this->uow->getScheduledCollections($document) as $coll) {
            if (!$this->uow->isCollectionScheduledForDeletion($coll)) {
                continue;
            }

            $this->cp->delete($coll);
        }

        // Collection updates (deleteRows, updateRows, insertRows)
        foreach ($this->uow->getScheduledCollections($document) as $coll) {
            if (!$this->uow->isCollectionScheduledForUpdate($coll)) {
                continue;
            }

            $this->cp->update($coll);
        }

        // Take new snapshots from visited collections
        foreach ($this->uow->getVisitedCollections($document) as $coll) {
            $coll->takeSnapshot();
        }
    }
332887
public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){
		$this->strs[] = $chunk;
	}
680337
static private function update_file_or_buffer($chunk, $fp, &$buffer) {
        if ($fp) {
            fwrite($fp, $chunk);
        } else {
            $buffer .= $chunk;
        }
    }