-
Notifications
You must be signed in to change notification settings - Fork 462
Expand file tree
/
Copy pathCollectionReference.php
More file actions
339 lines (316 loc) · 10.3 KB
/
CollectionReference.php
File metadata and controls
339 lines (316 loc) · 10.3 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
<?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\ApiCore\ApiException;
use Google\ApiCore\Options\CallOptions;
use Google\Cloud\Core\ApiHelperTrait;
use Google\Cloud\Core\DebugInfoTrait;
use Google\Cloud\Core\Iterator\ItemIterator;
use Google\Cloud\Core\Iterator\PageIterator;
use Google\Cloud\Core\OptionsValidator;
use Google\Cloud\Core\RequestProcessorTrait;
use Google\Cloud\Core\TimestampTrait;
use Google\Cloud\Firestore\V1\Client\FirestoreClient;
use Google\Cloud\Firestore\V1\ListDocumentsRequest;
/**
* Represents a Cloud Firestore Collection.
*
* Collections are implicit namespaces for Firestore Documents. They are created
* when the first document is inserted, and cease to exist when the last
* document is removed.
*
* Example:
* ```
* use Google\Cloud\Firestore\FirestoreClient;
*
* $firestore = new FirestoreClient();
* $collection = $firestore->collection('users');
* ```
*/
class CollectionReference extends Query
{
use ApiHelperTrait;
use DebugInfoTrait;
use PathTrait;
use TimestampTrait;
use RequestProcessorTrait;
private FirestoreClient $gapicClient;
private ValueMapper $valueMapper;
private String $name;
private DocumentReference|null $parent = null;
private Serializer $serializer;
private OptionsValidator $optionsValidator;
/**
* @param FirestoreClient $firestoreClient A Connection to Cloud Firestore.
* This object is created by FirestoreClient,
* and should not be instantiated outside of this client.
* @param ValueMapper $valueMapper A Firestore Value Mapper.
* @param string $name The absolute name of the collection.
*/
public function __construct(
FirestoreClient $firestoreClient,
ValueMapper $valueMapper,
$name
) {
$this->gapicClient = $firestoreClient;
$this->valueMapper = $valueMapper;
$this->name = $name;
$this->serializer = new Serializer();
$this->optionsValidator = new OptionsValidator($this->serializer);
parent::__construct(
$this->gapicClient,
$valueMapper,
$this->parentPath($this->name),
[
'from' => [
[
'collectionId' => $this->pathId($this->name)
]
]
]
);
}
/**
* Get the collection name.
*
* Names are absolute. The result of this call would be of the form
* `projects/<project-id>/databases/<database-id>/documents/<relative-path>`.
*
* Other methods are available to retrieve different parts of a collection name:
* * {@see \Google\Cloud\Firestore\CollectionReference::id()} Returns the last element.
* * {@see \Google\Cloud\Firestore\CollectionReference::path()} Returns the path, relative to the database.
*
* Example:
* ```
* $name = $collection->name();
* ```
*
* @return string
*/
public function name()
{
return $this->name;
}
/**
* Get the collection path.
*
* Paths identify the location of a collection, relative to the database name.
*
* To retrieve the collection ID (the last element of the path), use
* {@see \Google\Cloud\Firestore\CollectionReference::id()}.
*
* Example:
* ```
* $path = $collection->path();
* ```
*
* @return string
*/
public function path()
{
return $this->relativeName($this->name);
}
/**
* Get the collection ID.
*
* IDs are the path element which identifies a resource. To retrieve the
* full path to a resource (the resource name), use
* {@see \Google\Cloud\Firestore\CollectionReference::name()}.
*
* Example:
* ```
* $id = $collection->id();
* ```
*
* @return string
*/
public function id()
{
return $this->pathId($this->name);
}
/**
* Get a reference to a document which is a direct child of this collection.
*
* Example:
* ```
* $newUser = $collection->document('john');
* ```
*
* @param string $documentId The document ID.
* @return DocumentReference
*/
public function document($documentId)
{
return $this->documentFactory($this->childPath($this->name, $documentId));
}
/**
* Get a document reference with a randomly generated document ID.
*
* If you wish to create a document reference with a specified name, use
* {@see \Google\Cloud\Firestore\CollectionReference::document()}.
*
* This method does NOT insert the document until you call
* {@see \Google\Cloud\Firestore\DocumentReference::create()}.
*
* Example:
* ```
* $newUser = $collection->newDocument();
* ```
*
* @return DocumentReference
*/
public function newDocument()
{
return $this->documentFactory($this->randomName($this->name));
}
/**
* Generate a new document reference, and insert it with the given field data.
*
* This method will generate a random document name. If you wish to create a
* document with a specified name, create a reference with
* {@see \Google\Cloud\Firestore\CollectionReference::document()}, then call
* {@see \Google\Cloud\Firestore\DocumentReference::create()} to insert the
* document.
*
* This method immediately inserts the document. If you wish for lazy
* creation of a Document instance, refer to
* {@see \Google\Cloud\Firestore\CollectionReference::document()} or
* {@see \Google\Cloud\Firestore\CollectionReference::newDocument()}.
*
* Example:
* ```
* $newUser = $collection->add([
* 'name' => 'Kate'
* ]);
* ```
*
* @param array $fields An array containing field names paired with their value.
* Accepts a nested array, or a simple array of field paths.
* @param array $options Configuration Options.
* @return DocumentReference
*/
public function add(array $fields = [], array $options = [])
{
$name = $this->randomName($this->name);
$document = $this->documentFactory($name);
$result = $document->create($fields, $options);
return $document;
}
/**
* List all documents in the collection.
*
* Missing documents will be included in the result. A missing document is
* one which does not exist, but has sub-documents.
*
* Example:
* ```
* $documents = $collection->listDocuments();
* foreach ($documents as $document) {
* echo $document->name() . PHP_EOL;
* }
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1beta1#google.firestore.v1beta1.ListDocumentsRequest ListDocumentsRequest
* @codingStandardsIgnoreEnd
*
* @param array $options {
* Configuration options
*
* @type int $pageSize The maximum number of results to return per
* request.
* @type int $resultLimit Limit the number of results returned in total.
* **Defaults to** `0` (return all results).
* @type string $pageToken A previously-returned page token used to
* resume the loading of results from a specific point.
* }
* @return ItemIterator<DocumentReference>
* @throws \InvalidArgumentException if an invalid `$options.readTime` is
* specified.
*/
public function listDocuments(array $options = [])
{
$resultLimit = $this->pluck('resultLimit', $options, false);
$options += [
'parent' => $this->parentPath($this->name),
'collectionId' => $this->pathId($this->name),
'mask' => []
];
$options = $this->formatReadTimeOption($options);
/**
* @var ListDocumentsRequest $request
* @var CallOptions $callOptions
*/
[$request, $callOptions] = $this->validateOptions(
$options,
new ListDocumentsRequest(),
CallOptions::class
);
$listDocumentsCall = function (array $callOptions) use ($request) {
try {
$response = $this->gapicClient->listDocuments($request, $callOptions);
} catch (ApiException $ex) {
throw $this->convertToGoogleException($ex);
}
$page = $response->getPage();
return $this->serializer->encodeMessage($page->getResponseObject());
};
return new ItemIterator(
new PageIterator(
function ($document) {
return $this->documentFactory($document['name']);
},
$listDocumentsCall,
$options,
[
'itemsKey' => 'documents',
'resultLimit' => $resultLimit
]
)
);
}
/**
* Get the parent document reference for a subcollection, or null if root.
*
* Example:
* ```
* $parent = $collection->parent();
* ```
*
* @return DocumentReference|null
*/
public function parent()
{
if (!isset($this->parent)) {
$parentPath = $this->parentPath($this->name);
if ($this->isDocument($parentPath)) {
$this->parent = $this->documentFactory($parentPath);
}
}
return $this->parent;
}
/**
* Create a document instance with the given document name.
*
* @param string $name The document name.
* @return DocumentReference
*/
private function documentFactory($name)
{
return new DocumentReference($this->gapicClient, $this->valueMapper, $this, $name);
}
}