forked from SugiPHP/Database
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.php
More file actions
349 lines (313 loc) · 7.23 KB
/
Database.php
File metadata and controls
349 lines (313 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
/**
* @package SugiPHP
* @subpackage Database
* @author Plamen Popov <tzappa@gmail.com>
* @license http://opensource.org/licenses/mit-license.php (MIT License)
*/
namespace SugiPHP\Database;
class Database
{
/**
* Database driver instance.
*
* @var object DriverInterface
*/
protected $driver;
/**
* Hooks
* @var array of events
*/
protected $hooks = array();
/**
* Constructor.
*
* @param DriverInterface $driver
*/
public function __construct(DriverInterface $driver)
{
$this->driver = $driver;
}
/**
* Class destructor
*/
public function __destruct()
{
$this->close();
}
/**
* Calling methods that are only part of the database driver
*/
public function __call($method, $args)
{
if (method_exists($this->driver, $method)) {
return call_user_func_array(array($this->driver, $method), $args);
}
throw new Exception("Method $method does not exist", "internal_error");
}
/**
* Returns the driver in use.
*
* @return DriverInterface
*/
public function getDriver()
{
return $this->driver;
}
/**
* Opens connection to the database
*/
public function open()
{
if (!$this->driver->getHandle()) {
$this->triggerAction("pre", "open");
$this->driver->open();
$this->triggerAction("post", "open");
}
}
/**
* Closes connection to the database
*/
public function close()
{
if ($this->driver->getHandle()) {
$this->triggerAction("pre", "close");
$this->driver->close();
$this->triggerAction("post", "close");
}
}
/**
* Escape method
*
* @param string $item
* @return string
*/
public function escape($item)
{
// For delayed opens
$this->open();
return $this->driver->escape($item);
}
/**
* Executes query.
* Query could be any valid SQL statement.
*
* @param string $sql
* @throws SugiPHP\Database\Exception If the query fails
* @return mixed
*/
public function query($sql)
{
// For delayed opens
$this->open();
$this->triggerAction("pre", "query", $sql);
if ($res = $this->driver->query($sql)) {
$this->triggerAction("post", "query", $sql);
return $res;
}
throw new Exception($this->driver->error(), "sql_error");
}
/**
* Fetches one row
*
* @param handle $res result returned from query()
* @return array
* @throws SugiPHP\Database\Exception
*/
public function fetch($res)
{
try {
$res = $this->driver->fetch($res);
} catch (\Exception $e) {
throw new Exception($e->getMessage(), "resource_error");
}
return $res;
}
/**
* Fetches all rows
*
* @param handle $res result returned from query()
* @return array
*/
public function fetchAll($res)
{
$return = array();
while ($row = $this->fetch($res)) {
$return[] = $row;
}
return $return;
}
/**
* Fetches all rows
*
* @param string $sql SQL statement
* @return array
*/
public function all($sql)
{
return $this->fetchAll($this->query($sql));
}
/**
* Fetches single row
*
* @param string $sql SQL statement
* @return array|null
*/
public function single($sql)
{
if ($res = $this->query($sql)) {
return $this->fetch($res);
}
return null;
}
/**
* Returns first field of the first row
*
* @param string $sql - SQL statment
* @return string|null
*/
public function singleField($sql)
{
if ($row = $this->single($sql)) {
return array_shift($row);
}
return null;
}
/**
* Returns rows affected by the query
*
* @param handle $res handle returned by query()
* @return integer
*/
public function affected($res = null)
{
return $this->driver->affected($res);
}
/**
* Returns last ID returned after successful INSERT statement
*
* @return mixed
*/
public function lastId()
{
return $this->driver->lastId();
}
/**
* Frees result
*
* @param handle $res handle returned by query()
* @throws SugiPHP\Database\Exception
*/
public function free($res)
{
if (!$res) {
throw new Exception("Could not free invalid resource.", "resource_error");
}
$this->driver->free($res);
}
/**
* Hook a callback function/method to some hookable events.
* Hooks could be 'pre_' and 'post_'.
*
* <code>
* // to hook an event before executing a query
* Database::hook('pre_query', array($object, 'method_name'));
* // to hook an event after executing a query
* Database::hook('post_query', 'function_name')
* </code>
*
* @param string $event - pre or post method name
* @param mixed $callback - callable function or method name
*/
public function hook($event, $callback)
{
if (is_array($callback)) $inx = get_class($callback[0])."::".$callback[1];
elseif (gettype($callback) == "object") $inx = uniqid();
else $inx = $callback;
$this->hooks[$event][$inx] = $callback;
}
/**
* Unhook.
* If callback is not given all callbacks are unhooked from this event.
* If event is not given all callbacks are unhooked.
*
* <code>
* Database::unhook('pre_query', array($this, 'before_query')); // This will unhook method $this->before_query before query
* Database::unhook('post_query'); // This will unhook all callbacks which are executed after query
* Database::unhook(); // This will unhook all callbacks
* Database::unhook(false, 'test'); // This will unhook callback function test from any (pre and post) events
* </code>
*
* @param string $event
* @param mixed $callback - callback function to unhook.
*/
public function unhook($event = null, $callback = null)
{
if (is_array($callback)) $inx = get_class($callback[0])."::".$callback[1];
else $inx = $callback;
if (is_null($event) AND is_null($callback)) {
$this->hooks = array();
}
elseif (is_null($callback)) {
$this->hooks[$event] = array();
}
elseif (is_null($event)) {
foreach ($this->hooks as $key => $value) {
unset($this->hooks[$key][$inx]);
}
}
else {
unset($this->hooks[$event][$inx]);
}
}
/**
* Escapes each element in the array
*
* @param array
* @return array
*/
public function escapeAll(array $values)
{
$return = array();
foreach ($values as $key => $value) {
if (is_null($value)) $value = "null";
elseif (is_numeric($value)) $value = "'" . $value . "'";
elseif (is_bool($value)) $value = $value ? "TRUE" : "FALSE";
else $value = "'" . $this->escape($value) . "'";
$return[$key] = $value;
}
return $return;
}
/**
* Escapes all parameters and binds them in the SQL
*
* @param string $sql
* @param array $params Associative array, where the key is replaced in the SQL with the value
* @param boolean $nullMissing - set NULL when the param is missing
* @return string
*/
public function bindParams($sql, array $params, $nullMissing = true)
{
$params = $this->escapeAll($params);
if (preg_match_all("#:([a-zA-Z0-9_]+)#", $sql, $matches)) {
foreach ($matches[1] as $match) {
if (isset($params[$match])) {
$sql = str_replace(":$match", $params[$match], $sql);
} elseif ($nullMissing) {
$sql = str_replace(":$match", "null", $sql);
}
}
}
return $sql;
}
protected function triggerAction($type, $action, $data = null)
{
$hook = "{$type}_{$action}";
// check for hooks
if (!empty($this->hooks[$hook])) {
foreach ($this->hooks[$hook] as $callback) {
$callback($action, $data);
}
}
}
}