|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Puzzle\QueryBuilder\Queries\Snippets; |
|
6
|
|
|
|
|
7
|
|
|
use Puzzle\QueryBuilder\Snippet; |
|
8
|
|
|
|
|
9
|
|
|
class Select implements Snippet |
|
10
|
|
|
{ |
|
11
|
|
|
private |
|
12
|
|
|
$columns; |
|
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @param array[string|Selectable] | string|Selectable $columns |
|
16
|
|
|
*/ |
|
17
|
33 |
|
public function __construct($columns = []) |
|
18
|
|
|
{ |
|
19
|
33 |
|
$this->columns = []; |
|
20
|
|
|
|
|
21
|
33 |
|
$this->addColumns($columns); |
|
22
|
32 |
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param array[string|Selectable] | string|Selectable $columns |
|
26
|
|
|
*/ |
|
27
|
28 |
|
public function select($columns): self |
|
28
|
|
|
{ |
|
29
|
28 |
|
$this->addColumns($columns); |
|
30
|
|
|
|
|
31
|
28 |
|
return $this; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
31 |
|
public function toString(): string |
|
35
|
|
|
{ |
|
36
|
31 |
|
if(empty($this->columns)) |
|
37
|
|
|
{ |
|
38
|
2 |
|
throw new \LogicException('No columns defined for SELECT clause'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
29 |
|
return sprintf('SELECT %s', $this->buildColumnsString()); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
29 |
|
private function buildColumnsString() |
|
45
|
|
|
{ |
|
46
|
29 |
|
$columns = array(); |
|
47
|
|
|
|
|
48
|
29 |
|
foreach($this->columns as $column) |
|
49
|
|
|
{ |
|
50
|
29 |
|
if($column instanceof Selectable) |
|
51
|
|
|
{ |
|
52
|
2 |
|
$column = $column->toString(); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
29 |
|
$columns[] = $column; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
29 |
|
return implode(', ', array_unique($columns)); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
33 |
|
private function addColumns($columns): void |
|
62
|
|
|
{ |
|
63
|
33 |
|
$columns = array_filter($this->ensureIsArray($columns)); |
|
64
|
|
|
|
|
65
|
33 |
|
$this->validateColumns($columns); |
|
66
|
|
|
|
|
67
|
32 |
|
$this->columns = array_merge($this->columns, $columns); |
|
68
|
32 |
|
} |
|
69
|
|
|
|
|
70
|
33 |
|
private function validateColumns($columns) |
|
71
|
|
|
{ |
|
72
|
33 |
|
foreach($columns as $column) |
|
73
|
|
|
{ |
|
74
|
31 |
|
if(! is_string($column) && (!$column instanceof Selectable)) |
|
75
|
|
|
{ |
|
76
|
1 |
|
throw new \InvalidArgumentException('Column name must be a string.'); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
32 |
|
} |
|
80
|
|
|
|
|
81
|
33 |
|
private function ensureIsArray($select): array |
|
82
|
|
|
{ |
|
83
|
33 |
|
if(! is_array($select)) |
|
84
|
|
|
{ |
|
85
|
21 |
|
$select = array($select); |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
33 |
|
return $select; |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|
The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using
the property is implicitly global.
To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.