InsertMany.php 4.21 KB
Newer Older
1 2 3 4 5
<?php

namespace MongoDB\Operation;

use MongoDB\InsertManyResult;
6
use MongoDB\Driver\BulkWrite as Bulk;
7 8 9 10 11 12 13 14 15 16 17 18 19
use MongoDB\Driver\Server;
use MongoDB\Driver\WriteConcern;
use MongoDB\Exception\InvalidArgumentException;

/**
 * Operation for inserting multiple documents with the insert command.
 *
 * @api
 * @see MongoDB\Collection::insertMany()
 * @see http://docs.mongodb.org/manual/reference/command/insert/
 */
class InsertMany implements Executable
{
20 21
    private static $wireVersionForDocumentLevelValidation = 4;

22 23 24 25 26 27 28 29 30 31
    private $databaseName;
    private $collectionName;
    private $documents;
    private $options;

    /**
     * Constructs an insert command.
     *
     * Supported options:
     *
32 33 34
     *  * bypassDocumentValidation (boolean): If true, allows the write to opt
     *    out of document level validation.
     *
35 36 37 38 39 40 41 42 43 44 45 46
     *  * ordered (boolean): If true, when an insert fails, return without
     *    performing the remaining writes. If false, when a write fails,
     *    continue with the remaining writes, if any. The default is true.
     *
     *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
     *
     * @param string           $databaseName   Database name
     * @param string           $collectionName Collection name
     * @param array[]|object[] $documents      List of documents to insert
     * @param array            $options        Command options
     * @throws InvalidArgumentException
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
47
    public function __construct($databaseName, $collectionName, array $documents, array $options = [])
48 49 50 51 52 53 54 55 56 57 58 59 60
    {
        if (empty($documents)) {
            throw new InvalidArgumentException('$documents is empty');
        }

        $expectedIndex = 0;

        foreach ($documents as $i => $document) {
            if ($i !== $expectedIndex) {
                throw new InvalidArgumentException(sprintf('$documents is not a list (unexpected index: "%s")', $i));
            }

            if ( ! is_array($document) && ! is_object($document)) {
61
                throw InvalidArgumentException::invalidType(sprintf('$documents[%d]', $i), $document, 'array or object');
62 63 64 65 66
            }

            $expectedIndex += 1;
        }

Jeremy Mikola's avatar
Jeremy Mikola committed
67
        $options += ['ordered' => true];
68

69
        if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
70
            throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
71 72
        }

73
        if ( ! is_bool($options['ordered'])) {
74
            throw InvalidArgumentException::invalidType('"ordered" option', $options['ordered'], 'boolean');
75 76
        }

77
        if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
78
            throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], 'MongoDB\Driver\WriteConcern');
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        }

        $this->databaseName = (string) $databaseName;
        $this->collectionName = (string) $collectionName;
        $this->documents = $documents;
        $this->options = $options;
    }

    /**
     * Execute the operation.
     *
     * @see Executable::execute()
     * @param Server $server
     * @return InsertManyResult
     */
    public function execute(Server $server)
    {
96 97 98 99 100 101 102
        $options = ['ordered' => $this->options['ordered']];

        if (isset($this->options['bypassDocumentValidation']) && \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)) {
            $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
        }

        $bulk = new Bulk($options);
Jeremy Mikola's avatar
Jeremy Mikola committed
103
        $insertedIds = [];
104 105 106 107 108 109 110

        foreach ($this->documents as $i => $document) {
            $insertedId = $bulk->insert($document);

            if ($insertedId !== null) {
                $insertedIds[$i] = $insertedId;
            } else {
111
                $insertedIds[$i] = \MongoDB\extract_id_from_inserted_document($document);
112 113 114 115 116 117 118 119 120
            }
        }

        $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
        $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);

        return new InsertManyResult($writeResult, $insertedIds);
    }
}