FindAndModify.php 11.9 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 20

namespace MongoDB\Operation;

use MongoDB\Driver\Command;
21
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
22
use MongoDB\Driver\Server;
23
use MongoDB\Driver\Session;
24
use MongoDB\Driver\WriteConcern;
25 26
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Exception\UnexpectedValueException;
27
use MongoDB\Exception\UnsupportedException;
28 29 30 31 32 33
use function current;
use function is_array;
use function is_bool;
use function is_integer;
use function is_object;
use function MongoDB\create_field_path_type_map;
34
use function MongoDB\is_pipeline;
35
use function MongoDB\server_supports_feature;
36 37 38 39 40 41 42 43 44 45

/**
 * Operation for the findAndModify command.
 *
 * This class is used internally by the FindOneAndDelete, FindOneAndReplace, and
 * FindOneAndUpdate operation classes.
 *
 * @internal
 * @see http://docs.mongodb.org/manual/reference/command/findAndModify/
 */
46
class FindAndModify implements Executable, Explainable
47
{
48
    /** @var integer */
49
    private static $wireVersionForArrayFilters = 6;
50 51

    /** @var integer */
52
    private static $wireVersionForCollation = 5;
53 54

    /** @var integer */
55
    private static $wireVersionForDocumentLevelValidation = 4;
56 57

    /** @var integer */
58
    private static $wireVersionForWriteConcern = 4;
59

60
    /** @var string */
61
    private $databaseName;
62 63

    /** @var string */
64
    private $collectionName;
65 66

    /** @var array */
67 68 69 70 71 72 73
    private $options;

    /**
     * Constructs a findAndModify command.
     *
     * Supported options:
     *
74 75 76 77 78 79
     *  * arrayFilters (document array): A set of filters specifying to which
     *    array elements an update should apply.
     *
     *    This is not supported for server versions < 3.6 and will result in an
     *    exception at execution time if used.
     *
80 81 82 83 84
     *  * collation (document): Collation specification.
     *
     *    This is not supported for server versions < 3.4 and will result in an
     *    exception at execution time if used.
     *
85 86 87 88 89
     *  * bypassDocumentValidation (boolean): If true, allows the write to
     *    circumvent document level validation.
     *
     *    For servers < 3.2, this option is ignored as document level validation
     *    is not available.
90
     *
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
     *  * fields (document): Limits the fields to return for the matching
     *    document.
     *
     *  * maxTimeMS (integer): The maximum amount of time to allow the query to
     *    run.
     *
     *  * new (boolean): When true, returns the modified document rather than
     *    the original. This option is ignored for remove operations. The
     *    The default is false.
     *
     *  * query (document): Query by which to filter documents.
     *
     *  * remove (boolean): When true, removes the matched document. This option
     *    cannot be true if the update option is set. The default is false.
     *
106 107 108 109
     *  * session (MongoDB\Driver\Session): Client session.
     *
     *    Sessions are not supported for server versions < 3.6.
     *
110 111 112
     *  * sort (document): Determines which document the operation modifies if
     *    the query selects multiple documents.
     *
113 114
     *  * typeMap (array): Type map for BSON deserialization.
     *
115 116 117 118 119 120 121
     *  * update (document): Update or replacement to apply to the matched
     *    document. This option cannot be set if the remove option is true.
     *
     *  * upsert (boolean): When true, a new document is created if no document
     *    matches the query. This option is ignored for remove operations. The
     *    default is false.
     *
122 123
     *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
     *
124 125
     *    This is not supported for server versions < 3.2 and will result in an
     *    exception at execution time if used.
126
     *
127 128 129
     * @param string $databaseName   Database name
     * @param string $collectionName Collection name
     * @param array  $options        Command options
130
     * @throws InvalidArgumentException for parameter/option parsing errors
131 132 133
     */
    public function __construct($databaseName, $collectionName, array $options)
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
134
        $options += [
135 136 137
            'new' => false,
            'remove' => false,
            'upsert' => false,
Jeremy Mikola's avatar
Jeremy Mikola committed
138
        ];
139

140 141 142 143
        if (isset($options['arrayFilters']) && ! is_array($options['arrayFilters'])) {
            throw InvalidArgumentException::invalidType('"arrayFilters" option', $options['arrayFilters'], 'array');
        }

144
        if (isset($options['bypassDocumentValidation']) && ! is_bool($options['bypassDocumentValidation'])) {
145
            throw InvalidArgumentException::invalidType('"bypassDocumentValidation" option', $options['bypassDocumentValidation'], 'boolean');
146 147
        }

148 149 150 151
        if (isset($options['collation']) && ! is_array($options['collation']) && ! is_object($options['collation'])) {
            throw InvalidArgumentException::invalidType('"collation" option', $options['collation'], 'array or object');
        }

152
        if (isset($options['fields']) && ! is_array($options['fields']) && ! is_object($options['fields'])) {
153
            throw InvalidArgumentException::invalidType('"fields" option', $options['fields'], 'array or object');
154 155 156
        }

        if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
157
            throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
158 159
        }

160
        if (! is_bool($options['new'])) {
161
            throw InvalidArgumentException::invalidType('"new" option', $options['new'], 'boolean');
162 163 164
        }

        if (isset($options['query']) && ! is_array($options['query']) && ! is_object($options['query'])) {
165
            throw InvalidArgumentException::invalidType('"query" option', $options['query'], 'array or object');
166 167
        }

