-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueryBuilderDecorator.php
More file actions
342 lines (298 loc) · 9.42 KB
/
QueryBuilderDecorator.php
File metadata and controls
342 lines (298 loc) · 9.42 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
<?php
namespace Digbang\Utils\Doctrine;
use Digbang\Utils\Sorting;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\Query\Expr\From;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\Query\Expr\Select;
use Doctrine\ORM\QueryBuilder;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
class QueryBuilderDecorator extends QueryBuilder
{
public function __construct(QueryBuilder $queryBuilder)
{
parent::__construct($queryBuilder->getEntityManager());
$this->decorateDQLParts($queryBuilder->getDQLParts());
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
public function from($from, $alias, $indexBy = null)
{
$singleAlias = $this->getSingleAlias($alias);
/** @var From $part */
foreach ($this->getDQLPart('from') as $part) {
if ($part->getAlias() === $singleAlias && $part->getFrom() !== $from) {
throw new \InvalidArgumentException("Duplicated FROM alias: $singleAlias.");
}
}
return parent::from($from, $singleAlias, $indexBy);
}
/**
* {@inheritDoc}
*/
public function select($select = null)
{
$selects = is_array($select) ? $select : func_get_args();
return parent::select(collect($selects)
->unique()
->toArray()
);
}
/**
* {@inheritDoc}
*/
public function addSelect($select = null)
{
$selects = is_array($select) ? $select : func_get_args();
$dqlSelectParts = collect();
/** @var Select $part */
foreach ($this->getDQLPart('select') as $part) {
foreach ($part->getParts() as $element) {
$dqlSelectParts->add($element);
}
}
return parent::addSelect(collect($selects)
->unique()
->diff($dqlSelectParts)
->toArray()
);
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
public function innerJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
{
$singleAlias = $this->getSingleAlias($alias);
if ($this->isJoined($singleAlias, Join::INNER_JOIN)) {
return $this->mergeJoinConditions($singleAlias, $conditionType, $condition);
}
return parent::innerJoin($join, $singleAlias, $conditionType, $condition, $indexBy);
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
public function leftJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
{
$singleAlias = $this->getSingleAlias($alias);
if ($this->isJoined($singleAlias, Join::LEFT_JOIN)) {
return $this->mergeJoinConditions($singleAlias, $conditionType, $condition);
}
return parent::leftJoin($join, $singleAlias, $conditionType, $condition, $indexBy);
}
/**
* Adds "order by" statement if sort is found in sortOptions.
* Returns true if order by was added.
* sortOptions example:
* [
* 'sortKeySentInPaginationData' => 'actualFieldDefinitionForThatKey',
* 'aliasJoin' => 'actualFieldDefinitionForThatKey',
* 'nameFieldValueObject' => [
* 'actualFieldDefinitionForThatKey',
* 'actualFieldDefinitionForThatKey'
* ]
* ].
*
* @param Sorting $sorting
* @param array $sortOptions
*
* @return QueryBuilderDecorator
*/
public function addSorting(Sorting $sorting, array $sortOptions): QueryBuilderDecorator
{
foreach ($sorting->get($sortOptions) as $sortBy => $sortSense) {
$this->addOrderBy($sortBy, $sortSense);
}
return $this;
}
/**
* Adds "order by" statement with raw PaginationData sorting values
* Returns true if order by was added.
*
* @param Sorting $sorting
*
* @return QueryBuilderDecorator
*/
public function addRawSorting(Sorting $sorting): QueryBuilderDecorator
{
foreach ($sorting->getRaw() as $sortBy => $sortSense) {
$this->addOrderBy($sortBy, $sortSense);
}
return $this;
}
/**
* Adds "join" and "leftJoin" statements.
* join/leftJoin example:
* [
* 'aliasJoinA' => 'alias.fieldA',
* 'aliasJoinB' => 'alias.fieldB',
* 'aliasJoinC' => 'aliasJoinA.fieldA',
* ].
*
* @deprecated
*
* @param array $joins
* @param array|null $leftJoins
*
* @return QueryBuilderDecorator
*/
public function applyJoins(array $joins, array $leftJoins = null): QueryBuilderDecorator
{
foreach ($joins as $alias => $field) {
$this->join($field, $alias);
}
if ($leftJoins) {
foreach ($leftJoins as $alias => $field) {
$this->leftJoin($field, $alias);
}
}
return $this;
}
/**
* Adds "andWhere's" statements for each filter.
*
* @param array $filters
*
* @return QueryBuilderDecorator
*/
public function applyFilters(array $filters): QueryBuilderDecorator
{
$expr = $this->expr();
if (! empty($filters)) {
$this->where($expr->andX(...$filters));
}
return $this;
}
/**
* Pre: Receive a DQLParts array.
*
* Post: Fill the current instance DQLParts with the given ones.
*
* @param array $dqlParts
*
* @return void
*/
private function decorateDQLParts(array $dqlParts): void
{
$filledDQLParts = array_filter($dqlParts);
foreach ($filledDQLParts as $key => $value) {
$this->add($key, $value, false);
}
}
/**
* Pre: Receive an array or string like one of the following (with all it's variants):
* a) 'a, b, c'
* b) ['a as foo, b, c']
* c) ['a as foo', 'b', 'c']
*
* Post: Return a normalized array like the following: ['a', 'b', 'c']
*
* Normalized array means no NULL, empty strings, duplicates or ' ' like should be inside of it.
*
* @param string|array $alias
*
* @return Collection
*/
private function normalizeAlias($alias): Collection
{
return Str::of(collect($alias)->join(','))
->explode(',')
->map(function (string $value) {
return trim($value);
})
->filter()
->unique()
->values();
}
/**
* Pre: Receive an alias
*
* Post: Return the first normalized alias if it has only one, otherwise thrown an \InvalidArgumentException if the alias is empty or has more than one alias
*
* @param null|string|array $alias
*
* @throws \InvalidArgumentException
*
* @return string
*/
private function getSingleAlias($alias): string
{
$normalizedAlias = $this->normalizeAlias($alias);
if ($normalizedAlias->count() !== 1) {
throw new \InvalidArgumentException('There should be one alias on the current context.');
}
return $normalizedAlias->first();
}
/**
* Pre: Receive two strings: join alias and type.
*
* Post: Return a true if the join was defined before, otherwhise return false. \InvalidArgumentException may be
* thrown if the alias was defined for a different join type.
*
* @param string $alias
* @param string $joinType
*
* @throws \InvalidArgumentException
*
* @return bool
*/
private function isJoined(string $alias, string $joinType): bool
{
/** @var Join[] $joins */
$joins = collect($this->getDQLPart('join'))->flatten();
foreach ($joins as $join) {
if ($join->getAlias() !== $alias) {
continue;
}
if ($join->getJoinType() === $joinType) {
return true;
}
throw new \InvalidArgumentException("Alias '$alias' is defined for a different join type: {$join->getJoinType()}.");
}
return false;
}
/**
* Pre: Receive the alias, condition type and the join condition as strings.
*
* Post: Merge the given condition with the desired join.
*
* @param string $alias
* @param null|string $conditionType
* @param null|string|Expr\Comparison|Expr\Func|Expr\Orx $condition
*
* @return QueryBuilderDecorator
*/
private function mergeJoinConditions(string $alias, ?string $conditionType = Join::WITH, $condition = null): self
{
if (is_null($condition)) {
return $this;
}
/** @var Join[] $joins */
foreach ($this->getDQLPart('join') as $key => $joins) {
foreach ($joins as $index => $join) {
if ($join->getAlias() !== $alias) {
continue;
}
$newConditionType = in_array(Join::ON, [$join->getConditionType(), $conditionType]) ? Join::ON : Join::WITH;
$newCondition = $this->expr()->andX($join->getCondition(), $condition);
$joins[$index] = new Join(
$join->getJoinType(),
$join->getJoin(),
$join->getAlias(),
$newConditionType,
$newCondition,
$join->getIndexBy()
);
return $this->add('join', [$key => $joins], false);
}
}
return $this;
}
}