Client.php 10.1 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright 2015-2017 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
 *
 *   http://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.
 */
17 18 19

namespace MongoDB;

20 21
use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
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 29
use MongoDB\Exception\UnexpectedValueException;
use MongoDB\Exception\UnsupportedException;
30 31
use MongoDB\Model\BSONArray;
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 39

class Client
{
40
    private static $defaultTypeMap = [
41 42 43
        'array' => BSONArray::class,
        'document' => BSONDocument::class,
        'root' => BSONDocument::class,
44
    ];
45
    private static $wireVersionForReadConcern = 4;
46
    private static $wireVersionForWritableCommandWriteConcern = 5;
47

48
    private $manager;
49 50
    private $readConcern;
    private $readPreference;
51
    private $uri;
52
    private $typeMap;
53
    private $writeConcern;
54 55

    /**
56
     * Constructs a new Client instance.
57
     *
58 59 60
     * 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.
61
     *
62 63 64 65 66 67
     * Supported driver-specific options:
     *
     *  * typeMap (array): Default type map for cursors and BSON documents.
     *
     * Other options are documented in MongoDB\Driver\Manager::__construct().
     *
68
     * @see http://docs.mongodb.org/manual/reference/connection-string/
69 70
     * @see http://php.net/manual/en/mongodb-driver-manager.construct.php
     * @see http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps
71
     * @param string $uri           MongoDB connection string
72
     * @param array  $uriOptions    Additional connection string options
73
     * @param array  $driverOptions Driver-specific options
74 75 76
     * @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)
77
     */
78
    public function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])
79
    {
80
        $driverOptions += ['typeMap' => self::$defaultTypeMap];
81

82
        if (isset($driverOptions['typeMap']) && ! is_array($driverOptions['typeMap'])) {
83
            throw InvalidArgumentException::invalidType('"typeMap" driver option', $driverOptions['typeMap'], 'array');
84 85
        }

86
        $this->uri = (string) $uri;
87
        $this->typeMap = isset($driverOptions['typeMap']) ? $driverOptions['typeMap'] : null;
88 89 90 91

        unset($driverOptions['typeMap']);

        $this->manager = new Manager($uri, $uriOptions, $driverOptions);
92 93
        $this->readConcern = $this->manager->getReadConcern();
        $this->readPreference = $this->manager->getReadPreference();
94
        $this->writeConcern = $this->manager->getWriteConcern();
95 96
    }

97 98 99 100
    /**
     * Return internal properties for debugging purposes.
     *
     * @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
101
     * @return array
102 103 104 105 106 107
     */
    public function __debugInfo()
    {
        return [
            'manager' => $this->manager,
            'uri' => $this->uri,
108
            'typeMap' => $this->typeMap,
109
            'writeConcern' => $this->writeConcern,
110 111 112
        ];
    }

113 114 115
    /**
     * Select a database.
     *
116
     * Note: databases whose names contain special characters (e.g. "-") may
117 118 119 120 121 122 123 124 125 126 127 128 129
     * be selected with complex syntax (e.g. $client->{"that-database"}) or
     * {@link selectDatabase()}.
     *
     * @see http://php.net/oop5.overloading#object.get
     * @see http://php.net/types.string#language.types.string.parsing.complex
     * @param string $databaseName Name of the database to select
     * @return Database
     */
    public function __get($databaseName)
    {
        return $this->selectDatabase($databaseName);
    }

130 131 132
    /**
     * Return the connection string (i.e. URI).
     *
133
     * @return string
134 135 136 137
     */
    public function __toString()
    {
        return $this->uri;
138 139
    }

140 141 142
    /**
     * Drop a database.
     *
143 144 145 146
     * @see DropDatabase::__construct() for supported options
     * @param string $databaseName Database name
     * @param array  $options      Additional options
     * @return array|object Command result document
147 148 149
     * @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)
150
     */
151
    public function dropDatabase($databaseName, array $options = [])
152
    {
153
        if (! isset($options['typeMap'])) {
154 155 156
            $options['typeMap'] = $this->typeMap;
        }

157
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
158

159
        if (! isset($options['writeConcern']) && server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern)) {
160 161 162 163 164
            $options['writeConcern'] = $this->writeConcern;
        }

        $operation = new DropDatabase($databaseName, $options);

