1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Grido\DataSources;
13
14 use Grido\Components\Filters\Condition;
15
16 17 18 19 20 21 22 23 24 25 26
27 class NetteDatabase extends \Nette\Object implements IDataSource
28 {
29
30 protected $selection;
31
32 33 34
35 public function __construct(\Nette\Database\Table\Selection $selection)
36 {
37 $this->selection = $selection;
38 }
39
40 41 42
43 public function getSelection()
44 {
45 return $this->selection;
46 }
47
48 49 50 51
52 protected function makeWhere(Condition $condition, \Nette\Database\Table\Selection $selection = NULL)
53 {
54 $selection = $selection === NULL
55 ? $this->selection
56 : $selection;
57
58 if ($condition->callback) {
59 callback($condition->callback)->invokeArgs(array($condition->value, $selection));
60 } else {
61 call_user_func_array(array($selection, 'where'), $condition->__toArray());
62 }
63 }
64
65
66
67 68 69 70 71 72 73
74 public function update($id, array $values, $idCol)
75 {
76 return (bool) $this->getSelection()
77 ->where(array($idCol => $id))
78 ->update($values);
79 }
80
81 82 83 84 85 86
87 public function getRow($id, $idCol)
88 {
89 return $this->getSelection()
90 ->where(array($idCol => $id))
91 ->fetch();
92 }
93
94
95
96 97 98
99 public function getCount()
100 {
101 return (int) $this->selection->count('*');
102 }
103
104 105 106
107 public function getData()
108 {
109 return $this->selection;
110 }
111
112 113 114
115 public function filter(array $conditions)
116 {
117 foreach ($conditions as $condition) {
118 $this->makeWhere($condition);
119 }
120 }
121
122 123 124 125
126 public function limit($offset, $limit)
127 {
128 $this->selection->limit($limit, $offset);
129 }
130
131 132 133
134 public function sort(array $sorting)
135 {
136 foreach ($sorting as $column => $sort) {
137 $this->selection->order("$column $sort");
138 }
139 }
140
141 142 143 144 145 146 147
148 public function suggest($column, array $conditions, $limit)
149 {
150 $selection = clone $this->selection;
151 is_string($column) && $selection->select("DISTINCT $column");
152 $selection->limit($limit);
153
154 foreach ($conditions as $condition) {
155 $this->makeWhere($condition, $selection);
156 }
157
158 $items = array();
159 foreach ($selection as $row) {
160 if (is_string($column)) {
161 $value = (string) $row[$column];
162 } elseif (is_callable($column)) {
163 $value = (string) $column($row);
164 } else {
165 $type = gettype($column);
166 throw new \InvalidArgumentException("Column of suggestion must be string or callback, $type given.");
167 }
168
169 $items[$value] = \Nette\Templating\Helpers::escapeHtml($value);
170 }
171
172 return array_values($items);
173 }
174 }
175