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