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