InsertMany.php 4.31 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 20
use MongoDB\Driver\Server;
use MongoDB\Driver\WriteConcern;
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Exception\InvalidArgumentTypeException;

/**
 * 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
{
21 22
    private static $wireVersionForDocumentLevelValidation = 4;

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

    /**
     * Constructs an insert command.
     *
     * Supported options:
     *
33 34 35
     *  * bypassDocumentValidation (boolean): If true, allows the write to opt
     *    out of document level validation.
     *
36 37 38 39 40 41 42 43 44 45 46 47
     *  * 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
48
    public function __construct($databaseName, $collectionName, array $documents, array $options = [])
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    {
        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)) {
                throw new InvalidArgumentTypeException(sprintf('$documents[%d]', $i), $document, 'array or object');
            }

            $expectedIndex += 1;
        }

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

70 71 72 73
        if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
            throw new InvalidArgumentTypeException('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
        }

74 75 76 77
        if ( ! is_bool($options['ordered'])) {
            throw new InvalidArgumentTypeException('"ordered" option', $options['ordered'], 'boolean');
        }

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

        $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)
    {
97 98 99 100 101 102 103
        $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
104
        $insertedIds = [];
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

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

            if ($insertedId !== null) {
                $insertedIds[$i] = $insertedId;
            } else {
                // TODO: This may be removed if PHPC-382 is implemented
                $insertedIds[$i] = is_array($document) ? $document['_id'] : $document->_id;
            }
        }

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

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