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