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