-
Notifications
You must be signed in to change notification settings - Fork 460
Expand file tree
/
Copy pathTransaction.php
More file actions
376 lines (356 loc) · 12.2 KB
/
Transaction.php
File metadata and controls
376 lines (356 loc) · 12.2 KB
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
<?php
/**
* Copyright 2017 Google 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.
*/
namespace Google\Cloud\Firestore;
use Google\Cloud\Core\ApiHelperTrait;
use Google\Cloud\Core\DebugInfoTrait;
use Google\Cloud\Core\OptionsValidator;
use Google\Cloud\Core\Timestamp;
use Google\Cloud\Firestore\V1\Client\FirestoreClient;
/**
* Represents a Firestore transaction.
*
* This class should be accessed inside a transaction callable, obtained via
* {@see \Google\Cloud\Firestore\FirestoreClient::runTransaction()}.
*
* Note that method examples, while shown as being called directly for the sake
* of brevity, should be called only within the context of a transaction
* callable, as noted above.
*
* Example:
* ```
* use Google\Cloud\Firestore\FirestoreClient;
* use Google\Cloud\Firestore\Transaction;
*
* $firestore = new FirestoreClient();
* $document = $firestore->document('users/john');
* $firestore->runTransaction(function (Transaction $transaction) use ($document) {
* // Manage Transaction.
* });
* ```
*/
class Transaction
{
use ApiHelperTrait;
use SnapshotTrait;
use DebugInfoTrait;
private FirestoreClient $gapicClient;
private ValueMapper $valueMapper;
private string $transaction;
private string $database;
private BulkWriter $writer;
private Serializer $serializer;
private OptionsValidator $optionsValidator;
/**
* @param FirestoreClient $firestoreClient A FirestoreClient instance.
* @param ValueMapper $valueMapper A Firestore Value Mapper.
* @param string $database The database name.
* @param string $transaction The transaction ID.
*/
public function __construct(
FirestoreClient $firestoreClient,
ValueMapper $valueMapper,
$database,
$transaction
) {
$this->gapicClient = $firestoreClient;
$this->valueMapper = $valueMapper;
$this->database = $database;
$this->transaction = $transaction;
$this->serializer = new Serializer();
$this->optionsValidator = new OptionsValidator($this->serializer);
$this->writer = new BulkWriter($this->gapicClient, $valueMapper, $database, $transaction);
}
/**
* Get a Document Snapshot.
*
* Example:
* ```
* $snapshot = $transaction->snapshot($document);
* ```
*
* @param DocumentReference $document The document to retrieve.
* @param array $options Configuration options.
* @return DocumentSnapshot
*/
public function snapshot(DocumentReference $document, array $options = [])
{
return $this->createSnapshot($this->gapicClient, $this->valueMapper, $document, [
'transaction' => $this->transaction,
] + $options);
}
/**
* Get an Aggregate Query Snapshot.
*
* Example:
* ```
* $snapshot = $transaction->runAggregateQuery($aggregateQuery);
* ```
*
* @param AggregateQuery $aggregateQuery The aggregate query to retrieve.
* @param array $options {
* Configuration Options
*
* @type Timestamp $readTime Reads entities as they were at the given timestamp.
* }
* @return AggregateQuerySnapshot
* @throws \InvalidArgumentException if an invalid `$options.readTime` is specified.
*/
public function runAggregateQuery(AggregateQuery $aggregateQuery, array $options = [])
{
if (isset($options['readTime'])) {
if (!($options['readTime'] instanceof Timestamp)) {
throw new \InvalidArgumentException(sprintf(
'`$options.readTime` must be an instance of %s',
Timestamp::class
));
}
$options['readTime'] = $options['readTime']->formatForApi();
}
return $aggregateQuery->getSnapshot([
'transaction' => $this->transaction
] + $options);
}
/**
* Get a list of documents by their path.
*
* The number of results generated will be equal to the number of documents
* requested, except in case of error.
*
* Note that this method will **always** return instances of
* {@see \Google\Cloud\Firestore\DocumentSnapshot}, even if the documents
* requested do not exist. It is highly recommended that you check for
* existence before accessing document data.
*
* Example:
* ```
* $documents = $transaction->documents([
* 'users/john',
* 'users/dave'
* ]);
* ```
*
* ```
* // To check whether a given document exists, use `DocumentSnapshot::exists()`.
* $documents = $transaction->documents([
* 'users/deleted-user'
* ]);
*
* foreach ($documents as $document) {
* if (!$document->exists()) {
* echo $document->id() . ' Does Not Exist';
* }
* }
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1beta1#google.firestore.v1beta1.Firestore.BatchGetDocuments BatchGetDocuments
* @codingStandardsIgnoreEnd
*
* @param string[]|DocumentReference[] $paths Any combination of string paths or DocumentReference instances.
* @param array $options Configuration options.
* @return DocumentSnapshot[]
*/
public function documents(array $paths, array $options = [])
{
return $this->getDocumentsByPaths(
$this->gapicClient,
$this->valueMapper,
$this->projectIdFromName($this->database),
$this->databaseIdFromName($this->database),
$paths,
[
'transaction' => $this->transaction
] + $options
);
}
/**
* Run a Query inside the Transaction.
*
* Example:
* ```
* $results = $transaction->runQuery($query);
* ```
*
* @param Query $query A Firestore Query.
* @param array $options Configuration options.
* @return QuerySnapshot
*/
public function runQuery(Query $query, array $options = [])
{
return $query->documents([
'transaction' => $this->transaction
] + $options);
}
/**
* Enqueue an operation to create a Firestore document.
*
* Example:
* ```
* $transaction->create($document, [
* 'name' => 'John',
* 'country' => 'USA'
* ]);
* ```
*
* @param DocumentReference $document The document to create.
* @param array $fields An array containing fields, where keys are the field
* names, and values are field values. Nested arrays are allowed.
* Note that unlike
* {@see \Google\Cloud\Firestore\DocumentReference::update()}, field
* paths are NOT supported by this method.
* @return Transaction
*/
public function create(DocumentReference $document, array $fields)
{
$this->writer->create($document->name(), $fields);
return $this;
}
/**
* Enqueue an operation to modify or replace a Firestore document.
*
* Example:
* ```
* // In this example, all field not explicitly specified will be removed.
* $transaction->set($document, [
* 'name' => 'Johnny'
* ]);
* ```
*
* ```
* // To specify MERGE over REPLACE, set `$options.merge` to `true`.
* $transaction->set($document, [
* 'name' => 'Johnny'
* ], [
* 'merge' => true
* ]);
* ```
*
* @param DocumentReference $document The document to modify or replace.
* @param array $fields An array containing fields, where keys are the field
* names, and values are field values. Nested arrays are allowed.
* Note that unlike {@see \Google\Cloud\Firestore\Transaction::update()},
* field paths are NOT supported by this method.
* @param array $options {
* Configuration options.
*
* @type bool $merge If true, unwritten fields will be preserved.
* Otherwise, they will be overwritten (removed). **Defaults to**
* `false`.
* }
* @return Transaction
*/
public function set(DocumentReference $document, array $fields, array $options = [])
{
$this->writer->set($document->name(), $fields, $options);
return $this;
}
/**
* Enqueue an update with field paths and values.
*
* Merges provided data with data stored in Firestore.
*
* Calling this method on a non-existent document will raise an exception.
*
* This method supports various sentinel values, to perform special operations
* on fields. Available sentinel values are provided as methods, found in
* {@see \Google\Cloud\Firestore\FieldValue}.
*
* Note that field names must be provided using field paths, encoded either
* as a dot-delimited string (i.e. `foo.bar`), or an instance of
* {@see \Google\Cloud\Firestore\FieldPath}. Nested arrays are not allowed.
*
* Please note that conflicting paths will result in an exception. Paths
* conflict when one path indicates a location nested within another path.
* For instance, path `a.b` cannot be set directly if path `a` is also
* provided.
*
* Example:
* ```
* $transaction->update($document, [
* ['path' => 'name', 'value' => 'John'],
* ['path' => 'country', 'value' => 'USA'],
* ['path' => 'cryptoCurrencies.bitcoin', 'value' => 0.5],
* ['path' => 'cryptoCurrencies.ethereum', 'value' => 10],
* ['path' => 'cryptoCurrencies.litecoin', 'value' => 5.51]
* ]);
* ```
*
* ```
* // Google Cloud PHP provides special field values to enable operations such
* // as deleting fields or setting the value to the current server timestamp.
* use Google\Cloud\Firestore\FieldValue;
*
* $transaction->update($document, [
* ['path' => 'country', 'value' => FieldValue::deleteField()],
* ['path' => 'lastLogin', 'value' => FieldValue::serverTimestamp()]
* ]);
* ```
*
* ```
* // If your field names contain special characters (such as `.`, or symbols),
* // using {@see \Google\Cloud\Firestore\FieldPath} will properly escape each element.
*
* use Google\Cloud\Firestore\FieldPath;
*
* $transaction->update($document, [
* ['path' => new FieldPath(['cryptoCurrencies', 'big$$$coin']), 'value' => 5.51]
* ]);
* ```
*
* @param DocumentReference $document The document to modify or replace.
* @param array[] $data A list of arrays of form
* `[FieldPath|string $path, mixed $value]`.
* @param array $options Configuration options
* @return Transaction
* @throws \InvalidArgumentException If data is given in an invalid format
* or is empty.
* @throws \InvalidArgumentException If any field paths are empty.
* @throws \InvalidArgumentException If field paths conflict.
*/
public function update(DocumentReference $document, array $data, array $options = [])
{
$this->writer->update($document->name(), $data, $options);
return $this;
}
/**
* Enqueue an operation to delete a Firestore document.
*
* Example:
* ```
* $transaction->delete($document);
* ```
*
* @param DocumentReference $document The document to delete.
* @param array $options Configuration Options.
* @return Transaction
*/
public function delete(DocumentReference $document, array $options = [])
{
$this->writer->delete($document->name(), $options);
return $this;
}
/**
* Get the BulkWriter object.
*
* @access private
* @return BulkWriter
*/
public function writer()
{
return $this->writer;
}
}