FindOneAndUpdate.php 6.09 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\Operation;

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 26 27
use function is_array;
use function is_integer;
use function is_object;
use function MongoDB\is_first_key_operator;
28
use function MongoDB\is_pipeline;
29 30 31 32 33

/**
 * Operation for updating a document with the findAndModify command.
 *
 * @api
34
 * @see \MongoDB\Collection::findOneAndUpdate()
35 36
 * @see http://docs.mongodb.org/manual/reference/command/findAndModify/
 */
37
class FindOneAndUpdate implements Executable, Explainable
38 39 40 41
{
    const RETURN_DOCUMENT_BEFORE = 1;
    const RETURN_DOCUMENT_AFTER = 2;

42
    /** @var FindAndModify */
43 44 45 46 47 48 49
    private $findAndModify;

    /**
     * Constructs a findAndModify command for updating a document.
     *
     * Supported options:
     *
50 51 52
     *  * arrayFilters (document array): A set of filters specifying to which
     *    array elements an update should apply.
     *
53 54 55 56 57
     *  * 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.
58
     *
59 60 61 62 63
     *  * collation (document): Collation specification.
     *
     *    This is not supported for server versions < 3.4 and will result in an
     *    exception at execution time if used.
     *
64 65 66 67 68 69 70
     *  * maxTimeMS (integer): The maximum amount of time to allow the query to
     *    run.
     *
     *  * projection (document): Limits the fields to return for the matching
     *    document.
     *
     *  * returnDocument (enum): Whether to return the document before or after
71 72 73 74
     *    the update is applied. Must be either
     *    FindOneAndUpdate::RETURN_DOCUMENT_BEFORE or
     *    FindOneAndUpdate::RETURN_DOCUMENT_AFTER. The default is
     *    FindOneAndUpdate::RETURN_DOCUMENT_BEFORE.
75
     *
76 77 78 79
     *  * session (MongoDB\Driver\Session): Client session.
     *
     *    Sessions are not supported for server versions < 3.6.
     *
80 81 82
     *  * sort (document): Determines which document the operation modifies if
     *    the query selects multiple documents.
     *
83 84
     *  * typeMap (array): Type map for BSON deserialization.
     *
85 86 87
     *  * upsert (boolean): When true, a new document is created if no document
     *    matches the query. The default is false.
     *
88 89 90 91
     *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
     *
     *    This is not supported for server versions < 3.2 and will result in an
     *    exception at execution time if used.
92
     *
93 94 95 96 97
     * @param string       $databaseName   Database name
     * @param string       $collectionName Collection name
     * @param array|object $filter         Query by which to filter documents
     * @param array|object $update         Update to apply to the matched document
     * @param array        $options        Command options
98
     * @throws InvalidArgumentException for parameter/option parsing errors
99
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
100
    public function __construct($databaseName, $collectionName, $filter, $update, array $options = [])
101
    {
102
        if (! is_array($filter) && ! is_object($filter)) {
103
            throw InvalidArgumentException::invalidType('$filter', $filter, 'array or object');
104 105
        }

106
        if (! is_array($update) && ! is_object($update)) {
107
            throw InvalidArgumentException::invalidType('$update', $update, 'array or object');
108 109
        }

110 111
        if (! is_first_key_operator($update) && ! is_pipeline($update)) {
            throw new InvalidArgumentException('Expected an update document with operator as first key or a pipeline');
112 113
        }

Jeremy Mikola's avatar
Jeremy Mikola committed
114
        $options += [
115 116
            'returnDocument' => self::RETURN_DOCUMENT_BEFORE,
            'upsert' => false,
Jeremy Mikola's avatar
Jeremy Mikola committed
117
        ];
118 119

        if (isset($options['projection']) && ! is_array($options['projection']) && ! is_object($options['projection'])) {
120
            throw InvalidArgumentException::invalidType('"projection" option', $options['projection'], 'array or object');
121 122
        }

123
        if (! is_integer($options['returnDocument'])) {
124
            throw InvalidArgumentException::invalidType('"returnDocument" option', $options['returnDocument'], 'integer');
125 126 127 128 129 130 131
        }

        if ($options['returnDocument'] !== self::RETURN_DOCUMENT_AFTER &&
            $options['returnDocument'] !== self::RETURN_DOCUMENT_BEFORE) {
            throw new InvalidArgumentException('Invalid value for "returnDocument" option: ' . $options['returnDocument']);
        }

132 133
        if (isset($options['projection'])) {
            $options['fields'] = $options['projection'];
134 135
        }

136 137 138
        $options['new'] = $options['returnDocument'] === self::RETURN_DOCUMENT_AFTER;

        unset($options['projection'], $options['returnDocument']);
139 140 141 142

        $this->findAndModify = new FindAndModify(
            $databaseName,
            $collectionName,
Jeremy Mikola's avatar
Jeremy Mikola committed
143
            ['query' => $filter, 'update' => $update] + $options
144 145 146 147 148 149 150 151
        );
    }

    /**
     * Execute the operation.
     *
     * @see Executable::execute()
     * @param Server $server
152
     * @return array|object|null
153
     * @throws UnsupportedException if collation or write concern is used and unsupported
154
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
155 156 157 158 159
     */
    public function execute(Server $server)
    {
        return $this->findAndModify->execute($server);
    }
160

161
    public function getCommandDocument(Server $server)
162
    {
163
        return $this->findAndModify->getCommandDocument($server);
164
    }
165
}