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\InsertOneResult;
  28  
  29  use function is_array;
  30  use function is_bool;
  31  use function is_object;
  32  
  33  /**
  34   * Operation for inserting a single document with the insert command.
  35   *
  36   * @api
  37   * @see \MongoDB\Collection::insertOne()
  38   * @see https://mongodb.com/docs/manual/reference/command/insert/
  39   */
  40  class InsertOne implements Executable
  41  {
  42      /** @var string */
  43      private $databaseName;
  44  
  45      /** @var string */
  46      private $collectionName;
  47  
  48      /** @var array|object */
  49      private $document;
  50  
  51      /** @var array */
  52      private $options;
  53  
  54      /**
  55       * Constructs an insert command.
  56       *
  57       * Supported options:
  58       *
  59       *  * bypassDocumentValidation (boolean): If true, allows the write to
  60       *    circumvent document level validation.
  61       *
  62       *  * comment (mixed): BSON value to attach as a comment to this command.
  63       *
  64       *    This is not supported for servers versions < 4.4.
  65       *
  66       *  * session (MongoDB\Driver\Session): Client session.
  67       *
  68       *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
  69       *
  70       * @param string       $databaseName   Database name
  71       * @param string       $collectionName Collection name
  72       * @param array|object $document       Document to insert
  73       * @param array        $options        Command options
  74       * @throws InvalidArgumentException for parameter/option parsing errors
  75       */
  76      public function __construct(string $databaseName, string $collectionName, $document, array $options = [])
  77      {
  78          if (! is_array($document) && ! is_object($document)) {
  79              throw InvalidArgumentException::invalidType('$document', $document, 'array or object');
  80          }
  81  
  82          if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
  83              throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
  84          }
  85  
  86          if (isset($options['session']) && ! $options['session'] instanceof Session) {
  87              throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
  88          }
  89  
  90          if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
  91              throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
  92          }
  93  
  94          if (isset($options['bypassDocumentValidation']) && ! $options['bypassDocumentValidation']) {
  95              unset($options['bypassDocumentValidation']);
  96          }
  97  
  98          if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
  99              unset($options['writeConcern']);
 100          }
 101  
 102          $this->databaseName = $databaseName;
 103          $this->collectionName = $collectionName;
 104          $this->document = $document;
 105          $this->options = $options;
 106      }
 107  
 108      /**
 109       * Execute the operation.
 110       *
 111       * @see Executable::execute()
 112       * @return InsertOneResult
 113       * @throws UnsupportedException if write concern is used and unsupported
 114       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 115       */
 116      public function execute(Server $server)
 117      {
 118          $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
 119          if (isset($this->options['writeConcern']) && $inTransaction) {
 120              throw UnsupportedException::writeConcernNotSupportedInTransaction();
 121          }
 122  
 123          $bulk = new Bulk($this->createBulkWriteOptions());
 124          $insertedId = $bulk->insert($this->document);
 125  
 126          $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createExecuteOptions());
 127  
 128          return new InsertOneResult($writeResult, $insertedId);
 129      }
 130  
 131      /**
 132       * Create options for constructing the bulk write.
 133       *
 134       * @see https://php.net/manual/en/mongodb-driver-bulkwrite.construct.php
 135       */
 136      private function createBulkWriteOptions(): array
 137      {
 138          $options = [];
 139  
 140          foreach (['bypassDocumentValidation', 'comment'] as $option) {
 141              if (isset($this->options[$option])) {
 142                  $options[$option] = $this->options[$option];
 143              }
 144          }
 145  
 146          return $options;
 147      }
 148  
 149      /**
 150       * Create options for executing the bulk write.
 151       *
 152       * @see https://php.net/manual/en/mongodb-driver-server.executebulkwrite.php
 153       */
 154      private function createExecuteOptions(): array
 155      {
 156          $options = [];
 157  
 158          if (isset($this->options['session'])) {
 159              $options['session'] = $this->options['session'];
 160          }
 161  
 162          if (isset($this->options['writeConcern'])) {
 163              $options['writeConcern'] = $this->options['writeConcern'];
 164          }
 165  
 166          return $options;
 167      }
 168  }