1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Muffin\Queries\Snippets; |
4
|
|
|
|
5
|
|
|
use Muffin\Snippet; |
6
|
|
|
|
7
|
|
|
class Select implements Snippet |
8
|
|
|
{ |
9
|
|
|
private |
10
|
|
|
$columns; |
11
|
|
|
|
12
|
33 |
|
public function __construct($columns = array()) |
13
|
|
|
{ |
14
|
33 |
|
$this->columns = array(); |
15
|
|
|
|
16
|
33 |
|
$this->addColumns($columns); |
17
|
32 |
|
} |
18
|
|
|
|
19
|
28 |
|
public function select($columns) |
|
|
|
|
20
|
|
|
{ |
21
|
28 |
|
$this->addColumns($columns); |
22
|
|
|
|
23
|
28 |
|
return $this; |
24
|
|
|
} |
25
|
|
|
|
26
|
31 |
|
public function toString() |
27
|
|
|
{ |
28
|
31 |
|
if(empty($this->columns)) |
29
|
31 |
|
{ |
30
|
2 |
|
throw new \LogicException('No columns defined for SELECT clause'); |
31
|
|
|
} |
32
|
|
|
|
33
|
29 |
|
return sprintf('SELECT %s', $this->buildColumnsString()); |
34
|
|
|
} |
35
|
|
|
|
36
|
29 |
|
private function buildColumnsString() |
37
|
|
|
{ |
38
|
29 |
|
$columns = array(); |
39
|
|
|
|
40
|
29 |
|
foreach($this->columns as $column) |
41
|
|
|
{ |
42
|
29 |
|
if($column instanceof Selectable) |
43
|
29 |
|
{ |
44
|
2 |
|
$column = $column->toString(); |
45
|
2 |
|
} |
46
|
|
|
|
47
|
29 |
|
$columns[] = $column; |
48
|
29 |
|
} |
49
|
|
|
|
50
|
29 |
|
return implode(', ', array_unique($columns)); |
51
|
|
|
} |
52
|
|
|
|
53
|
33 |
|
private function addColumns($columns) |
54
|
|
|
{ |
55
|
33 |
|
$columns = array_filter($this->ensureIsArray($columns)); |
56
|
|
|
|
57
|
33 |
|
$this->validateColumns($columns); |
58
|
|
|
|
59
|
32 |
|
$this->columns = array_merge($this->columns, $columns); |
60
|
32 |
|
} |
61
|
|
|
|
62
|
33 |
|
private function validateColumns($columns) |
63
|
|
|
{ |
64
|
33 |
|
foreach($columns as $column) |
65
|
|
|
{ |
66
|
31 |
|
if(! is_string($column) && (!$column instanceof Selectable)) |
67
|
31 |
|
{ |
68
|
1 |
|
throw new \InvalidArgumentException('Column name must be a string.'); |
69
|
|
|
} |
70
|
33 |
|
} |
71
|
32 |
|
} |
72
|
|
|
|
73
|
33 |
|
private function ensureIsArray($select) |
74
|
|
|
{ |
75
|
33 |
|
if(! is_array($select)) |
76
|
33 |
|
{ |
77
|
21 |
|
$select = array($select); |
78
|
21 |
|
} |
79
|
|
|
|
80
|
33 |
|
return $select; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|