1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace QB\MySQL\Clause; |
6
|
|
|
|
7
|
|
|
use QB\Generic\IQueryPart; |
8
|
|
|
|
9
|
|
|
class CombiningQuery |
10
|
|
|
{ |
11
|
|
|
public const TYPE_UNION = 'UNION'; |
12
|
|
|
|
13
|
|
|
public const MODIFIER_ALL = 'ALL'; |
14
|
|
|
public const MODIFIER_DISTINCT = 'DISTINCT'; |
15
|
|
|
|
16
|
|
|
protected const VALID_TYPE = [null, self::TYPE_UNION]; |
17
|
|
|
protected const VALID_MODIFIERS = [null, self::MODIFIER_ALL, self::MODIFIER_DISTINCT]; |
18
|
|
|
|
19
|
|
|
protected string $type; |
20
|
|
|
|
21
|
|
|
protected IQueryPart $queryPart; |
22
|
|
|
|
23
|
|
|
protected ?string $modifier = null; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* CombiningQuery constructor. |
27
|
|
|
* |
28
|
|
|
* @param string $type |
29
|
|
|
* @param IQueryPart $queryPart |
30
|
|
|
* @param string|null $modifier |
31
|
|
|
*/ |
32
|
23 |
|
public function __construct(string $type, IQueryPart $queryPart, ?string $modifier = null) |
33
|
|
|
{ |
34
|
23 |
|
if (!$this->isValid($type, $modifier)) { |
35
|
5 |
|
throw new \InvalidArgumentException( |
36
|
5 |
|
sprintf('invalid arguments for %s. arguments: %s', __CLASS__, print_r([$type, $modifier], true)) |
|
|
|
|
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
18 |
|
$this->type = $type; |
41
|
18 |
|
$this->queryPart = $queryPart; |
42
|
18 |
|
$this->modifier = $modifier; |
43
|
18 |
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param string $type |
47
|
|
|
* @param string|null $modifier |
48
|
|
|
* |
49
|
|
|
* @return bool |
50
|
|
|
*/ |
51
|
23 |
|
private function isValid(string $type, ?string $modifier = null): bool |
52
|
|
|
{ |
53
|
23 |
|
if (!in_array($type, static::VALID_TYPE, true)) { |
54
|
2 |
|
return false; |
55
|
|
|
} |
56
|
|
|
|
57
|
21 |
|
if (!in_array($modifier, static::VALID_MODIFIERS, true)) { |
58
|
3 |
|
return false; |
59
|
|
|
} |
60
|
|
|
|
61
|
18 |
|
return true; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
18 |
|
public function __toString(): string |
68
|
|
|
{ |
69
|
18 |
|
$modifier = ''; |
70
|
18 |
|
if ($this->modifier) { |
71
|
5 |
|
$modifier = ' ' . $this->modifier; |
72
|
|
|
} |
73
|
|
|
|
74
|
18 |
|
$parts = []; |
75
|
18 |
|
$parts[] = $this->type . $modifier; |
76
|
18 |
|
$parts[] = (string)$this->queryPart; |
77
|
|
|
|
78
|
18 |
|
return implode(PHP_EOL, $parts); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|