-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathQuery.php
More file actions
1220 lines (1107 loc) · 40.9 KB
/
Query.php
File metadata and controls
1220 lines (1107 loc) · 40.9 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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\ExponentialBackoff;
use Google\Cloud\Core\OptionsValidator;
use Google\Cloud\Core\RequestProcessorTrait;
use Google\Cloud\Firestore\FieldValue\FieldValueInterface;
use Google\Cloud\Firestore\V1\Client\FirestoreClient as GapicFirestoreClient;
use Google\Cloud\Firestore\V1\ExplainMetrics;
use Google\Cloud\Firestore\V1\RunQueryRequest;
use Google\Cloud\Firestore\V1\StructuredQuery\CompositeFilter\Operator;
use Google\Cloud\Firestore\V1\StructuredQuery\Direction;
use Google\Cloud\Firestore\V1\StructuredQuery\FieldFilter\Operator as FieldFilterOperator;
use Google\Cloud\Firestore\V1\StructuredQuery\UnaryFilter\Operator as UnaryFilterOperator;
use InvalidArgumentException;
/**
* A Cloud Firestore Query.
*
* This class is immutable; any filters applied will return a new instance of
* the class.
*
* Example:
* ```
* use Google\Cloud\Firestore\FirestoreClient;
*
* $firestore = new FirestoreClient();
*
* $collection = $firestore->collection('users');
* $query = $collection->where('age', '>', 18);
* ```
*/
class Query
{
use ApiHelperTrait;
use DebugInfoTrait;
use SnapshotTrait;
use QueryTrait;
use RequestProcessorTrait;
/**
* @deprecated
*/
const OP_LESS_THAN = FieldFilterOperator::LESS_THAN;
/**
* @deprecated
*/
const OP_LESS_THAN_OR_EQUAL = FieldFilterOperator::LESS_THAN_OR_EQUAL;
/**
* @deprecated
*/
const OP_GREATER_THAN = FieldFilterOperator::GREATER_THAN;
/**
* @deprecated
*/
const OP_GREATER_THAN_OR_EQUAL = FieldFilterOperator::GREATER_THAN_OR_EQUAL;
/**
* @deprecated
*/
const OP_EQUAL = FieldFilterOperator::EQUAL;
/**
* @deprecated
*/
const OP_ARRAY_CONTAINS = FieldFilterOperator::ARRAY_CONTAINS;
const OP_NAN = UnaryFilterOperator::IS_NAN;
const OP_NULL = UnaryFilterOperator::IS_NULL;
const DIR_ASCENDING = Direction::ASCENDING;
const DIR_DESCENDING = Direction::DESCENDING;
const DOCUMENT_ID = '__name__';
private $shortOperators = [
'<' => FieldFilterOperator::LESS_THAN,
'<=' => FieldFilterOperator::LESS_THAN_OR_EQUAL,
'>' => FieldFilterOperator::GREATER_THAN,
'>=' => FieldFilterOperator::GREATER_THAN_OR_EQUAL,
'=' => FieldFilterOperator::EQUAL,
'!=' => FieldFilterOperator::NOT_EQUAL,
'==' => FieldFilterOperator::EQUAL,
'===' => FieldFilterOperator::EQUAL,
'array-contains' => FieldFilterOperator::ARRAY_CONTAINS,
'array-contains-any' => FieldFilterOperator::ARRAY_CONTAINS_ANY,
'in' => FieldFilterOperator::IN,
'not_in' => FieldFilterOperator::NOT_IN,
];
private $allowedDirections = [
self::DIR_ASCENDING,
self::DIR_DESCENDING
];
private $shortDirections = [
'ASC' => self::DIR_ASCENDING,
'ASCENDING' => self::DIR_ASCENDING,
'DESC' => self::DIR_DESCENDING,
'DESCENDING' => self::DIR_DESCENDING
];
private GapicFirestoreClient $gapicClient;
private ValueMapper $valueMapper;
private string $parentName;
private array $query;
private bool $limitToLast;
private Serializer $serializer;
private OptionsValidator $optionsValidator;
/**
* @param GapicFirestoreClient $firestoreClient A FirestoreClient instance.
* @param ValueMapper $valueMapper A Firestore Value Mapper.
* @param string $parent The parent of the query.
* @param array $query The Query object
* @param bool $limitToLast Limit a query to return only the last matching documents.
* @throws \InvalidArgumentException If the query does not provide a valid selector.
*/
public function __construct(
GapicFirestoreClient $firestoreClient,
ValueMapper $valueMapper,
$parent,
array $query,
$limitToLast = false
) {
$this->gapicClient = $firestoreClient;
$this->valueMapper = $valueMapper;
$this->parentName = $parent;
$this->query = $query;
$this->limitToLast = $limitToLast;
$this->serializer = new Serializer();
$this->optionsValidator = new OptionsValidator($this->serializer);
if (!isset($this->query['from'])) {
throw new \InvalidArgumentException(
'Cannot instantiate a query which does not specify a collection selector (`from`).'
);
}
}
/**
* Gets the count of all documents matching the provided query filters.
*
* Example:
* ```
* $count = $query->count();
* ```
*
* @param array $options [optional] {
* Configuration options is an array.
*
* @type Timestamp $readTime Reads entities as they were at the given timestamp.
* }
* @return int
*/
public function count(array $options = [])
{
if (isset($options['explainOptions'])) {
throw new InvalidArgumentException(
'The explainOptions option is not supported in the ' . __FUNCTION__ . ' method'
);
}
$aggregateQuery = $this->addAggregation(Aggregate::count()->alias('count'));
$aggregationResult = $aggregateQuery->getSnapshot($options);
return $aggregationResult->get('count');
}
/**
* Gets the sum of all documents matching the provided query filters.
*
* Example:
* ```
* $sum = $query->sum();
* ```
*
* Sum of integers which exceed maximum integer value returns a float.
* Sum of numbers exceeding max float value returns `INF`.
* Sum of data which contains `NaN` returns `NaN`.
* Non numeric values are ignored.
*
* @param string $field The relative path of the field to aggregate upon.
* @param array $options [optional] {
* Configuration options is an array.
*
* @type Timestamp $readTime Reads entities as they were at the given timestamp.
* }
* @return int|float
*/
public function sum(string $field, array $options = [])
{
if (isset($options['explainOptions'])) {
throw new InvalidArgumentException(
'The explainOptions option is not supported in the ' . __FUNCTION__ . ' method'
);
}
$aggregateQuery = $this->addAggregation(Aggregate::sum($field)->alias('sum'));
$aggregationResult = $aggregateQuery->getSnapshot($options);
return $aggregationResult->get('sum');
}
/**
* Gets the average of all documents matching the provided query filters.
*
* Example:
* ```
* $avg = $query->avg();
* ```
*
* Average of empty valid data set return `null`.
* Average of numbers exceeding max float value returns `INF`.
* Average of data which contains `NaN` returns `NaN`.
* Non numeric values are ignored.
*
* @param string $field The relative path of the field to aggregate upon.
* @param array $options [optional] {
* Configuration options is an array.
*
* @type Timestamp $readTime Reads entities as they were at the given timestamp.
* }
* @return float|null
*/
public function avg(string $field, array $options = [])
{
if (isset($options['explainOptions'])) {
throw new InvalidArgumentException(
'The explainOptions option is not supported in the ' . __FUNCTION__ . ' method'
);
}
$aggregateQuery = $this->addAggregation(Aggregate::avg($field)->alias('avg'));
$aggregationResult = $aggregateQuery->getSnapshot($options);
return $aggregationResult->get('avg');
}
/**
* Returns an aggregate query provided an aggregation with existing query filters.
*
* Example:
* ```
* use Google\Cloud\Firestore\Aggregate;
*
* $aggregation = Aggregate::count()->alias('count_upto_1');
* $aggregateQuery = $query->limit(1)->addAggregation($aggregation);
* $aggregateQuerySnapshot = $aggregateQuery->getSnapshot();
* $countUpto1 = $aggregateQuerySnapshot->get('count_upto_1');
* ```
*
* @param Aggregate $aggregate Aggregate properties to be applied over query.
* @return AggregateQuery
*/
public function addAggregation($aggregate)
{
$aggregateQuery = new AggregateQuery(
$this->gapicClient,
$this->parentName,
[
'query' => $this->query,
'limitToLast' => $this->limitToLast
],
$aggregate
);
return $aggregateQuery;
}
/**
* Get all documents matching the provided query filters.
*
* Example:
* ```
* $result = $query->documents();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1beta1#google.firestore.v1beta1.Firestore.RunQuery RunQuery
* @codingStandardsIgnoreEnd
* @param array $options {
* Configuration options.
*
* @type int $maxRetries The maximum number of times to retry a query.
* **Defaults to** `5`.
* }
* @return QuerySnapshot<DocumentSnapshot>
* @throws \InvalidArgumentException if an invalid `$options.readTime` is
* specified.
* @throws \RuntimeException If limit-to-last is enabled but no order-by has
* been specified.
*/
public function documents(array $options = [])
{
$options = $this->formatReadTimeOption($options);
$maxRetries = $this->pluck('maxRetries', $options, false);
$maxRetries = $maxRetries === null
? FirestoreClient::MAX_RETRIES
: $maxRetries;
$query = $this->structuredQueryPrepare([
'query' => $this->query,
'limitToLast' => $this->limitToLast
]);
$explainMetrics = null;
$rows = (new ExponentialBackoff($maxRetries))->execute(function () use ($query, $options, &$explainMetrics) {
/**
* @var RunQueryRequest $request
* @var CallOptions $callOptions
*/
[$request, $callOptions] = $this->validateOptions(
[
'parent' => $this->parentName,
'structuredQuery' => $query
] + $options,
new RunQueryRequest(),
CallOptions::class
);
try {
$generator = $this->gapicClient->runQuery($request, $callOptions)->readAll();
} catch (ApiException $ex) {
throw $this->convertToGoogleException($ex);
}
// cache collection references
$collections = [];
$out = [];
while ($generator->valid()) {
$result = $this->serializer->encodeMessage($generator->current());
if (isset($result['document']) && $result['document']) {
$collectionName = $this->parentPath($result['document']['name']);
if (!isset($collections[$collectionName])) {
$collections[$collectionName] = new CollectionReference(
$this->gapicClient,
$this->valueMapper,
$collectionName
);
}
$ref = new DocumentReference(
$this->gapicClient,
$this->valueMapper,
$collections[$collectionName],
$result['document']['name']
);
$document = $result['document'];
$document['readTime'] = $result['readTime'] ?? null;
$out[] = $this->createSnapshotWithData($this->valueMapper, $ref, $document);
}
if (isset($result['explainMetrics'])) {
$explainMetrics = $this->parseMetrics($result['explainMetrics']);
}
$generator->next();
}
// if limitToLast is on, reverse the results, since we already
// reversed all the ordering constraints before sending the query.
return $this->limitToLast
? array_reverse($out)
: $out;
});
return new QuerySnapshot($this, $rows, $explainMetrics);
}
/**
* Add a SELECT to the Query.
*
* Creates and returns a new Query instance that applies a field mask to the
* result and returns only the specified subset of fields. You can specify a
* list of field paths to return, or use an empty list to only return the
* references of matching documents.
*
* Subsequent calls to this method will override previous values.
*
* Example:
* ```
* $query = $query->select(['firstName']);
* ```
*
* @param string[]|FieldPath[] $fieldPaths The projection to return, in the
* form of an array of field paths. To only return the name of the
* document, provide an empty array.
* @return Query A new instance of Query with the given changes applied.
*/
public function select(array $fieldPaths)
{
$fields = [];
foreach ($fieldPaths as $field) {
if (!($field instanceof FieldPath)) {
$field = FieldPath::fromString($field);
}
$fields[] = [
'fieldPath' => $field->pathString()
];
}
if (!$fields) {
$fields[] = [
'fieldPath' => self::DOCUMENT_ID
];
}
return $this->newQuery([
'select' => [
'fields' => $fields
]
], true);
}
/**
* Add a WHERE clause to the Query.
*
* For a list of all available operators, see
* {@see \Google\Cloud\Firestore\V1\StructuredQuery\FieldFilter\Operator}.
* This method also supports a number of comparison operators which you will
* be familiar with, such as `=`, `>`, `<`, `<=` and `>=`. For array fields,
* the `array-contains`, `IN` and `array-contains-any` operators are also
* available.
* This method also supports usage of Filters (see {@see \Google\Cloud\Firestore\Filter}).
* The Filter class helps to create complex queries using AND and OR operators.
*
* Example:
* ```
* $query = $query->where('firstName', '=', 'John');
* ```
*
* ```
* // Filtering against `null` and `NAN` is supported only with the equality operator.
* $query = $query->where('coolnessPercentage', '=', NAN);
* ```
*
* ```
* // Use `array-contains` to select documents where the array contains given elements.
* $query = $query->where('friends', 'array-contains', ['Steve', 'Sarah']);
* ```
*
* ```
* use Google\Cloud\Firestore\Filter;
*
* // Filtering with Filter::or
* $query = $query->where(Filter::or([
* Filter::field('firstName', '=', 'John'),
* Filter::field('firstName', '=', 'Monica')
* ]));
* ```
*
* @param string|array|FieldPath $fieldPath The field to filter by, or array of Filters.
* If filter array is provided, other params will be ignored.
* @param string|int $operator The operator to filter by.
* @param mixed $value The value to compare to.
* @return Query A new instance of Query with the given changes applied.
* @throws \InvalidArgumentException If an invalid operator or value is encountered.
*/
public function where($fieldPath, $operator = null, $value = null)
{
if (is_array($fieldPath)) {
$filters = $this->createCompositeFilter($fieldPath);
} else {
$filters = $this->createFieldFilter($fieldPath, $operator, $value);
}
$query = [
'where' => [
'compositeFilter' => [
'op' => Operator::PBAND,
'filters' => [$filters]
]
]
];
return $this->newQuery($query);
}
/**
* Add an ORDER BY clause to the Query.
*
* Example:
* ```
* $query = $query->orderBy('firstName', 'DESC');
* ```
*
* @param string|FieldPath $fieldPath The field to order by.
* @param string|int $direction The direction to order in. **Defaults to**
* `ASC`.
* @return Query A new instance of Query with the given changes applied.
* @throws \InvalidArgumentException If an invalid direction is given.
* @throws \InvalidArgumentException If orderBy is called after `startAt()`,
* `startAfter()`, `endBefore()` or `endAt`().
*/
public function orderBy($fieldPath, $direction = self::DIR_ASCENDING)
{
$direction = array_key_exists(strtoupper($direction), $this->shortDirections)
? $this->shortDirections[strtoupper($direction)]
: $direction;
if (!in_array($direction, $this->allowedDirections)) {
throw new \InvalidArgumentException(sprintf(
'Direction %s is not a valid direction',
$direction
));
}
if ($this->queryHas('startAt') || $this->queryHas('endAt')) {
throw new \InvalidArgumentException(
'Cannot specify an orderBy constraint after calling any of ' .
'`startAt()`, `startAfter()`, `endBefore()` or `endAt`().'
);
}
if (!($fieldPath instanceof FieldPath)) {
$fieldPath = FieldPath::fromString($fieldPath);
}
return $this->newQuery([
'orderBy' => [
[
'field' => [
'fieldPath' => $fieldPath->pathString()
],
'direction' => $direction
]
]
]);
}
/**
* Limits a query to return only the first matching documents.
*
* Applies after all other constraints. Must be >= 0 if specified.
*
* Example:
* ```
* $query = $query->limit(10);
* ```
*
* @param int $number The number of results to return.
* @return Query A new instance of Query with the given changes applied.
*/
public function limit($number)
{
return $this->newQuery([
'limit' => $number
], false, false); // create a new query, explicitly setting `limitToLast` to false.
}
/**
* Limits a query to return only the last matching documents.
*
* Applies after all other constraints. Must be >= 0 if specified.
*
* You must specify at least one orderBy clause for limitToLast queries,
* otherwise an exception will be thrown during execution.
*
* Example:
* ```
* $query = $query->limitToLast(10)
* ->orderBy('firstName');
* ```
*
* @param int $number The number of results to return.
* @return Query A new instance of Query with the given changes applied.
*/
public function limitToLast($number)
{
return $this->newQuery([
'limit' => $number
], false, true); // create a new query, explicitly setting `limitToLast` to true.
}
/**
* The number of results to skip.
*
* Applies before limit, but after all other constraints. Must be >= 0 if specified.
*
* Example:
* ```
* $query = $query->offset(10);
* ```
*
* @param int $number The number of results to skip.
* @return Query A new instance of Query with the given changes applied.
*/
public function offset($number)
{
return $this->newQuery([
'offset' => $number
]);
}
/**
* A starting point for the query results.
*
* Starts results at the provided set of field values relative to the order
* of the query. The order of the provided values must match the order of
* the order by clauses of the query. Values in the given cursor will be
* included in the result set, if found.
*
* Multiple invocations of this call overwrite previous calls. Calling
* `startAt()` will overwrite both previous `startAt()` and `startAfter()`
* calls.
*
* Example:
* ```
* $query = $query->orderBy('age', 'ASC')->startAt([18]);
* $users18YearsOrOlder = $query->documents();
* ```
*
* @param mixed[]|DocumentSnapshot $fieldValues A list of values, or an
* instance of {@see \Google\Cloud\Firestore\DocumentSnapshot}
* defining the query starting point.
* @return Query A new instance of Query with the given changes applied.
*/
public function startAt($fieldValues)
{
return $this->buildPosition('startAt', $fieldValues, true);
}
/**
* A starting point for the query results.
*
* Starts results after the provided set of field values relative to the order
* of the query. The order of the provided values must match the order of
* the order by clauses of the query. Values in the given cursor will not be
* included in the result set.
*
* Multiple invocations of this call overwrite previous calls. Calling
* `startAt()` will overwrite both previous `startAt()` and `startAfter()`
* calls.
*
* Example:
* ```
* $query = $query->orderBy('age', 'ASC')->startAfter([17]);
* $users18YearsOrOlder = $query->documents();
* ```
*
* @param mixed[]|DocumentSnapshot $fieldValues A list of values, or an
* instance of {@see \Google\Cloud\Firestore\DocumentSnapshot}
* defining the query starting point.
* @return Query A new instance of Query with the given changes applied.
*/
public function startAfter($fieldValues)
{
return $this->buildPosition('startAt', $fieldValues, false);
}
/**
* An end point for the query results.
*
* Ends results before the provided set of field values relative to the order
* of the query. The order of the provided values must match the order of
* the order by clauses of the query. Values in the given cursor will be
* included in the result set, if found.
*
* Multiple invocations of this call overwrite previous calls. Calling
* `endBefore()` will overwrite both previous `endBefore()` and `endAt()`
* calls.
*
* Example:
* ```
* $query = $query->orderBy('age', 'ASC')->endBefore([18]);
* $usersYoungerThan18 = $query->documents();
* ```
*
* @param mixed[]|DocumentSnapshot $fieldValues A list of values, or an
* instance of {@see \Google\Cloud\Firestore\DocumentSnapshot}
* defining the query end point.
* @return Query A new instance of Query with the given changes applied.
*/
public function endBefore($fieldValues)
{
return $this->buildPosition('endAt', $fieldValues, true);
}
/**
* An end point for the query results.
*
* Ends results at the provided set of field values relative to the order
* of the query. The order of the provided values must match the order of
* the order by clauses of the query. Values in the given cursor will not be
* included in the result set.
*
* Multiple invocations of this call overwrite previous calls. Calling
* `endBefore()` will overwrite both previous `endBefore()` and `endAt()`
* calls.
*
* Example:
* ```
* $query = $query->orderBy('age', 'ASC')->endAt([17]);
* $usersYoungerThan18 = $query->documents();
* ```
*
* @param mixed[]|DocumentSnapshot $fieldValues A list of values, or an
* instance of {@see \Google\Cloud\Firestore\DocumentSnapshot}
* defining the query end point.
* @return Query A new instance of Query with the given changes applied.
*/
public function endAt($fieldValues)
{
return $this->buildPosition('endAt', $fieldValues, false);
}
/**
* Check if a given constraint type has been specified on the query.
*
* @param string $key The constraint name.
* @return bool
* @access private
*/
public function queryHas($key)
{
return isset($this->query[$key]);
}
/**
* Get the constraint data from the current query.
*
* @param string $key The constraint name
* @return mixed
* @access private
*/
public function queryKey($key)
{
return $this->queryHas($key)
? $this->query[$key]
: null;
}
/**
* Builds a Firestore query position.
*
* @param string $key The query key.
* @param mixed[]|DocumentSnapshot $fieldValues An array of values, or an
* instance of {@see \Google\Cloud\Firestore\DocumentSnapshot}
* to use as the query boundary.
* @param bool $before Whether the query boundary lies just before or after
* the provided data.
* @return Query
*/
private function buildPosition($key, $fieldValues, $before)
{
$basePath = $this->basePath();
$orderBy = $this->queryKey('orderBy') ?: [];
if ($fieldValues instanceof DocumentSnapshot) {
list($fieldValues, $orderBy) = $this->snapshotPosition($fieldValues, $orderBy);
} else {
if (!is_array($fieldValues)) {
throw new \InvalidArgumentException(sprintf(
'Field values must be an array or an instance of `%s`.',
DocumentSnapshot::class
));
}
foreach ($fieldValues as $value) {
if ($value instanceof DocumentSnapshot) {
throw new \InvalidArgumentException(sprintf(
'Instances of `%s` are not allowed in an array of field values. ' .
'Provide it as the method argument instead.',
DocumentSnapshot::class
));
}
if ($value instanceof FieldValueInterface) {
throw new \InvalidArgumentException(sprintf(
'Value cannot be a `%s` value.',
FieldValue::class
));
}
}
}
if (count($fieldValues) > count($orderBy)) {
throw new \InvalidArgumentException(
'Too many cursor values specified. The specified values must ' .
'match the `orderBy` constraints of the query.'
);
}
foreach ($fieldValues as $i => &$value) {
if ($orderBy[$i]['field']['fieldPath'] === self::DOCUMENT_ID) {
if (is_string($value)) {
$value = $this->createDocumentReference($basePath, $value);
} else {
if ($value instanceof DocumentReference) {
$name = $value->name();
$parent = $value->parent()->name();
} else {
throw new \InvalidArgumentException(
'The corresponding value for DOCUMENT_ID must be a ' .
'string or a DocumentReference.'
);
}
if (!$this->isPrefixOf($basePath, $name)) {
throw new \InvalidArgumentException(sprintf(
'%s is not a part of the query result set and ' .
'cannot be used as a query boundary',
$name
));
}
if ($parent !== $basePath && !$this->allDescendants()) {
throw new \InvalidArgumentException(
'Only direct children may be used as query boundaries.'
);
}
}
}
}
$clause = [
'values' => $this->valueMapper->encodeValues($fieldValues)
];
if ($before) {
$clause['before'] = $before;
}
return $this->newQuery([
$key => $clause,
'orderBy' => $orderBy
], true);
}
/**
* Find fieldFilters in a composite filter.
*
* @param array $filter The composite filter.
* @return array array of field filters.
*/
private function flattenFilter($filter)
{
$ret = [];
$filters = $filter['compositeFilter']['filters'];
foreach ($filters as $fltr) {
$type = array_keys($fltr)[0];
if ($type === 'compositeFilter') {
$ret = array_merge($ret, $this->flattenFilter($fltr));
} else {
$ret[] = $fltr;
}
}
return $ret;
}
/**
* Build cursors for document snapshots.
*
* @param DocumentSnapshot $snapshot The document snapshot
* @param array $orderBy A list of orderBy clauses.
* @return array A list, where position 0 is fieldValues and position 1 is orderBy.
*/
private function snapshotPosition(DocumentSnapshot $snapshot, array $orderBy)
{
$appendName = true;
foreach ($orderBy as $order) {
if ($order['field']['fieldPath'] === self::DOCUMENT_ID) {
$appendName = false;
break;
}
}
if ($appendName) {
// If there is inequality filter (anything other than equals),
// append orderBy(the last inequality filter’s path, ascending).
if (!$orderBy && $this->queryHas('where')) {
// Flatten the filters array if compositeFilters are present
$filters = $this->flattenFilter($this->query['where']);
$inequality = array_filter($filters, function ($filter) {
$type = array_keys($filter)[0];
return !in_array($filter[$type]['op'], [
FieldFilterOperator::EQUAL,
FieldFilterOperator::ARRAY_CONTAINS
]);
});
if ($inequality) {
$filter = end($inequality);
$type = array_keys($filter)[0];
$orderBy[] = [
'field' => [
'fieldPath' => $filter[$type]['field']['fieldPath'],
],
'direction' => self::DIR_ASCENDING
];
}
}
// If the query has existing orderBy constraints
if ($orderBy) {
// Append orderBy(__name__, direction of last orderBy clause)
$lastOrderDirection = end($orderBy)['direction'];
$orderBy[] = [
'field' => [
'fieldPath' => self::DOCUMENT_ID
],
'direction' => $lastOrderDirection
];
} else {
// no existing orderBy constraints
// Otherwise append orderBy(__name__, ‘asc’)
$orderBy[] = [
'field' => [
'fieldPath' => self::DOCUMENT_ID
],
'direction' => self::DIR_ASCENDING
];
}
}
$fieldValues = $this->snapshotCursorValues($snapshot, $orderBy);
return [
$fieldValues,
$orderBy
];
}
/**
* Determine field values for Document Snapshot cursors.
*
* @param DocumentSnapshot $snapshot
* @param array $orderBy
* @return array $fieldValues
*/
private function snapshotCursorValues(DocumentSnapshot $snapshot, array $orderBy)
{
$fieldValues = [];
foreach ($orderBy as $order) {
$path = $order['field']['fieldPath'];
if ($path === self::DOCUMENT_ID) {
continue;
}
$fieldValues[] = $snapshot->get($path);
}
$fieldValues[] = $snapshot->reference();
return $fieldValues;
}
/**
* Create a new Query instance
*
* @param array $additionalConfig
* @param bool $overrideTopLevelKeys If true, top-level keys will be replaced
* rather than recursively merged.
* @param bool $limitToLast If true, the query limit will be applied from
* the end of the result set.
* @return Query A new instance of Query with the given changes applied.
*/
private function newQuery(array $additionalConfig, $overrideTopLevelKeys = false, $limitToLast = false)
{
$query = $this->query;
if ($overrideTopLevelKeys) {
$keys = array_keys($additionalConfig);
foreach ($keys as $key) {
unset($query[$key]);
}
}
$query = $this->arrayMergeRecursive($query, $additionalConfig);
return new self(
$this->gapicClient,
$this->valueMapper,