Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

   1  <?php
   2  /*
   3   * Copyright 2015-2017 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   *   http://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;
  19  
  20  use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
  21  use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
  22  use MongoDB\Driver\Manager;
  23  use MongoDB\Driver\ReadConcern;
  24  use MongoDB\Driver\ReadPreference;
  25  use MongoDB\Driver\Session;
  26  use MongoDB\Driver\WriteConcern;
  27  use MongoDB\Exception\InvalidArgumentException;
  28  use MongoDB\Exception\UnexpectedValueException;
  29  use MongoDB\Exception\UnsupportedException;
  30  use MongoDB\Model\BSONArray;
  31  use MongoDB\Model\BSONDocument;
  32  use MongoDB\Model\DatabaseInfoIterator;
  33  use MongoDB\Operation\DropDatabase;
  34  use MongoDB\Operation\ListDatabases;
  35  use MongoDB\Operation\Watch;
  36  use function is_array;
  37  
  38  class Client
  39  {
  40      /** @var array */
  41      private static $defaultTypeMap = [
  42          'array' => BSONArray::class,
  43          'document' => BSONDocument::class,
  44          'root' => BSONDocument::class,
  45      ];
  46  
  47      /** @var integer */
  48      private static $wireVersionForReadConcern = 4;
  49  
  50      /** @var integer */
  51      private static $wireVersionForWritableCommandWriteConcern = 5;
  52  
  53      /** @var Manager */
  54      private $manager;
  55  
  56      /** @var ReadConcern */
  57      private $readConcern;
  58  
  59      /** @var ReadPreference */
  60      private $readPreference;
  61  
  62      /** @var string */
  63      private $uri;
  64  
  65      /** @var array */
  66      private $typeMap;
  67  
  68      /** @var WriteConcern */
  69      private $writeConcern;
  70  
  71      /**
  72       * Constructs a new Client instance.
  73       *
  74       * This is the preferred class for connecting to a MongoDB server or
  75       * cluster of servers. It serves as a gateway for accessing individual
  76       * databases and collections.
  77       *
  78       * Supported driver-specific options:
  79       *
  80       *  * typeMap (array): Default type map for cursors and BSON documents.
  81       *
  82       * Other options are documented in MongoDB\Driver\Manager::__construct().
  83       *
  84       * @see http://docs.mongodb.org/manual/reference/connection-string/
  85       * @see http://php.net/manual/en/mongodb-driver-manager.construct.php
  86       * @see http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps
  87       * @param string $uri           MongoDB connection string
  88       * @param array  $uriOptions    Additional connection string options
  89       * @param array  $driverOptions Driver-specific options
  90       * @throws InvalidArgumentException for parameter/option parsing errors
  91       * @throws DriverInvalidArgumentException for parameter/option parsing errors in the driver
  92       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
  93       */
  94      public function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])
  95      {
  96          $driverOptions += ['typeMap' => self::$defaultTypeMap];
  97  
  98          if (isset($driverOptions['typeMap']) && ! is_array($driverOptions['typeMap'])) {
  99              throw InvalidArgumentException::invalidType('"typeMap" driver option', $driverOptions['typeMap'], 'array');
 100          }
 101  
 102          $this->uri = (string) $uri;
 103          $this->typeMap = isset($driverOptions['typeMap']) ? $driverOptions['typeMap'] : null;
 104  
 105          unset($driverOptions['typeMap']);
 106  
 107          $this->manager = new Manager($uri, $uriOptions, $driverOptions);
 108          $this->readConcern = $this->manager->getReadConcern();
 109          $this->readPreference = $this->manager->getReadPreference();
 110          $this->writeConcern = $this->manager->getWriteConcern();
 111      }
 112  
 113      /**
 114       * Return internal properties for debugging purposes.
 115       *
 116       * @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
 117       * @return array
 118       */
 119      public function __debugInfo()
 120      {
 121          return [
 122              'manager' => $this->manager,
 123              'uri' => $this->uri,
 124              'typeMap' => $this->typeMap,
 125              'writeConcern' => $this->writeConcern,
 126          ];
 127      }
 128  
 129      /**
 130       * Select a database.
 131       *
 132       * Note: databases whose names contain special characters (e.g. "-") may
 133       * be selected with complex syntax (e.g. $client->{"that-database"}) or
 134       * {@link selectDatabase()}.
 135       *
 136       * @see http://php.net/oop5.overloading#object.get
 137       * @see http://php.net/types.string#language.types.string.parsing.complex
 138       * @param string $databaseName Name of the database to select
 139       * @return Database
 140       */
 141      public function __get($databaseName)
 142      {
 143          return $this->selectDatabase($databaseName);
 144      }
 145  
 146      /**
 147       * Return the connection string (i.e. URI).
 148       *
 149       * @return string
 150       */
 151      public function __toString()
 152      {
 153          return $this->uri;
 154      }
 155  
 156      /**
 157       * Drop a database.
 158       *
 159       * @see DropDatabase::__construct() for supported options
 160       * @param string $databaseName Database name
 161       * @param array  $options      Additional options
 162       * @return array|object Command result document
 163       * @throws UnsupportedException if options are unsupported on the selected server
 164       * @throws InvalidArgumentException for parameter/option parsing errors
 165       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 166       */
 167      public function dropDatabase($databaseName, array $options = [])
 168      {
 169          if (! isset($options['typeMap'])) {
 170              $options['typeMap'] = $this->typeMap;
 171          }
 172  
 173          $server = select_server($this->manager, $options);
 174  
 175          if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern) && ! is_in_transaction($options)) {
 176              $options['writeConcern'] = $this->writeConcern;
 177          }
 178  
 179          $operation = new DropDatabase($databaseName, $options);
 180  
 181          return $operation->execute($server);
 182      }
 183  
 184      /**
 185       * Return the Manager.
 186       *
 187       * @return Manager
 188       */
 189      public function getManager()
 190      {
 191          return $this->manager;
 192      }
 193  
 194      /**
 195       * Return the read concern for this client.
 196       *
 197       * @see http://php.net/manual/en/mongodb-driver-readconcern.isdefault.php
 198       * @return ReadConcern
 199       */
 200      public function getReadConcern()
 201      {
 202          return $this->readConcern;
 203      }
 204  
 205      /**
 206       * Return the read preference for this client.
 207       *
 208       * @return ReadPreference
 209       */
 210      public function getReadPreference()
 211      {
 212          return $this->readPreference;
 213      }
 214  
 215      /**
 216       * Return the type map for this client.
 217       *
 218       * @return array
 219       */
 220      public function getTypeMap()
 221      {
 222          return $this->typeMap;
 223      }
 224  
 225      /**
 226       * Return the write concern for this client.
 227       *
 228       * @see http://php.net/manual/en/mongodb-driver-writeconcern.isdefault.php
 229       * @return WriteConcern
 230       */
 231      public function getWriteConcern()
 232      {
 233          return $this->writeConcern;
 234      }
 235  
 236      /**
 237       * List databases.
 238       *
 239       * @see ListDatabases::__construct() for supported options
 240       * @param array $options
 241       * @return DatabaseInfoIterator
 242       * @throws UnexpectedValueException if the command response was malformed
 243       * @throws InvalidArgumentException for parameter/option parsing errors
 244       * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
 245       */
 246      public function listDatabases(array $options = [])
 247      {
 248          $operation = new ListDatabases($options);
 249          $server = select_server($this->manager, $options);
 250  
 251          return $operation->execute($server);
 252      }
 253  
 254      /**
 255       * Select a collection.
 256       *
 257       * @see Collection::__construct() for supported options
 258       * @param string $databaseName   Name of the database containing the collection
 259       * @param string $collectionName Name of the collection to select
 260       * @param array  $options        Collection constructor options
 261       * @return Collection
 262       * @throws InvalidArgumentException for parameter/option parsing errors
 263       */
 264      public function selectCollection($databaseName, $collectionName, array $options = [])
 265      {
 266          $options += ['typeMap' => $this->typeMap];
 267  
 268          return new Collection($this->manager, $databaseName, $collectionName, $options);
 269      }
 270  
 271      /**
 272       * Select a database.
 273       *
 274       * @see Database::__construct() for supported options
 275       * @param string $databaseName Name of the database to select
 276       * @param array  $options      Database constructor options
 277       * @return Database
 278       * @throws InvalidArgumentException for parameter/option parsing errors
 279       */
 280      public function selectDatabase($databaseName, array $options = [])
 281      {
 282          $options += ['typeMap' => $this->typeMap];
 283  
 284          return new Database($this->manager, $databaseName, $options);
 285      }
 286  
 287      /**
 288       * Start a new client session.
 289       *
 290       * @see http://php.net/manual/en/mongodb-driver-manager.startsession.php
 291       * @param array $options Session options
 292       * @return Session
 293       */
 294      public function startSession(array $options = [])
 295      {
 296          return $this->manager->startSession($options);
 297      }
 298  
 299      /**
 300       * Create a change stream for watching changes to the cluster.
 301       *
 302       * @see Watch::__construct() for supported options
 303       * @param array $pipeline List of pipeline operations
 304       * @param array $options  Command options
 305       * @return ChangeStream
 306       * @throws InvalidArgumentException for parameter/option parsing errors
 307       */
 308      public function watch(array $pipeline = [], array $options = [])
 309      {
 310          if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
 311              $options['readPreference'] = $this->readPreference;
 312          }
 313  
 314          $server = select_server($this->manager, $options);
 315  
 316          if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern) && ! is_in_transaction($options)) {
 317              $options['readConcern'] = $this->readConcern;
 318          }
 319  
 320          if (! isset($options['typeMap'])) {
 321              $options['typeMap'] = $this->typeMap;
 322          }
 323  
 324          $operation = new Watch($this->manager, null, null, $pipeline, $options);
 325  
 326          return $operation->execute($server);
 327      }
 328  }