Issues (87)

src/Builder/Traits/UnionBuilder.php (1 issue)

1
<?php
2
3
namespace Kir\MySQL\Builder\Traits;
4
5
use Kir\MySQL\Builder\Select;
6
7
trait UnionBuilder {
8
	use AbstractDB;
9
10
	/** @var array<int, array{''|'ALL', string|Select}> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, array{''|'ALL', string|Select}> at position 6 could not be parsed: Expected ':' at position 6, but found ''''.
Loading history...
11
	private array $unions = [];
12
13
	/**
14
	 * @param string|Select ...$queries
15
	 * @return $this
16
	 */
17
	public function union(...$queries) {
18
		foreach($queries as $query) {
19
			$this->unions[] = ['', $query];
20
		}
21
22
		return $this;
23
	}
24
25
	/**
26
	 * @param string|Select ...$queries
27
	 * @return $this
28
	 */
29
	public function unionAll(...$queries) {
30
		foreach($queries as $query) {
31
			$this->unions[] = ['ALL', $query];
32
		}
33
34
		return $this;
35
	}
36
37
	/**
38
	 * @param string $query
39
	 * @return string
40
	 */
41
	protected function buildUnions(string $query): string {
42
		$wrap = static function($query) {
43
			$query = trim($query);
44
			$query = implode("\n\t", explode("\n", $query));
45
46
			return sprintf("(\n\t%s\n)", $query);
47
		};
48
		$queries = [$wrap($query)];
49
		foreach($this->unions as $unionQuery) {
50
			if($unionQuery[0] === 'ALL') {
51
				$queries[] = 'UNION ALL';
52
			} else {
53
				$queries[] = 'UNION';
54
			}
55
			$queries[] = $wrap($unionQuery[1]);
56
		}
57
		if(count($queries) > 1) {
58
			return implode(' ', $queries);
59
		}
60
61
		return $query;
62
	}
63
}
64