InsertMany.php 6.4 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright 2015-2017 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
17 18 19

namespace MongoDB\Operation;

20
use MongoDB\Driver\BulkWrite as Bulk;
21
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
22
use MongoDB\Driver\Server;
23
use MongoDB\Driver\Session;
24 25
use MongoDB\Driver\WriteConcern;
use MongoDB\Exception\InvalidArgumentException;
26
use MongoDB\Exception\UnsupportedException;
27 28 29 30 31 32
use MongoDB\InsertManyResult;
use function is_array;
use function is_bool;
use function is_object;
use function MongoDB\server_supports_feature;
use function sprintf;
33 34 35 36 37

/**
 * Operation for inserting multiple documents with the insert command.
 *
 * @api
38
 * @see \MongoDB\Collection::insertMany()
39 40 41 42
 * @see http://docs.mongodb.org/manual/reference/command/insert/
 */
class InsertMany implements Executable
{
43
    /** @var integer */
44 45
    private static $wireVersionForDocumentLevelValidation = 4;

46
    /** @var string */
47
    private $databaseName;
48 49

    /** @var string */
50
    private $collectionName;
51 52

    /** @var object[]|array[] */
53
    private $documents;
54 55

    /** @var array */
56 57 58 59 60 61 62
    private $options;

    /**
     * Constructs an insert command.
     *
     * Supported options:
     *
63 64 65 66 67
     *  * bypassDocumentValidation (boolean): If true, allows the write to
     *    circumvent document level validation.
     *
     *    For servers < 3.2, this option is ignored as document level validation
     *    is not available.
68
     *
69 70 71 72
     *  * 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.
     *
73 74 75 76
     *  * session (MongoDB\Driver\Session): Client session.
     *
     *    Sessions are not supported for server versions < 3.6.
     *
77 78 79 80 81 82
     *  * 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
83
     * @throws InvalidArgumentException for parameter/option parsing errors
84
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
85
    public function __construct($databaseName, $collectionName, array $documents, array $options = [])
86 87 88 89 90 91 92 93 94 95 96 97
    {
        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));
            }

98
            if (! is_array($document) && ! is_object($document)) {
99
                throw InvalidArgumentException::invalidType(sprintf('$documents[%d]', $i), $document, 'array or object');
100 101 102 103 104
            }

            $expectedIndex += 1;
        }

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

107
        if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
108
            throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
109 110
        }

111
        if (! is_bool($options['ordered'])) {
112
            throw InvalidArgumentException::invalidType('"ordered" option', $options['ordered'], 'boolean');
113 114
        }

115
        if (isset($options['session']) && ! $options['session'] instanceof Session) {
116
            throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
117 118
        }

119
        if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
120
            throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
121 122
        }

123 124 125 126
        if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
            unset($options['writeConcern']);
        }

127 128 129 130 131 132 133 134 135 136 137 138
        $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
139
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
140 141 142
     */
    public function execute(Server $server)
    {
143 144 145 146 147
        $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
        if ($inTransaction && isset($this->options['writeConcern'])) {
            throw UnsupportedException::writeConcernNotSupportedInTransaction();
        }

148 149
        $options = ['ordered' => $this->options['ordered']];

150 151
        if (! empty($this->options['bypassDocumentValidation']) &&
            server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
152
        ) {
153 154 155 156
            $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
        }

        $bulk = new Bulk($options);
Jeremy Mikola's avatar
Jeremy Mikola committed
157
        $insertedIds = [];
158 159

        foreach ($this->documents as $i => $document) {
160
            $insertedIds[$i] = $bulk->insert($document);
161 162
        }

163
        $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createOptions());
164 165 166

        return new InsertManyResult($writeResult, $insertedIds);
    }
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

    /**
     * Create options for executing the bulk write.
     *
     * @see http://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
     * @return array
     */
    private function createOptions()
    {
        $options = [];

        if (isset($this->options['session'])) {
            $options['session'] = $this->options['session'];
        }

        if (isset($this->options['writeConcern'])) {
            $options['writeConcern'] = $this->options['writeConcern'];
        }

        return $options;
    }
188
}