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\Exception\RuntimeException as DriverRuntimeException;
  21  use MongoDB\Driver\Server;
  22  use MongoDB\Exception\InvalidArgumentException;
  23  use MongoDB\Exception\UnsupportedException;
  24  
  25  use function array_key_exists;
  26  use function is_array;
  27  use function is_integer;
  28  use function is_object;
  29  use function MongoDB\is_first_key_operator;
  30  
  31  /**
  32   * Operation for replacing a document with the findAndModify command.
  33   *
  34   * @api
  35   * @see \MongoDB\Collection::findOneAndReplace()
  36   * @see https://mongodb.com/docs/manual/reference/command/findAndModify/
  37   */
  38  class FindOneAndReplace implements Executable, Explainable
  39  {
  40      public const RETURN_DOCUMENT_BEFORE = 1;
  41      public const RETURN_DOCUMENT_AFTER = 2;
  42  
  43      /** @var FindAndModify */
  44      private $findAndModify;
  45  
  46      /**
  47       * Constructs a findAndModify command for replacing a document.
  48       *
  49       * Supported options:
  50       *
  51       *  * bypassDocumentValidation (boolean): If true, allows the write to
  52       *    circumvent document level validation.
  53       *
  54       *  * collation (document): Collation specification.
  55       *
  56       *  * comment (mixed): BSON value to attach as a comment to this command.
  57       *
  58       *    This is not supported for servers versions < 4.4.
  59       *
  60       *  * hint (string|document): The index to use. Specify either the index
  61       *    name as a string or the index key pattern as a document. If specified,
  62       *    then the query system will only consider plans using the hinted index.
  63       *
  64       *    This is not supported for server versions < 4.4 and will result in an
  65       *    exception at execution time if used.
  66       *
  67       *  * maxTimeMS (integer): The maximum amount of time to allow the query to
  68       *    run.
  69       *
  70       *  * projection (document): Limits the fields to return for the matching
  71       *    document.
  72       *
  73       *  * returnDocument (enum): Whether to return the document before or after
  74       *    the update is applied. Must be either
  75       *    FindOneAndReplace::RETURN_DOCUMENT_BEFORE or
  76       *    FindOneAndReplace::RETURN_DOCUMENT_AFTER. The default is
  77       *    FindOneAndReplace::RETURN_DOCUMENT_BEFORE.
  78       *
  79       *  * session (MongoDB\Driver\Session): Client session.
  80       *
  81       *  * sort (document): Determines which document the operation modifies if
  82       *    the query selects multiple documents.
  83       *
  84       *  * typeMap (array): Type map for BSON deserialization.
  85       *
  86       *  * upsert (boolean): When true, a new document is created if no document
  87       *    matches the query. The default is false.
  88       *
  89       *  * let (document): Map of parameter names and values. Values must be
  90       *    constant or closed expressions that do not reference document fields.
  91       *    Parameters can then be accessed as variables in an aggregate
  92       *    expression context (e.g. "$$var").
  93       *
  94       *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
  95       *
  96       * @param string       $databaseName   Database name
  97       * @param string       $collectionName Collection name
  98       * @param array|object $filter         Query by which to filter documents
  99       * @param array|object $replacement    Replacement document
 100       * @param array        $options        Command options
 101       * @throws InvalidArgumentException for parameter/option parsing errors
 102       */
 103      public function __construct(string $databaseName, string $collectionName, $filter, $replacement, array $options = [])
 104      {
 105          if (! is_array($filter) && ! is_object($filter)) {
 106              throw InvalidArgumentException::invalidType('$filter', $filter, 'array or object');
 107          }
 108  
 109          if (! is_array($replacement) && ! is_object($replacement)) {
 110              throw InvalidArgumentException::invalidType('$replacement', $replacement, 'array or object');
 111          }
 112  
 113          if (is_first_key_operator($replacement)) {
 114              throw new InvalidArgumentException('First key in $replacement argument is an update operator');
 115          }
 116  
 117          if (isset($options['projection']) && ! is_array($options['projection']) && ! is_object($options['projection'])) {
 118              throw InvalidArgumentException::invalidType('"projection" option', $options['projection'], 'array or object');
 119          }
 120  
 121          if (array_key_exists('returnDocument', $options) && ! is_integer($options['returnDocument'])) {
 122              throw InvalidArgumentException::invalidType('"returnDocument" option', $options['returnDocument'], 'integer');
 123          }
 124  
 125          if (
 126              isset($options['returnDocument']) &&
 127              $options['returnDocument'] !== self::RETURN_DOCUMENT_AFTER &&
 128              $options['returnDocument'] !== self::RETURN_DOCUMENT_BEFORE
 129          ) {
 130              throw new InvalidArgumentException('Invalid value for "returnDocument" option: ' . $options['returnDocument']);
 131          }
 132  
 133          if (isset($options['projection'])) {
 134              $options['fields'] = $options['projection'];
 135          }
 136  
 137          if (isset($options['returnDocument'])) {
 138              $options['new'] = $options['returnDocument'] === self::RETURN_DOCUMENT_AFTER;
 139          }
 140  
 141          unset($options['projection'], $options['returnDocument']);
 142  
 143          $this->findAndModify = new FindAndModify(
 144              $databaseName,
 145              $collectionName,
 146              ['query' => $filter, 'update' => $replacement] + $options
 147          );
 148      }
 149  
 150      /**
 151       * Execute the operation.
 152       *
 153       * @see Executable::execute()
 154       * @return array|object|null
 155       * @throws UnsupportedException if collation or write concern is used and unsupported
 156       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 157       */
 158      public function execute(Server $server)
 159      {
 160          return $this->findAndModify->execute($server);
 161      }
 162  
 163      /**
 164       * Returns the command document for this operation.
 165       *
 166       * @see Explainable::getCommandDocument()
 167       * @return array
 168       */
 169      public function getCommandDocument(Server $server)
 170      {
 171          return $this->findAndModify->getCommandDocument($server);
 172      }
 173  }