Total Complexity | 102 |
Total Lines | 565 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 1 | Features | 0 |
Complex classes like AbstractDQLQueryBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use AbstractDQLQueryBuilder, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
41 | abstract class AbstractDQLQueryBuilder implements DQLQueryBuilderInterface |
||
42 | { |
||
43 | protected string $separator = ' '; |
||
44 | |||
45 | /** |
||
46 | * @var array map of condition aliases to condition classes. For example: |
||
47 | * |
||
48 | * ```php |
||
49 | * return [ |
||
50 | * 'LIKE' => \Yiisoft\Db\Condition\LikeCondition::class, |
||
51 | * ]; |
||
52 | * ``` |
||
53 | * |
||
54 | * This property is used by {@see createConditionFromArray} method. |
||
55 | * See default condition classes list in {@see defaultConditionClasses()} method. |
||
56 | * |
||
57 | * In case you want to add custom conditions support, use the {@see setConditionClasses()} method. |
||
58 | * |
||
59 | * @see setConditonClasses() |
||
60 | * @see defaultConditionClasses() |
||
61 | */ |
||
62 | protected array $conditionClasses = []; |
||
63 | |||
64 | /** |
||
65 | * @psalm-var array<string, class-string<ExpressionBuilderInterface>> maps expression class to expression builder |
||
66 | * class. |
||
67 | * |
||
68 | * For example: |
||
69 | * |
||
70 | * ```php |
||
71 | * [ |
||
72 | * Expression::class => ExpressionBuilder::class |
||
73 | * ] |
||
74 | * ``` |
||
75 | * This property is mainly used by {@see buildExpression()} to build SQL expressions form expression objects. |
||
76 | * See default values in {@see defaultExpressionBuilders()} method. |
||
77 | * |
||
78 | * {@see setExpressionBuilders()} |
||
79 | * {@see defaultExpressionBuilders()} |
||
80 | */ |
||
81 | protected array $expressionBuilders = []; |
||
82 | |||
83 | public function __construct( |
||
84 | private QueryBuilderInterface $queryBuilder, |
||
85 | private QuoterInterface $quoter, |
||
86 | private SchemaInterface $schema |
||
87 | ) { |
||
88 | $this->expressionBuilders = $this->defaultExpressionBuilders(); |
||
89 | $this->conditionClasses = $this->defaultConditionClasses(); |
||
90 | } |
||
91 | |||
92 | public function build(QueryInterface $query, array $params = []): array |
||
138 | } |
||
139 | |||
140 | public function buildColumns(array|string $columns): string |
||
141 | { |
||
142 | if (!is_array($columns)) { |
||
|
|||
143 | if (str_contains($columns, '(')) { |
||
144 | return $columns; |
||
145 | } |
||
146 | |||
147 | $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY); |
||
148 | } |
||
149 | |||
150 | /** @psalm-var array<array-key, ExpressionInterface|string> $columns */ |
||
151 | foreach ($columns as $i => $column) { |
||
152 | if ($column instanceof ExpressionInterface) { |
||
153 | $columns[$i] = $this->buildExpression($column); |
||
154 | } elseif (!str_contains($column, '(')) { |
||
155 | $columns[$i] = $this->quoter->quoteColumnName($column); |
||
156 | } |
||
157 | } |
||
158 | |||
159 | /** @psalm-var string[] $columns */ |
||
160 | return implode(', ', $columns); |
||
161 | } |
||
162 | |||
163 | public function buildCondition(array|string|ExpressionInterface|null $condition, array &$params = []): string |
||
164 | { |
||
165 | if (is_array($condition)) { |
||
166 | if (empty($condition)) { |
||
167 | return ''; |
||
168 | } |
||
169 | |||
170 | $condition = $this->createConditionFromArray($condition); |
||
171 | } |
||
172 | |||
173 | if ($condition instanceof ExpressionInterface) { |
||
174 | return $this->buildExpression($condition, $params); |
||
175 | } |
||
176 | |||
177 | return $condition ?? ''; |
||
178 | } |
||
179 | |||
180 | /** |
||
181 | * @throws InvalidArgumentException |
||
182 | * |
||
183 | * @psalm-suppress UndefinedInterfaceMethod |
||
184 | * @psalm-suppress MixedMethodCall |
||
185 | */ |
||
186 | public function buildExpression(ExpressionInterface $expression, array &$params = []): string |
||
187 | { |
||
188 | $builder = $this->queryBuilder->getExpressionBuilder($expression); |
||
189 | return (string) $builder->build($expression, $params); |
||
190 | } |
||
191 | |||
192 | public function buildFrom(array|null $tables, array &$params): string |
||
202 | } |
||
203 | |||
204 | public function buildGroupBy(array $columns, array &$params = []): string |
||
205 | { |
||
206 | if (empty($columns)) { |
||
207 | return ''; |
||
208 | } |
||
209 | |||
210 | /** @psalm-var array<string, Expression|string> $columns */ |
||
211 | foreach ($columns as $i => $column) { |
||
212 | if ($column instanceof Expression) { |
||
213 | $columns[$i] = $this->buildExpression($column); |
||
214 | $params = array_merge($params, $column->getParams()); |
||
215 | } elseif (!str_contains($column, '(')) { |
||
216 | $columns[$i] = $this->quoter->quoteColumnName($column); |
||
217 | } |
||
218 | } |
||
219 | |||
220 | return 'GROUP BY ' . implode(', ', $columns); |
||
221 | } |
||
222 | |||
223 | public function buildHaving(array|ExpressionInterface|string|null $condition, array &$params = []): string |
||
224 | { |
||
225 | $having = $this->buildCondition($condition, $params); |
||
226 | |||
227 | return ($having === '') ? '' : ('HAVING ' . $having); |
||
228 | } |
||
229 | |||
230 | public function buildJoin(array $joins, array &$params): string |
||
231 | { |
||
232 | if (empty($joins)) { |
||
233 | return ''; |
||
234 | } |
||
235 | |||
236 | /** |
||
237 | * @psalm-var array< |
||
238 | * array-key, |
||
239 | * array{ |
||
240 | * 0?:string, |
||
241 | * 1?:array<array-key, Query|string>|string, |
||
242 | * 2?:array|ExpressionInterface|string|null |
||
243 | * }|null |
||
244 | * > $joins |
||
245 | */ |
||
246 | foreach ($joins as $i => $join) { |
||
247 | if (!is_array($join) || !isset($join[0], $join[1])) { |
||
248 | throw new Exception( |
||
249 | 'A join clause must be specified as an array of join type, join table, and optionally join ' |
||
250 | . 'condition.' |
||
251 | ); |
||
252 | } |
||
253 | |||
254 | /* 0:join type, 1:join table, 2:on-condition (optional) */ |
||
255 | [$joinType, $table] = $join; |
||
256 | |||
257 | $tables = $this->quoteTableNames((array) $table, $params); |
||
258 | |||
259 | /** @var string $table */ |
||
260 | $table = reset($tables); |
||
261 | $joins[$i] = "$joinType $table"; |
||
262 | |||
263 | if (isset($join[2])) { |
||
264 | $condition = $this->buildCondition($join[2], $params); |
||
265 | if ($condition !== '') { |
||
266 | $joins[$i] .= ' ON ' . $condition; |
||
267 | } |
||
268 | } |
||
269 | } |
||
270 | |||
271 | /** @psalm-var array<string> $joins */ |
||
272 | return implode($this->separator, $joins); |
||
273 | } |
||
274 | |||
275 | public function buildLimit(Expression|int|null $limit, Expression|int|null $offset): string |
||
276 | { |
||
277 | $sql = ''; |
||
278 | |||
279 | if ($this->hasLimit($limit)) { |
||
280 | $sql = 'LIMIT ' . (string) $limit; |
||
281 | } |
||
282 | |||
283 | if ($this->hasOffset($offset)) { |
||
284 | $sql .= ' OFFSET ' . (string) $offset; |
||
285 | } |
||
286 | |||
287 | return ltrim($sql); |
||
288 | } |
||
289 | |||
290 | public function buildOrderBy(array $columns, array &$params = []): string |
||
291 | { |
||
292 | if (empty($columns)) { |
||
293 | return ''; |
||
294 | } |
||
295 | |||
296 | $orders = []; |
||
297 | |||
298 | /** @psalm-var array<string, Expression|int|string> $columns */ |
||
299 | foreach ($columns as $name => $direction) { |
||
300 | if ($direction instanceof Expression) { |
||
301 | $orders[] = $this->buildExpression($direction); |
||
302 | $params = array_merge($params, $direction->getParams()); |
||
303 | } else { |
||
304 | $orders[] = $this->quoter->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : ''); |
||
305 | } |
||
306 | } |
||
307 | |||
308 | return 'ORDER BY ' . implode(', ', $orders); |
||
309 | } |
||
310 | |||
311 | public function buildOrderByAndLimit( |
||
312 | string $sql, |
||
313 | array $orderBy, |
||
314 | Expression|int|null $limit, |
||
315 | Expression|int|null $offset, |
||
316 | array &$params = [] |
||
317 | ): string { |
||
318 | $orderBy = $this->buildOrderBy($orderBy, $params); |
||
319 | if ($orderBy !== '') { |
||
320 | $sql .= $this->separator . $orderBy; |
||
321 | } |
||
322 | $limit = $this->buildLimit($limit, $offset); |
||
323 | if ($limit !== '') { |
||
324 | $sql .= $this->separator . $limit; |
||
325 | } |
||
326 | |||
327 | return $sql; |
||
328 | } |
||
329 | |||
330 | public function buildSelect( |
||
331 | array $columns, |
||
332 | array &$params, |
||
333 | bool|null $distinct = false, |
||
334 | string $selectOption = null |
||
335 | ): string { |
||
336 | $select = $distinct ? 'SELECT DISTINCT' : 'SELECT'; |
||
337 | |||
338 | if ($selectOption !== null) { |
||
339 | $select .= ' ' . $selectOption; |
||
340 | } |
||
341 | |||
342 | if (empty($columns)) { |
||
343 | return $select . ' *'; |
||
344 | } |
||
345 | |||
346 | /** @psalm-var array<array-key, ExpressionInterface|string> $columns */ |
||
347 | foreach ($columns as $i => $column) { |
||
348 | if ($column instanceof ExpressionInterface) { |
||
349 | if (is_int($i)) { |
||
350 | $columns[$i] = $this->buildExpression($column, $params); |
||
351 | } else { |
||
352 | $columns[$i] = $this->buildExpression($column, $params) . ' AS ' |
||
353 | . $this->quoter->quoteColumnName($i); |
||
354 | } |
||
355 | } elseif (is_string($i) && $i !== $column) { |
||
356 | if (!str_contains($column, '(')) { |
||
357 | $column = $this->quoter->quoteColumnName($column); |
||
358 | } |
||
359 | $columns[$i] = "$column AS " . $this->quoter->quoteColumnName($i); |
||
360 | } elseif (!str_contains($column, '(')) { |
||
361 | if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $column, $matches)) { |
||
362 | $columns[$i] = $this->quoter->quoteColumnName($matches[1]) |
||
363 | . ' AS ' . $this->quoter->quoteColumnName($matches[2]); |
||
364 | } else { |
||
365 | $columns[$i] = $this->quoter->quoteColumnName($column); |
||
366 | } |
||
367 | } |
||
368 | } |
||
369 | |||
370 | return $select . ' ' . implode(', ', $columns); |
||
371 | } |
||
372 | |||
373 | public function buildUnion(array $unions, array &$params): string |
||
374 | { |
||
375 | if (empty($unions)) { |
||
376 | return ''; |
||
377 | } |
||
378 | |||
379 | $result = ''; |
||
380 | |||
381 | /** @psalm-var array<array{query:Query|string, all:bool}> $unions */ |
||
382 | foreach ($unions as $i => $union) { |
||
383 | $query = $union['query']; |
||
384 | if ($query instanceof QueryInterface) { |
||
385 | [$unions[$i]['query'], $params] = $this->build($query, $params); |
||
386 | } |
||
387 | |||
388 | $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) '; |
||
389 | } |
||
390 | |||
391 | return trim($result); |
||
392 | } |
||
393 | |||
394 | public function buildWhere( |
||
395 | array|string|ConditionInterface|ExpressionInterface|null $condition, |
||
396 | array &$params = [] |
||
397 | ): string { |
||
398 | $where = $this->buildCondition($condition, $params); |
||
399 | return ($where === '') ? '' : ('WHERE ' . $where); |
||
400 | } |
||
401 | |||
402 | public function buildWithQueries(array $withs, array &$params): string |
||
403 | { |
||
404 | if (empty($withs)) { |
||
405 | return ''; |
||
406 | } |
||
407 | |||
408 | $recursive = false; |
||
409 | $result = []; |
||
410 | |||
411 | /** @psalm-var array<array-key, array{query:string|Query, alias:string, recursive:bool}> $withs */ |
||
412 | foreach ($withs as $with) { |
||
413 | if ($with['recursive']) { |
||
414 | $recursive = true; |
||
415 | } |
||
416 | |||
417 | $query = $with['query']; |
||
418 | if ($query instanceof QueryInterface) { |
||
419 | [$with['query'], $params] = $this->build($query, $params); |
||
420 | } |
||
421 | |||
422 | $result[] = $with['alias'] . ' AS (' . $with['query'] . ')'; |
||
423 | } |
||
424 | |||
425 | return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result); |
||
426 | } |
||
427 | |||
428 | public function createConditionFromArray(array $condition): ConditionInterface |
||
429 | { |
||
430 | /** operator format: operator, operand 1, operand 2, ... */ |
||
431 | if (isset($condition[0])) { |
||
432 | $operator = strtoupper((string) array_shift($condition)); |
||
433 | |||
434 | /** @var string $className */ |
||
435 | $className = $this->conditionClasses[$operator] ?? SimpleCondition::class; |
||
436 | |||
437 | /** @var ConditionInterface $className */ |
||
438 | return $className::fromArrayDefinition($operator, $condition); |
||
439 | } |
||
440 | |||
441 | /** hash format: 'column1' => 'value1', 'column2' => 'value2', ... */ |
||
442 | return new HashCondition($condition); |
||
443 | } |
||
444 | |||
445 | public function getExpressionBuilder(ExpressionInterface $expression): object |
||
446 | { |
||
447 | $className = $expression::class; |
||
448 | |||
449 | if (!isset($this->expressionBuilders[$className])) { |
||
450 | throw new InvalidArgumentException( |
||
451 | 'Expression of class ' . $className . ' can not be built in ' . static::class |
||
452 | ); |
||
453 | } |
||
454 | |||
455 | return new $this->expressionBuilders[$className]($this->queryBuilder); |
||
456 | } |
||
457 | |||
458 | public function selectExists(string $rawSql): string |
||
459 | { |
||
460 | return 'SELECT EXISTS(' . $rawSql . ')'; |
||
461 | } |
||
462 | |||
463 | public function setConditionClasses(array $classes): void |
||
464 | { |
||
465 | $this->conditionClasses = array_merge($this->conditionClasses, $classes); |
||
466 | } |
||
467 | |||
468 | public function setExpressionBuilders(array $builders): void |
||
469 | { |
||
470 | $this->expressionBuilders = array_merge($this->expressionBuilders, $builders); |
||
471 | } |
||
472 | |||
473 | /** |
||
474 | * @param string the separator between different fragments of a SQL statement. |
||
475 | * |
||
476 | * Defaults to an empty space. This is mainly used by {@see build()} when generating a SQL statement. |
||
477 | */ |
||
478 | public function setSeparator(string $separator): void |
||
479 | { |
||
480 | $this->separator = $separator; |
||
481 | } |
||
482 | |||
483 | /** |
||
484 | * Contains array of default condition classes. Extend this method, if you want to change default condition classes |
||
485 | * for the query builder. |
||
486 | * |
||
487 | * See {@see conditionClasses} docs for details. |
||
488 | */ |
||
489 | protected function defaultConditionClasses(): array |
||
490 | { |
||
491 | return [ |
||
492 | 'NOT' => Condition\NotCondition::class, |
||
493 | 'AND' => Condition\AndCondition::class, |
||
494 | 'OR' => Condition\OrCondition::class, |
||
495 | 'BETWEEN' => Condition\BetweenCondition::class, |
||
496 | 'NOT BETWEEN' => Condition\BetweenCondition::class, |
||
497 | 'IN' => Condition\InCondition::class, |
||
498 | 'NOT IN' => Condition\InCondition::class, |
||
499 | 'LIKE' => Condition\LikeCondition::class, |
||
500 | 'NOT LIKE' => Condition\LikeCondition::class, |
||
501 | 'OR LIKE' => Condition\LikeCondition::class, |
||
502 | 'OR NOT LIKE' => Condition\LikeCondition::class, |
||
503 | 'EXISTS' => Condition\ExistsCondition::class, |
||
504 | 'NOT EXISTS' => Condition\ExistsCondition::class, |
||
505 | ]; |
||
506 | } |
||
507 | |||
508 | /** |
||
509 | * Contains array of default expression builders. Extend this method and override it, if you want to change default |
||
510 | * expression builders for this query builder. |
||
511 | * |
||
512 | * See {@see expressionBuilders} docs for details. |
||
513 | * |
||
514 | * @psalm-return array<string, class-string<ExpressionBuilderInterface>> |
||
515 | */ |
||
516 | protected function defaultExpressionBuilders(): array |
||
517 | { |
||
518 | return [ |
||
519 | Query::class => QueryExpressionBuilder::class, |
||
520 | Param::class => ParamBuilder::class, |
||
521 | Expression::class => ExpressionBuilder::class, |
||
522 | Condition\AbstractConjunctionCondition::class => Condition\Builder\ConjunctionConditionBuilder::class, |
||
523 | Condition\NotCondition::class => Condition\Builder\NotConditionBuilder::class, |
||
524 | Condition\AndCondition::class => Condition\Builder\ConjunctionConditionBuilder::class, |
||
525 | Condition\OrCondition::class => Condition\Builder\ConjunctionConditionBuilder::class, |
||
526 | Condition\BetweenCondition::class => Condition\Builder\BetweenConditionBuilder::class, |
||
527 | Condition\InCondition::class => Condition\Builder\InConditionBuilder::class, |
||
528 | Condition\LikeCondition::class => Condition\Builder\LikeConditionBuilder::class, |
||
529 | Condition\ExistsCondition::class => Condition\Builder\ExistsConditionBuilder::class, |
||
530 | Condition\SimpleCondition::class => Condition\Builder\SimpleConditionBuilder::class, |
||
531 | Condition\HashCondition::class => Condition\Builder\HashConditionBuilder::class, |
||
532 | Condition\BetweenColumnsCondition::class => Condition\Builder\BetweenColumnsConditionBuilder::class, |
||
533 | ]; |
||
534 | } |
||
535 | |||
536 | /** |
||
537 | * Extracts table alias if there is one or returns false. |
||
538 | * |
||
539 | * @psalm-return string[]|bool |
||
540 | */ |
||
541 | protected function extractAlias(string $table): array|bool |
||
542 | { |
||
543 | if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { |
||
544 | return $matches; |
||
545 | } |
||
546 | |||
547 | return false; |
||
548 | } |
||
549 | |||
550 | /** |
||
551 | * Checks to see if the given limit is effective. |
||
552 | * |
||
553 | * @param mixed $limit the given limit. |
||
554 | * |
||
555 | * @return bool whether the limit is effective. |
||
556 | */ |
||
557 | protected function hasLimit(mixed $limit): bool |
||
558 | { |
||
559 | return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit); |
||
560 | } |
||
561 | |||
562 | /** |
||
563 | * Checks to see if the given offset is effective. |
||
564 | * |
||
565 | * @param mixed $offset the given offset. |
||
566 | * |
||
567 | * @return bool whether the offset is effective. |
||
568 | */ |
||
569 | protected function hasOffset(mixed $offset): bool |
||
570 | { |
||
571 | return ($offset instanceof ExpressionInterface) || (ctype_digit((string)$offset) && (string)$offset !== '0'); |
||
572 | } |
||
573 | |||
574 | /** |
||
575 | * Quotes table names passed. |
||
576 | * |
||
577 | * @throws Exception|InvalidConfigException|NotSupportedException |
||
578 | */ |
||
579 | private function quoteTableNames(array $tables, array &$params): array |
||
606 | } |
||
607 | } |
||
608 |