GroupByBuilder::buildGroups()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 3
nc 3
nop 1
1
<?php
2
namespace Kir\MySQL\Builder\Traits;
3
4
use Kir\MySQL\Builder;
5
6
trait GroupByBuilder {
7
	use AbstractDB;
8
9
	/** @var string[] */
10
	private array $groupBy = [];
11
12
	/**
13
	 * @param mixed ...$args
14
	 * @return $this
15
	 */
16
	public function groupBy(...$args) {
17
		foreach($args as $expression) {
18
			if(is_array($expression)) {
19
				if(!count($expression)) {
20
					continue;
21
				}
22
				$expression = $this->quoteExpr($expression[0], array_slice($expression, 1));
23
			}
24
			$this->groupBy[] = $expression;
25
		}
26
		return $this;
27
	}
28
29
	/**
30
	 * @param string $query
31
	 * @return string
32
	 */
33
	protected function buildGroups(string $query): string {
34
		if(!count($this->groupBy)) {
35
			return $query;
36
		}
37
		$query .= "GROUP BY\n";
38
		$arr = [];
39
		foreach($this->groupBy as $expression) {
40
			$arr[] = "\t{$expression}";
41
		}
42
		return $query.implode(",\n", $arr)."\n";
43
	}
44
45
	/**
46
	 * @param string $expression
47
	 * @param array<int, null|int|float|string|array<int, string>|Builder\DBExpr|Builder\Select> $arguments
48
	 * @return string
49
	 */
50
	protected function quoteExpr(string $expression, array $arguments): string {
51
		return $this->db()->quoteExpression($expression, $arguments);
52
	}
53
}
54