168
        if (! is_bool($options['remove'])) {
169
            throw InvalidArgumentException::invalidType('"remove" option', $options['remove'], 'boolean');
170 171
        }

172
        if (isset($options['session']) && ! $options['session'] instanceof Session) {
173
            throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
174 175
        }

176
        if (isset($options['sort']) && ! is_array($options['sort']) && ! is_object($options['sort'])) {
177
            throw InvalidArgumentException::invalidType('"sort" option', $options['sort'], 'array or object');
178 179
        }

180 181 182 183
        if (isset($options['typeMap']) && ! is_array($options['typeMap'])) {
            throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array');
        }

184
        if (isset($options['update']) && ! is_array($options['update']) && ! is_object($options['update'])) {
185
            throw InvalidArgumentException::invalidType('"update" option', $options['update'], 'array or object');
186 187
        }

188
        if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
189
            throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], WriteConcern::class);
190 191
        }

192
        if (! is_bool($options['upsert'])) {
193
            throw InvalidArgumentException::invalidType('"upsert" option', $options['upsert'], 'boolean');
194 195
        }

196
        if (! (isset($options['update']) xor $options['remove'])) {
197 198 199
            throw new InvalidArgumentException('The "remove" option must be true or an "update" document must be specified, but not both');
        }

200 201 202 203
        if (isset($options['writeConcern']) && $options['writeConcern']->isDefault()) {
            unset($options['writeConcern']);
        }

204 205 206 207 208 209 210 211 212 213
        $this->databaseName = (string) $databaseName;
        $this->collectionName = (string) $collectionName;
        $this->options = $options;
    }

    /**
     * Execute the operation.
     *
     * @see Executable::execute()
     * @param Server $server
214
     * @return array|object|null
215
     * @throws UnexpectedValueException if the command response was malformed
216
     * @throws UnsupportedException if array filters, collation, or write concern is used and unsupported
217
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
218 219 220
     */
    public function execute(Server $server)
    {
221
        if (isset($this->options['arrayFilters']) && ! server_supports_feature($server, self::$wireVersionForArrayFilters)) {
222 223 224
            throw UnsupportedException::arrayFiltersNotSupported();
        }

225
        if (isset($this->options['collation']) && ! server_supports_feature($server, self::$wireVersionForCollation)) {
226 227 228
            throw UnsupportedException::collationNotSupported();
        }

229
        if (isset($this->options['writeConcern']) && ! server_supports_feature($server, self::$wireVersionForWriteConcern)) {
230 231 232
            throw UnsupportedException::writeConcernNotSupported();
        }

233 234 235 236 237
        $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
        if ($inTransaction && isset($this->options['writeConcern'])) {
            throw UnsupportedException::writeConcernNotSupportedInTransaction();
        }

Jeremy Mikola's avatar
Jeremy Mikola committed
238
        $cursor = $server->executeWriteCommand($this->databaseName, new Command($this->createCommandDocument($server)), $this->createOptions());
239

240
        if (isset($this->options['typeMap'])) {
241
            $cursor->setTypeMap(create_field_path_type_map($this->options['typeMap'], 'value'));
242 243
        }

244 245 246
        $result = current($cursor->toArray());

        return isset($result->value) ? $result->value : null;
247 248
    }

249
    public function getCommandDocument(Server $server)
250
    {
251
        return $this->createCommandDocument($server);
252 253 254 255 256
    }

    /**
     * Create the findAndModify command document.
     *
257
     * @param Server $server
258 259
     * @return array
     */
260
    private function createCommandDocument(Server $server)
261
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
262
        $cmd = ['findAndModify' => $this->collectionName];
263 264 265 266 267 268 269 270

        if ($this->options['remove']) {
            $cmd['remove'] = true;
        } else {
            $cmd['new'] = $this->options['new'];
            $cmd['upsert'] = $this->options['upsert'];
        }

271
        foreach (['collation', 'fields', 'query', 'sort'] as $option) {
272 273 274 275 276
            if (isset($this->options[$option])) {
                $cmd[$option] = (object) $this->options[$option];
            }
        }

277 278 279 280 281 282
        if (isset($this->options['update'])) {
            $cmd['update'] = is_pipeline($this->options['update'])
                ? $this->options['update']
                : (object) $this->options['update'];
        }

283 284 285 286
        if (isset($this->options['arrayFilters'])) {
            $cmd['arrayFilters'] = $this->options['arrayFilters'];
        }

287 288 289 290
        if (isset($this->options['maxTimeMS'])) {
            $cmd['maxTimeMS'] = $this->options['maxTimeMS'];
        }

291 292
        if (! empty($this->options['bypassDocumentValidation']) &&
            server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
293
        ) {
294 295 296
            $cmd['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
        }

297
        return $cmd;
298 299 300 301 302
    }

    /**
     * Create options for executing the command.
     *
303
     * @see http://php.net/manual/en/mongodb-driver-server.executewritecommand.php
304 305 306 307 308 309
     * @return array
     */
    private function createOptions()
    {
        $options = [];

310 311 312 313
        if (isset($this->options['session'])) {
            $options['session'] = $this->options['session'];
        }

314
        if (isset($this->options['writeConcern'])) {
315
            $options['writeConcern'] = $this->options['writeConcern'];
316 317
        }

318
        return $options;
319 320
    }
}