1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Mgid\Component\Pagination\Adapter\Doctrine\ODM; |
4
|
|
|
|
5
|
|
|
use Doctrine\ODM\MongoDB\Aggregation\Builder; |
6
|
|
|
use Mgid\Component\Pagination\Contract\SortableInterface; |
7
|
|
|
use Mgid\Component\Pagination\Contract\PaginationInterface; |
8
|
|
|
use Mgid\Component\Pagination\Contract\FilterableInterface; |
9
|
|
|
|
10
|
|
|
final class AggregationBuilderAdapter extends AbstractQueryBuilderAdapter |
11
|
|
|
{ |
12
|
|
|
private const OPTIONS = [ |
13
|
|
|
'allowDiskUse' => true, |
14
|
|
|
]; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var Builder |
18
|
|
|
*/ |
19
|
|
|
private Builder $builder; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param Builder $builder |
23
|
|
|
*/ |
24
|
|
|
public function __construct(Builder $builder) |
25
|
|
|
{ |
26
|
|
|
$this->builder = $builder; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* {@inheritdoc} |
31
|
|
|
*/ |
32
|
|
|
public function getRootAlias(): ?string |
33
|
|
|
{ |
34
|
|
|
return null; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
*/ |
40
|
|
|
public function addOrders(SortableInterface $sortable): void |
41
|
|
|
{ |
42
|
|
|
foreach ($sortable->getOrders() as $fieldName => $order) { |
43
|
|
|
$this->builder->sort($fieldName, $order); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* {@inheritdoc} |
49
|
|
|
*/ |
50
|
|
|
public function addFilters(FilterableInterface $filterable): void |
51
|
|
|
{ |
52
|
|
|
$match = $this->builder->match(); |
53
|
|
|
|
54
|
|
|
foreach ($filterable->getFilters() as $fieldName => $operators) { |
55
|
|
|
foreach ($operators as $operator => $value) { |
56
|
|
|
$match->addAnd( |
57
|
|
|
$match->expr()->field($fieldName)->operator($this->getOperator($operator), $value) |
58
|
|
|
); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* {@inheritdoc} |
65
|
|
|
*/ |
66
|
|
|
public function addPagination(PaginationInterface $pagination): void |
67
|
|
|
{ |
68
|
|
|
if ($pagination->getOffset() > 0) { |
69
|
|
|
$this->builder->skip($pagination->getOffset()); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if ($pagination->getLimit() > 0) { |
73
|
|
|
$this->builder->limit($pagination->getLimit()); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* {@inheritdoc} |
79
|
|
|
*/ |
80
|
|
|
public function getCount(): int |
81
|
|
|
{ |
82
|
|
|
return (int) ((clone $this->builder)->count('count')->execute(self::OPTIONS)->current()['count'] ?? 0); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* {@inheritdoc} |
87
|
|
|
*/ |
88
|
|
|
public function getItems(): iterable |
89
|
|
|
{ |
90
|
|
|
return $this->builder->execute(self::OPTIONS); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|