/
Client.php
437 lines (376 loc) · 14.1 KB
/
Client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<?php
/*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace MongoDB;
use Iterator;
use Jean85\PrettyVersions;
use MongoDB\Driver\ClientEncryption;
use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Monitoring\Subscriber;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\Session;
use MongoDB\Driver\WriteConcern;
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Exception\UnexpectedValueException;
use MongoDB\Exception\UnsupportedException;
use MongoDB\Model\BSONArray;
use MongoDB\Model\BSONDocument;
use MongoDB\Model\DatabaseInfoIterator;
use MongoDB\Operation\DropDatabase;
use MongoDB\Operation\ListDatabaseNames;
use MongoDB\Operation\ListDatabases;
use MongoDB\Operation\Watch;
use Throwable;
use function is_array;
use function is_string;
class Client
{
public const DEFAULT_URI = 'mongodb://127.0.0.1/';
private const DEFAULT_TYPE_MAP = [
'array' => BSONArray::class,
'document' => BSONDocument::class,
'root' => BSONDocument::class,
];
private const HANDSHAKE_SEPARATOR = '/';
private static ?string $version = null;
private Manager $manager;
private ReadConcern $readConcern;
private ReadPreference $readPreference;
private string $uri;
private array $typeMap;
private WriteConcern $writeConcern;
/**
* Constructs a new Client instance.
*
* This is the preferred class for connecting to a MongoDB server or
* cluster of servers. It serves as a gateway for accessing individual
* databases and collections.
*
* Supported driver-specific options:
*
* * typeMap (array): Default type map for cursors and BSON documents.
*
* Other options are documented in MongoDB\Driver\Manager::__construct().
*
* @see https://mongodb.com/docs/manual/reference/connection-string/
* @see https://php.net/manual/en/mongodb-driver-manager.construct.php
* @see https://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps
* @param string|null $uri MongoDB connection string. If none is provided, this defaults to self::DEFAULT_URI.
* @param array $uriOptions Additional connection string options
* @param array $driverOptions Driver-specific options
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverInvalidArgumentException for parameter/option parsing errors in the driver
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function __construct(?string $uri = null, array $uriOptions = [], array $driverOptions = [])
{
$driverOptions += ['typeMap' => self::DEFAULT_TYPE_MAP];
if (! is_array($driverOptions['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" driver option', $driverOptions['typeMap'], 'array');
}
if (isset($driverOptions['autoEncryption']['keyVaultClient'])) {
if ($driverOptions['autoEncryption']['keyVaultClient'] instanceof self) {
$driverOptions['autoEncryption']['keyVaultClient'] = $driverOptions['autoEncryption']['keyVaultClient']->manager;
} elseif (! $driverOptions['autoEncryption']['keyVaultClient'] instanceof Manager) {
throw InvalidArgumentException::invalidType('"keyVaultClient" autoEncryption option', $driverOptions['autoEncryption']['keyVaultClient'], [self::class, Manager::class]);
}
}
$driverOptions['driver'] = $this->mergeDriverInfo($driverOptions['driver'] ?? []);
$this->uri = $uri ?? self::DEFAULT_URI;
$this->typeMap = $driverOptions['typeMap'];
unset($driverOptions['typeMap']);
$this->manager = new Manager($uri, $uriOptions, $driverOptions);
$this->readConcern = $this->manager->getReadConcern();
$this->readPreference = $this->manager->getReadPreference();
$this->writeConcern = $this->manager->getWriteConcern();
}
/**
* Return internal properties for debugging purposes.
*
* @see https://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
* @return array
*/
public function __debugInfo()
{
return [
'manager' => $this->manager,
'uri' => $this->uri,
'typeMap' => $this->typeMap,
'writeConcern' => $this->writeConcern,
];
}
/**
* Select a database.
*
* Note: databases whose names contain special characters (e.g. "-") may
* be selected with complex syntax (e.g. $client->{"that-database"}) or
* {@link selectDatabase()}.
*
* @see https://php.net/oop5.overloading#object.get
* @see https://php.net/types.string#language.types.string.parsing.complex
* @param string $databaseName Name of the database to select
* @return Database
*/
public function __get(string $databaseName)
{
return $this->selectDatabase($databaseName);
}
/**
* Return the connection string (i.e. URI).
*
* @return string
*/
public function __toString()
{
return $this->uri;
}
/**
* Registers a monitoring event subscriber with this Client's Manager
*
* @see Manager::addSubscriber()
*/
final public function addSubscriber(Subscriber $subscriber): void
{
$this->manager->addSubscriber($subscriber);
}
/**
* Returns a ClientEncryption instance for explicit encryption and decryption
*
* @param array $options Encryption options
*
* @return ClientEncryption
*/
public function createClientEncryption(array $options)
{
if (isset($options['keyVaultClient'])) {
if ($options['keyVaultClient'] instanceof self) {
$options['keyVaultClient'] = $options['keyVaultClient']->manager;
} elseif (! $options['keyVaultClient'] instanceof Manager) {
throw InvalidArgumentException::invalidType('"keyVaultClient" option', $options['keyVaultClient'], [self::class, Manager::class]);
}
}
return $this->manager->createClientEncryption($options);
}
/**
* Drop a database.
*
* @see DropDatabase::__construct() for supported options
* @param string $databaseName Database name
* @param array $options Additional options
* @return array|object Command result document
* @throws UnsupportedException if options are unsupported on the selected server
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function dropDatabase(string $databaseName, array $options = [])
{
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$server = select_server_for_write($this->manager, $options);
if (! isset($options['writeConcern']) && ! is_in_transaction($options)) {
$options['writeConcern'] = $this->writeConcern;
}
$operation = new DropDatabase($databaseName, $options);
return $operation->execute($server);
}
/**
* Return the Manager.
*
* @return Manager
*/
public function getManager()
{
return $this->manager;
}
/**
* Return the read concern for this client.
*
* @see https://php.net/manual/en/mongodb-driver-readconcern.isdefault.php
* @return ReadConcern
*/
public function getReadConcern()
{
return $this->readConcern;
}
/**
* Return the read preference for this client.
*
* @return ReadPreference
*/
public function getReadPreference()
{
return $this->readPreference;
}
/**
* Return the type map for this client.
*
* @return array
*/
public function getTypeMap()
{
return $this->typeMap;
}
/**
* Return the write concern for this client.
*
* @see https://php.net/manual/en/mongodb-driver-writeconcern.isdefault.php
* @return WriteConcern
*/
public function getWriteConcern()
{
return $this->writeConcern;
}
/**
* List database names.
*
* @see ListDatabaseNames::__construct() for supported options
* @throws UnexpectedValueException if the command response was malformed
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function listDatabaseNames(array $options = []): Iterator
{
$operation = new ListDatabaseNames($options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* List databases.
*
* @see ListDatabases::__construct() for supported options
* @return DatabaseInfoIterator
* @throws UnexpectedValueException if the command response was malformed
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function listDatabases(array $options = [])
{
$operation = new ListDatabases($options);
$server = select_server($this->manager, $options);
return $operation->execute($server);
}
/**
* Unregisters a monitoring event subscriber with this Client's Manager
*
* @see Manager::removeSubscriber()
*/
final public function removeSubscriber(Subscriber $subscriber): void
{
$this->manager->removeSubscriber($subscriber);
}
/**
* Select a collection.
*
* @see Collection::__construct() for supported options
* @param string $databaseName Name of the database containing the collection
* @param string $collectionName Name of the collection to select
* @param array $options Collection constructor options
* @return Collection
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function selectCollection(string $databaseName, string $collectionName, array $options = [])
{
$options += ['typeMap' => $this->typeMap];
return new Collection($this->manager, $databaseName, $collectionName, $options);
}
/**
* Select a database.
*
* @see Database::__construct() for supported options
* @param string $databaseName Name of the database to select
* @param array $options Database constructor options
* @return Database
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function selectDatabase(string $databaseName, array $options = [])
{
$options += ['typeMap' => $this->typeMap];
return new Database($this->manager, $databaseName, $options);
}
/**
* Start a new client session.
*
* @see https://php.net/manual/en/mongodb-driver-manager.startsession.php
* @param array $options Session options
* @return Session
*/
public function startSession(array $options = [])
{
return $this->manager->startSession($options);
}
/**
* Create a change stream for watching changes to the cluster.
*
* @see Watch::__construct() for supported options
* @param array $pipeline Aggregation pipeline
* @param array $options Command options
* @return ChangeStream
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function watch(array $pipeline = [], array $options = [])
{
if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
$server = select_server($this->manager, $options);
if (! isset($options['readConcern']) && ! is_in_transaction($options)) {
$options['readConcern'] = $this->readConcern;
}
if (! isset($options['typeMap'])) {
$options['typeMap'] = $this->typeMap;
}
$operation = new Watch($this->manager, null, null, $pipeline, $options);
return $operation->execute($server);
}
private static function getVersion(): string
{
if (self::$version === null) {
try {
self::$version = PrettyVersions::getVersion('mongodb/mongodb')->getPrettyVersion();
} catch (Throwable $t) {
return 'unknown';
}
}
return self::$version;
}
private function mergeDriverInfo(array $driver): array
{
$mergedDriver = [
'name' => 'PHPLIB',
'version' => self::getVersion(),
];
if (isset($driver['name'])) {
if (! is_string($driver['name'])) {
throw InvalidArgumentException::invalidType('"name" handshake option', $driver['name'], 'string');
}
$mergedDriver['name'] .= self::HANDSHAKE_SEPARATOR . $driver['name'];
}
if (isset($driver['version'])) {
if (! is_string($driver['version'])) {
throw InvalidArgumentException::invalidType('"version" handshake option', $driver['version'], 'string');
}
$mergedDriver['version'] .= self::HANDSHAKE_SEPARATOR . $driver['version'];
}
if (isset($driver['platform'])) {
$mergedDriver['platform'] = $driver['platform'];
}
return $mergedDriver;
}
}