165
        return $operation->execute($server);
166 167
    }

168 169 170 171 172 173 174 175 176 177
    /**
     * Return the Manager.
     *
     * @return Manager
     */
    public function getManager()
    {
        return $this->manager;
    }

178
    /**
179
     * Return the read concern for this client.
180
     *
181 182
     * @see http://php.net/manual/en/mongodb-driver-readconcern.isdefault.php
     * @return ReadConcern
183 184 185
     */
    public function getReadConcern()
    {
186
        return $this->readConcern;
187 188 189
    }

    /**
190
     * Return the read preference for this client.
191 192 193 194 195
     *
     * @return ReadPreference
     */
    public function getReadPreference()
    {
196
        return $this->readPreference;
197 198 199
    }

    /**
200
     * Return the type map for this client.
201 202 203 204 205 206 207 208 209
     *
     * @return array
     */
    public function getTypeMap()
    {
        return $this->typeMap;
    }

    /**
210
     * Return the write concern for this client.
211
     *
212 213
     * @see http://php.net/manual/en/mongodb-driver-writeconcern.isdefault.php
     * @return WriteConcern
214 215 216 217 218 219
     */
    public function getWriteConcern()
    {
        return $this->writeConcern;
    }

220 221 222
    /**
     * List databases.
     *
223
     * @see ListDatabases::__construct() for supported options
224
     * @param array $options
225
     * @return DatabaseInfoIterator
226 227 228
     * @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)
229
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
230
    public function listDatabases(array $options = [])
231
    {
232 233
        $operation = new ListDatabases($options);
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
234

235
        return $operation->execute($server);
236 237
    }

238
    /**
239
     * Select a collection.
240
     *
241
     * @see Collection::__construct() for supported options
242 243 244
     * @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
245
     * @return Collection
246
     * @throws InvalidArgumentException for parameter/option parsing errors
247
     */
248
    public function selectCollection($databaseName, $collectionName, array $options = [])
249
    {
250 251
        $options += ['typeMap' => $this->typeMap];

252
        return new Collection($this->manager, $databaseName, $collectionName, $options);
253 254 255
    }

    /**
256
     * Select a database.
257
     *
258
     * @see Database::__construct() for supported options
259 260
     * @param string $databaseName Name of the database to select
     * @param array  $options      Database constructor options
261
     * @return Database
262
     * @throws InvalidArgumentException for parameter/option parsing errors
263
     */
264
    public function selectDatabase($databaseName, array $options = [])
265
    {
266 267
        $options += ['typeMap' => $this->typeMap];

268
        return new Database($this->manager, $databaseName, $options);
269
    }
270 271 272 273 274

    /**
     * Start a new client session.
     *
     * @see http://php.net/manual/en/mongodb-driver-manager.startsession.php
275
     * @param array $options Session options
276
     * @return Session
277 278 279 280 281
     */
    public function startSession(array $options = [])
    {
        return $this->manager->startSession($options);
    }
282 283 284 285 286 287 288 289 290 291 292 293

    /**
     * Create a change stream for watching changes to the cluster.
     *
     * @see Watch::__construct() for supported options
     * @param array $pipeline List of pipeline operations
     * @param array $options  Command options
     * @return ChangeStream
     * @throws InvalidArgumentException for parameter/option parsing errors
     */
    public function watch(array $pipeline = [], array $options = [])
    {
294
        if (! isset($options['readPreference'])) {
295 296 297 298 299
            $options['readPreference'] = $this->readPreference;
        }

        $server = $this->manager->selectServer($options['readPreference']);

300
        if (! isset($options['readConcern']) && server_supports_feature($server, self::$wireVersionForReadConcern)) {
301 302 303
            $options['readConcern'] = $this->readConcern;
        }

304
        if (! isset($options['typeMap'])) {
305 306 307 308 309 310 311
            $options['typeMap'] = $this->typeMap;
        }

        $operation = new Watch($this->manager, null, null, $pipeline, $options);

        return $operation->execute($server);
    }
312
}