Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401]

   1  <?php
   2  /*
   3   * Copyright 2015-present MongoDB, Inc.
   4   *
   5   * Licensed under the Apache License, Version 2.0 (the "License");
   6   * you may not use this file except in compliance with the License.
   7   * You may obtain a copy of the License at
   8   *
   9   *   https://www.apache.org/licenses/LICENSE-2.0
  10   *
  11   * Unless required by applicable law or agreed to in writing, software
  12   * distributed under the License is distributed on an "AS IS" BASIS,
  13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14   * See the License for the specific language governing permissions and
  15   * limitations under the License.
  16   */
  17  
  18  namespace MongoDB\Operation;
  19  
  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  use MongoDB\Driver\WriteConcern;
  25  use MongoDB\Exception\InvalidArgumentException;
  26  use MongoDB\Exception\UnsupportedException;
  27  use MongoDB\InsertManyResult;
  28  
  29  use function is_array;
  30  use function is_bool;
  31  use function is_object;
  32  use function sprintf;
  33  
  34  /**
  35   * Operation for inserting multiple documents with the insert command.
  36   *
  37   * @api
  38   * @see \MongoDB\Collection::insertMany()
  39   * @see https://mongodb.com/docs/manual/reference/command/insert/
  40   */
  41  class InsertMany implements Executable
  42  {
  43      /** @var string */
  44      private $databaseName;
  45  
  46      /** @var string */
  47      private $collectionName;
  48  
  49      /** @var object[]|array[] */
  50      private $documents;
  51  
  52      /** @var array */
  53      private $options;
  54  
  55      /**
  56       * Constructs an insert command.
  57       *
  58       * Supported options:
  59       *
  60       *  * bypassDocumentValidation (boolean): If true, allows the write to
  61       *    circumvent document level validation.
  62       *
  63       *  * comment (mixed): BSON value to attach as a comment to the command(s)
  64       *    associated with this insert.
  65       *
  66       *    This is not supported for servers versions < 4.4.
  67       *
  68       *  * ordered (boolean): If true, when an insert fails, return without
  69       *    performing the remaining writes. If false, when a write fails,
  70       *    continue with the remaining writes, if any. The default is true.
  71       *
  72       *  * session (MongoDB\Driver\Session): Client session.
  73       *
  74       *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
  75       *
  76       * @param string           $databaseName   Database name
  77       * @param string           $collectionName Collection name
  78       * @param array[]|object[] $documents      List of documents to insert
  79       * @param array            $options        Command options
  80       * @throws InvalidArgumentException for parameter/option parsing errors
  81       */
  82      public function __construct(string $databaseName, string $collectionName, array $documents, array $options = [])
  83      {
  84          if (empty($documents)) {
  85              throw new InvalidArgumentException('$documents is empty');
  86          }
  87  
  88          $expectedIndex = 0;
  89  
  90          foreach ($documents as $i => $document) {
  91              if ($i !== $expectedIndex) {
  92                  throw new InvalidArgumentException(sprintf('$documents is not a list (unexpected index: "%s")', $i));
  93              }
  94  
  95              if (! is_array($document) && ! is_object($document)) {
  96                  throw InvalidArgumentException::invalidType(sprintf('$documents[%d]', $i), $document, 'array or object');
  97              }
  98  
  99              $expectedIndex += 1;
 100          }
 101  
 102          $options += ['ordered' => true];
 103  
 104          if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
 105              throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
 106          }
 107  
 108          if (! is_bool($options['ordered'])) {
 109              throw InvalidArgumentException::invalidType('"ordered" option', $options['ordered'], 'boolean');
 110          }
 111  
 112          if (isset($options['session']) && ! $options['session'] instanceof Session) {
 113              throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
 114          }
 115  
 116          if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
 117              throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
 118          }
 119  
 120          if (isset($options['bypassDocumentValidation']) && ! $options['bypassDocumentValidation']) {
 121              unset($options['bypassDocumentValidation']);
 122          }
 123  
 124          if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
 125              unset($options['writeConcern']);
 126          }
 127  
 128          $this->databaseName = $databaseName;
 129          $this->collectionName = $collectionName;
 130          $this->documents = $documents;
 131          $this->options = $options;
 132      }
 133  
 134      /**
 135       * Execute the operation.
 136       *
 137       * @see Executable::execute()
 138       * @return InsertManyResult
 139       * @throws UnsupportedException if write concern is used and unsupported
 140       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 141       */
 142      public function execute(Server $server)
 143      {
 144          $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
 145          if ($inTransaction && isset($this->options['writeConcern'])) {
 146              throw UnsupportedException::writeConcernNotSupportedInTransaction();
 147          }
 148  
 149          $bulk = new Bulk($this->createBulkWriteOptions());
 150          $insertedIds = [];
 151  
 152          foreach ($this->documents as $i => $document) {
 153              $insertedIds[$i] = $bulk->insert($document);
 154          }
 155  
 156          $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createExecuteOptions());
 157  
 158          return new InsertManyResult($writeResult, $insertedIds);
 159      }
 160  
 161      /**
 162       * Create options for constructing the bulk write.
 163       *
 164       * @see https://php.net/manual/en/mongodb-driver-bulkwrite.construct.php
 165       */
 166      private function createBulkWriteOptions(): array
 167      {
 168          $options = ['ordered' => $this->options['ordered']];
 169  
 170          foreach (['bypassDocumentValidation', 'comment'] as $option) {
 171              if (isset($this->options[$option])) {
 172                  $options[$option] = $this->options[$option];
 173              }
 174          }
 175  
 176          return $options;
 177      }
 178  
 179      /**
 180       * Create options for executing the bulk write.
 181       *
 182       * @see https://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
 183       */
 184      private function createExecuteOptions(): array
 185      {
 186          $options = [];
 187  
 188          if (isset($this->options['session'])) {
 189              $options['session'] = $this->options['session'];
 190          }
 191  
 192          if (isset($this->options['writeConcern'])) {
 193              $options['writeConcern'] = $this->options['writeConcern'];
 194          }
 195  
 196          return $options;
 197      }
 198  }