-
-
Notifications
You must be signed in to change notification settings - Fork 505
/
Copy pathBuilder.php
700 lines (600 loc) · 22 KB
/
Builder.php
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
<?php
declare(strict_types=1);
namespace Doctrine\ODM\MongoDB\Aggregation;
use Doctrine\ODM\MongoDB\Aggregation\Stage\Sort;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Iterator\Iterator;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\Persisters\DocumentPersister;
use Doctrine\ODM\MongoDB\Query\Expr as QueryExpr;
use GeoJson\Geometry\Point;
use MongoDB\Collection;
use OutOfRangeException;
use TypeError;
use function array_map;
use function array_unshift;
use function func_get_arg;
use function func_num_args;
use function gettype;
use function is_array;
use function is_bool;
use function sprintf;
use function trigger_deprecation;
/**
* Fluent interface for building aggregation pipelines.
*
* @psalm-import-type SortShape from Sort
* @psalm-import-type StageExpression from Stage
* @psalm-type PipelineExpression = list<StageExpression>
*/
class Builder
{
/**
* The DocumentManager instance for this query
*/
private DocumentManager $dm;
/**
* The ClassMetadata instance.
*/
private ClassMetadata $class;
/** @psalm-var class-string */
private ?string $hydrationClass = null;
/**
* The Collection instance.
*/
private Collection $collection;
/** @var Stage[] */
private array $stages = [];
private bool $rewindable = true;
/**
* Create a new aggregation builder.
*
* @psalm-param class-string $documentName
*/
public function __construct(DocumentManager $dm, string $documentName)
{
$this->dm = $dm;
$this->class = $this->dm->getClassMetadata($documentName);
$this->collection = $this->dm->getDocumentCollection($documentName);
}
/**
* Adds new fields to documents. $addFields outputs documents that contain all
* existing fields from the input documents and newly added fields.
*
* The $addFields stage is equivalent to a $project stage that explicitly specifies
* all existing fields in the input documents and adds the new fields.
*
* If the name of the new field is the same as an existing field name (including _id),
* $addFields overwrites the existing value of that field with the value of the
* specified expression.
*
* @see http://docs.mongodb.com/manual/reference/operator/aggregation/addFields/
*/
public function addFields(): Stage\AddFields
{
$stage = new Stage\AddFields($this);
return $this->addStage($stage);
}
/**
* Categorizes incoming documents into groups, called buckets, based on a
* specified expression and bucket boundaries.
*
* Each bucket is represented as a document in the output. The document for
* each bucket contains an _id field, whose value specifies the inclusive
* lower bound of the bucket and a count field that contains the number of
* documents in the bucket. The count field is included by default when the
* output is not specified.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/bucket/
*/
public function bucket(): Stage\Bucket
{
$stage = new Stage\Bucket($this, $this->dm, $this->class);
return $this->addStage($stage);
}
/**
* Categorizes incoming documents into a specific number of groups, called
* buckets, based on a specified expression.
*
* Bucket boundaries are automatically determined in an attempt to evenly
* distribute the documents into the specified number of buckets. Each
* bucket is represented as a document in the output. The document for each
* bucket contains an _id field, whose value specifies the inclusive lower
* bound and the exclusive upper bound for the bucket, and a count field
* that contains the number of documents in the bucket. The count field is
* included by default when the output is not specified.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/bucketAuto/
*/
public function bucketAuto(): Stage\BucketAuto
{
$stage = new Stage\BucketAuto($this, $this->dm, $this->class);
return $this->addStage($stage);
}
/**
* Returns statistics regarding a collection or view.
*
* $collStats must be the first stage in an aggregation pipeline, or else
* the pipeline returns an error.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/collStats/
*/
public function collStats(): Stage\CollStats
{
$stage = new Stage\CollStats($this);
return $this->addStage($stage);
}
/**
* Returns a document that contains a count of the number of documents input
* to the stage.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/count/
*/
public function count(string $fieldName): Stage\Count
{
$stage = new Stage\Count($this, $fieldName);
return $this->addStage($stage);
}
/**
* Creates new documents in a sequence of documents where certain values in a field are missing.
*
* @see https://www.mongodb.com/docs/rapid/reference/operator/aggregation/densify/
*/
public function densify(string $fieldName): Stage\Densify
{
$stage = new Stage\Densify($this, $fieldName);
return $this->addStage($stage);
}
/**
* Executes the aggregation pipeline
*
* @deprecated This method was deprecated in doctrine/mongodb-odm 2.2. Please use getAggregation() instead.
*
* @param array<string, mixed> $options
*/
public function execute(array $options = []): Iterator
{
trigger_deprecation(
'doctrine/mongodb-odm',
'2.2',
'Using "%s" is deprecated. Please use "%s::getAggregation()" instead.',
__METHOD__,
self::class,
);
return $this->getAggregation($options)->getIterator();
}
public function expr(): Expr
{
return new Expr($this->dm, $this->class);
}
/**
* Processes multiple aggregation pipelines within a single stage on the
* same set of input documents.
*
* Each sub-pipeline has its own field in the output document where its
* results are stored as an array of documents.
*/
public function facet(): Stage\Facet
{
$stage = new Stage\Facet($this);
return $this->addStage($stage);
}
/**
* Populates null and missing field values within documents.
*
* @see https://www.mongodb.com/docs/rapid/reference/operator/aggregation/fill/
*/
public function fill(): Stage\Fill
{
$stage = new Stage\Fill($this);
return $this->addStage($stage);
}
/**
* Outputs documents in order of nearest to farthest from a specified point.
*
* A GeoJSON point may be provided as the first and only argument for
* 2dsphere queries. This single parameter may be a GeoJSON point object or
* an array corresponding to the point's JSON representation. If GeoJSON is
* used, the "spherical" option will default to true.
*
* You can only use this as the first stage of a pipeline.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/
*
* @param float|array<string, mixed>|Point $x
* @param float $y
*/
public function geoNear($x, $y = null): Stage\GeoNear
{
$stage = new Stage\GeoNear($this, $x, $y);
return $this->addStage($stage);
}
/**
* Returns an aggregation object for the current pipeline
*
* @param array<string, mixed> $options
*/
public function getAggregation(array $options = []): Aggregation
{
$class = $this->hydrationClass ? $this->dm->getClassMetadata($this->hydrationClass) : null;
return new Aggregation($this->dm, $class, $this->collection, $this->getPipeline(), $options, $this->rewindable);
}
// phpcs:disable Squiz.Commenting.FunctionComment.ExtraParamComment
/**
* Returns the assembled aggregation pipeline
*
* @param bool $applyFilters Whether to apply filters on the aggregation
* pipeline stage
*
* For pipelines where the first stage is a $geoNear stage, it will apply
* the document filters and discriminator queries to the query portion of
* the geoNear operation. For all other pipelines, it prepends a $match stage
* containing the required query.
*
* For aggregation pipelines that will be nested (e.g. in a facet stage),
* you should not apply filters as this may cause wrong results to be
* given.
*
* @return array<array<string, mixed>>
* @psalm-return PipelineExpression
*/
// phpcs:enable Squiz.Commenting.FunctionComment.ExtraParamComment
public function getPipeline(/* bool $applyFilters = true */): array
{
$applyFilters = func_num_args() > 0 ? func_get_arg(0) : true;
if (! is_bool($applyFilters)) {
throw new TypeError(sprintf(
'Argument 1 passed to %s must be of the type bool, %s given',
__METHOD__,
gettype($applyFilters),
));
}
$pipeline = array_map(
static fn (Stage $stage) => $stage->getExpression(),
$this->stages,
);
if ($this->getStage(0) instanceof Stage\IndexStats) {
// Don't apply any filters when using an IndexStats stage: since it
// needs to be the first pipeline stage, prepending a match stage
// with discriminator information will not work
$applyFilters = false;
}
if (! $applyFilters) {
return $pipeline;
}
if ($this->getStage(0) instanceof Stage\GeoNear) {
$pipeline[0]['$geoNear']['query'] = $this->applyFilters($pipeline[0]['$geoNear']['query']);
return $pipeline;
}
$matchExpression = $this->applyFilters([]);
if ($matchExpression !== []) {
array_unshift($pipeline, ['$match' => $matchExpression]);
}
return $pipeline;
}
/**
* Returns a certain stage from the pipeline
*/
public function getStage(int $index): Stage
{
if (! isset($this->stages[$index])) {
throw new OutOfRangeException(sprintf('Could not find stage with index %d.', $index));
}
return $this->stages[$index];
}
/**
* Performs a recursive search on a collection, with options for restricting
* the search by recursion depth and query filter.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/
*
* @param string $from Target collection for the $graphLookup operation to
* search, recursively matching the connectFromField to the connectToField.
*/
public function graphLookup(string $from): Stage\GraphLookup
{
$stage = new Stage\GraphLookup($this, $from, $this->dm, $this->class);
return $this->addStage($stage);
}
/**
* Groups documents by some specified expression and outputs to the next
* stage a document for each distinct grouping.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/group/
*/
public function group(): Stage\Group
{
$stage = new Stage\Group($this);
return $this->addStage($stage);
}
/**
* Set which class to use when hydrating results as document class instances.
*/
public function hydrate(?string $className): static
{
$this->hydrationClass = $className;
return $this;
}
/**
* Returns statistics regarding the use of each index for the collection.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/indexStats/
*/
public function indexStats(): Stage\IndexStats
{
$stage = new Stage\IndexStats($this);
return $this->addStage($stage);
}
/**
* Limits the number of documents passed to the next stage in the pipeline.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/limit/
*/
public function limit(int $limit): Stage\Limit
{
$stage = new Stage\Limit($this, $limit);
return $this->addStage($stage);
}
/**
* Performs a left outer join to an unsharded collection in the same
* database to filter in documents from the “joined” collection for
* processing.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
*/
public function lookup(string $from): Stage\Lookup
{
$stage = new Stage\Lookup($this, $from, $this->dm, $this->class);
return $this->addStage($stage);
}
/**
* Filters the documents to pass only the documents that match the specified
* condition(s) to the next pipeline stage.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/match/
*/
public function match(): Stage\MatchStage
{
$stage = new Stage\MatchStage($this);
return $this->addStage($stage);
}
/**
* Returns a query expression to be used in match stages
*/
public function matchExpr(): QueryExpr
{
$expr = new QueryExpr($this->dm);
$expr->setClassMetadata($this->class);
return $expr;
}
/**
* Writes the results of the aggregation pipeline to a specified collection.
* The $merge operator must be the last stage in the pipeline.
*
* @see https://www.mongodb.com/docs/rapid/reference/operator/aggregation/merge/
*/
public function merge(): Stage\Merge
{
$stage = new Stage\Merge($this, $this->dm);
return $this->addStage($stage);
}
/**
* Takes the documents returned by the aggregation pipeline and writes them
* to a specified collection. This must be the last stage in the pipeline.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/out/
*/
public function out(string $from): Stage\Out
{
$stage = new Stage\Out($this, $from, $this->dm);
return $this->addStage($stage);
}
/**
* Passes along the documents with only the specified fields to the next
* stage in the pipeline. The specified fields can be existing fields from
* the input documents or newly computed fields.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/project/
*/
public function project(): Stage\Project
{
$stage = new Stage\Project($this);
return $this->addStage($stage);
}
/**
* Restricts the contents of the documents based on information stored in
* the documents themselves.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/redact/
*/
public function redact(): Stage\Redact
{
$stage = new Stage\Redact($this);
return $this->addStage($stage);
}
/**
* Promotes a specified document to the top level and replaces all other
* fields.
*
* The operation replaces all existing fields in the input document,
* including the _id field. You can promote an existing embedded document to
* the top level, or create a new document for promotion.
*
* @param string|mixed[]|Expr|null $expression Optional. A replacement expression that
* resolves to a document.
*/
public function replaceRoot($expression = null): Stage\ReplaceRoot
{
$stage = new Stage\ReplaceRoot($this, $this->dm, $this->class, $expression);
return $this->addStage($stage);
}
/**
* Replaces the input document with the specified document. The operation
* replaces all existing fields in the input document, including the _id
* field. With $replaceWith, you can promote an embedded document to the
* top-level. You can also specify a new document as the replacement.
*
* The $replaceWith stage is an alias for $replaceRoot.
*
* @see https://www.mongodb.com/docs/rapid/reference/operator/aggregation/replaceWith/
*
* @param string|mixed[]|Expr|null $expression Optional. A replacement expression that
* resolves to a document.
*/
public function replaceWith($expression = null): Stage\ReplaceWith
{
$stage = new Stage\ReplaceWith($this, $this->dm, $this->class, $expression);
return $this->addStage($stage);
}
/**
* Controls if resulting iterator should be wrapped with CachingIterator.
*/
public function rewindable(bool $rewindable = true): static
{
$this->rewindable = $rewindable;
return $this;
}
/**
* Randomly selects the specified number of documents from its input.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/sample/
*/
public function sample(int $size): Stage\Sample
{
$stage = new Stage\Sample($this, $size);
return $this->addStage($stage);
}
/**
* The $search stage performs a full-text search on the specified field or
* fields which must be covered by an Atlas Search index.
*
* @see https://www.mongodb.com/docs/atlas/atlas-search/query-syntax/#mongodb-pipeline-pipe.-search
*/
public function search(): Stage\Search
{
$stage = new Stage\Search($this);
return $this->addStage($stage);
}
/**
* Adds new fields to documents. $set outputs documents that contain all
* existing fields from the input documents and newly added fields.
*
* The $set stage is an alias for $addFields.
*
* @see https://www.mongodb.com/docs/rapid/reference/operator/aggregation/set/
*/
public function set(): Stage\Set
{
$stage = new Stage\Set($this);
return $this->addStage($stage);
}
/**
* Skips over the specified number of documents that pass into the stage and
* passes the remaining documents to the next stage in the pipeline.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/skip/
*/
public function skip(int $skip): Stage\Skip
{
$stage = new Stage\Skip($this, $skip);
return $this->addStage($stage);
}
/**
* Sorts all input documents and returns them to the pipeline in sorted
* order.
*
* If sorting by multiple fields, the first argument should be an array of
* field name (key) and order (value) pairs.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/sort/
*
* @param array<string, int|string|array<string, string>>|string $fieldName Field name or array of field/order pairs
* @param int|string|null $order Field order (if one field is specified)
* @psalm-param SortShape|string $fieldName Field name or array of field/order pairs
*/
public function sort($fieldName, $order = null): Stage\Sort
{
$fields = is_array($fieldName) ? $fieldName : [$fieldName => $order];
// fixme: move to sort stage
$stage = new Stage\Sort($this, $this->getDocumentPersister()->prepareSort($fields));
return $this->addStage($stage);
}
/**
* Groups incoming documents based on the value of a specified expression,
* then computes the count of documents in each distinct group.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/
*/
public function sortByCount(string $expression): Stage\SortByCount
{
$stage = new Stage\SortByCount($this, $expression, $this->dm, $this->class);
return $this->addStage($stage);
}
/**
* Performs a union of two collections. $unionWith combines pipeline results
* from two collections into a single result set. The stage outputs the
* combined result set (including duplicates) to the next stage.
*
* @see https://www.mongodb.com/docs/rapid/reference/operator/aggregation/unionWith/
*/
public function unionWith(string $collection): Stage\UnionWith
{
$stage = new Stage\UnionWith($this, $this->dm, $collection);
return $this->addStage($stage);
}
/**
* Removes/excludes fields from documents.
*
* @see https://www.mongodb.com/docs/rapid/reference/operator/aggregation/unset/
*/
public function unset(string ...$fields): Stage\UnsetStage
{
$stage = new Stage\UnsetStage($this, $this->getDocumentPersister(), ...$fields);
return $this->addStage($stage);
}
/**
* Deconstructs an array field from the input documents to output a document
* for each element. Each output document is the input document with the
* value of the array field replaced by the element.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/
*/
public function unwind(string $fieldName): Stage\Unwind
{
// Fixme: move field name translation to stage
$stage = new Stage\Unwind($this, $this->getDocumentPersister()->prepareFieldName($fieldName));
return $this->addStage($stage);
}
/**
* Allows adding an arbitrary stage to the pipeline
*
* @param T $stage
*
* @return T The method returns the stage given as an argument
*
* @template T of Stage
*/
public function addStage(Stage $stage): Stage
{
$this->stages[] = $stage;
return $stage;
}
/**
* Applies filters and discriminator queries to the pipeline
*
* @param array<string, mixed> $query
*
* @return array<string, mixed>
*/
private function applyFilters(array $query): array
{
$documentPersister = $this->dm->getUnitOfWork()->getDocumentPersister($this->class->name);
$query = $documentPersister->addDiscriminatorToPreparedQuery($query);
$query = $documentPersister->addFilterToPreparedQuery($query);
return $query;
}
private function getDocumentPersister(): DocumentPersister
{
return $this->dm->getUnitOfWork()->getDocumentPersister($this->class->name);
}
}