-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdumbledorm.php
504 lines (464 loc) · 13.9 KB
/
dumbledorm.php
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<?php
/**
*
* DumbledORM
*
* @version 0.1.1
* @author Jason Mooberry <jasonmoo@me.com>
* @link http://github.com/jasonmoo/DumbledORM
* @package DumbledORM
*
* DumbledORM is a novelty PHP ORM
*
* Copyright (c) 2010 Jason Mooberry
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
* exceptional moments defined here
*/
class RecordNotFoundException extends Exception {}
/**
* Class for denoting sql that should be inserted into the query directly without escaping
*
*/
final class PlainSql {
private $_sql;
public function __construct($sql) { $this->_sql = $sql; }
public function __toString() { return $this->_sql; }
}
/**
* Builder class for required for generating base classes
*
*/
abstract class Builder {
/**
* simple cameCasing method
*
* @param string $string
* @return string
*/
public static function camelCase($string) {
return ucfirst(preg_replace("/_(\w)/e","strtoupper('\\1')",strtolower($string)));
}
/**
* simple un_camel_casing method
*
* @param string $string
* @return string
*/
public static function unCamelCase($string) {
return strtolower(preg_replace("/(\w)([A-Z])/","\\1_\\2",$string));
}
/**
* re/generates base classes for db schema
*
* @param string $prefix
* @param string $dir
* @return void
*/
public static function generateBase($prefix=null,$dir='model') {
$tables = array();
foreach (Db::query('show tables',null,PDO::FETCH_NUM) as $row) {
foreach (Db::query('show columns from `'.$row[0].'`') as $col) {
if ($col['Key'] === 'PRI') {
$tables[$row[0]]['pk'] = $col['Field']; break;
}
}
}
foreach (array_keys($tables) as $table) {
foreach (Db::query('show columns from `'.$table.'`') as $col) {
if (substr($col['Field'],-3,3) === '_id') {
$rel = substr($col['Field'],0,-3);
if (array_key_exists($rel,$tables)) {
if ($table === "{$rel}_meta") {
$tables[$rel]['meta']['class'] = self::camelCase($table);
$tables[$rel]['meta']['field'] = $col['Field'];
}
$tables[$table]['relations'][$rel] = array('fk' => 'id', 'lk' => $col['Field']);
$tables[$rel]['relations'][$table] = array('fk' => $col['Field'], 'lk' => 'id');
}
}
}
}
$basetables = "<?php\nspl_autoload_register(function(\$class) { @include(__DIR__.\"/\$class.class.php\"); });\n";
foreach ($tables as $table => $conf) {
$relations = preg_replace('/[\n\t\s]+/','',var_export((array)@$conf['relations'],true));
$meta = isset($conf['meta']) ? "\$meta_class = '{$conf['meta']['class']}', \$meta_field = '{$conf['meta']['field']}'," : '';
$basetables .= "class ".$prefix.self::camelCase($table)."Base extends BaseTable { protected static \$table = '$table', \$pk = '{$conf['pk']}', $meta \$relations = $relations; }\n";
}
@mkdir("./$dir",0777,true);
file_put_contents("./$dir/base.php",$basetables);
foreach (array_keys($tables) as $table) {
$file = "./$dir/$prefix".self::camelCase($table).'.class.php';
if (!file_exists($file)) {
file_put_contents($file,"<?php\nclass ".$prefix.self::camelCase($table).' extends '.$prefix.self::camelCase($table).'Base {}');
}
}
}
}
/**
* thin wrapper for PDO access
*
*/
abstract class Db {
/**
* singleton variable for PDO connection
*
*/
private static $_pdo;
/**
* singleton getter for PDO connection
*
* @return PDO
*/
public static function pdo() {
if (!self::$_pdo) {
self::$_pdo = new PDO('mysql:host='.DbConfig::HOST.';port='.DbConfig::PORT.';dbname='.DbConfig::DBNAME, DbConfig::USER, DbConfig::PASSWORD);
self::$_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$_pdo;
}
/**
* execute sql as a prepared statement
*
* @param string $sql
* @param mixed $params
* @return PDOStatement
*/
public static function execute($sql,$params=null) {
$params = is_array($params) ? $params : array($params);
if ($params) {
// using preg_replace_callback ensures that any inserted PlainSql
// with ?'s in it will not be confused for replacement markers
$sql = preg_replace_callback('/\?/',function($a) use (&$params) {
$a = array_shift($params);
if ($a instanceof PlainSql) {
return $a;
}
$params[] = $a;
return '?';
},$sql);
}
$stmt = self::pdo()->prepare($sql);
$stmt->execute($params);
return $stmt;
}
/**
* execute sql as a prepared statement and return all records
*
* @param string $query
* @param mixed $params
* @param PDO constant $fetch_style
* @return Array
*/
public static function query($query,$params=null,$fetch_style=PDO::FETCH_ASSOC) {
return self::execute($query,$params)->fetchAll($fetch_style);
}
/**
* run a query and return the results as a ResultSet of BaseTable objects
*
* @param BaseTable $obj
* @param string $query
* @param mixed $params
* @return ResultSet
*/
public static function hydrate(BaseTable $obj,$query,$params=null) {
$set = array();
foreach (self::query($query,$params) as $record) {
$clone = clone $obj;
$clone->hydrate($record);
$set[$clone->getId()] = $clone;
}
return new ResultSet($set);
}
}
/**
* class to manage result array more effectively
*
*/
final class ResultSet extends ArrayIterator {
/**
* magic method for applying called methods to all members of result set
*
* @param string $method
* @param Array $params
* @return $this
*/
public function __call($method,$params=array()) {
foreach ($this as $obj) {
call_user_func_array(array($obj,$method),$params);
}
return $this;
}
}
/**
* base functionality available to all objects extending from a generated base class
*
*/
abstract class BaseTable {
protected static
/**
* table name
*/
$table,
/**
* primary key
*/
$pk,
/**
* table relations array
*/
$relations,
/**
* metadata class name
*/
$meta_class,
/**
* metadata field
*/
$meta_field;
protected
/**
* record data array
*/
$data,
/**
* metadata array
*/
$meta,
/**
* relation data array
*/
$relation_data,
/**
* record primary key value
*/
$id,
/**
* array of data fields that have changed since hydration
*/
$changed;
/**
* search for single record in self::$table
*
* @param Array $constraints
* @return BaseTable
*/
final public static function one(Array $constraints) {
return self::select('`'.implode('` = ? and `',array_keys($constraints)).'` = ? limit 1',array_values($constraints))->current();
}
/**
* search for any number of records in self::$table
*
* @param Array $constraints
* @return ResultSet
*/
final public static function find(Array $constraints) {
return self::select('`'.implode('` = ? and `',array_keys($constraints)).'` = ?',array_values($constraints));
}
/**
* execute a query in self::$table
*
* @param string $qs
* @param mixed $params
* @return ResultSet
*/
final public static function select($qs,$params=null) {
return Db::hydrate(new static,'select * from `'.static::$table.'` where '.$qs,$params);
}
/**
* construct object and load supplied data or fetch data by supplied id
*
* @param mixed $val
*/
public function __construct($val=null) {
if (is_array($val)) {
$this->data = $val;
$this->changed = array_flip(array_keys($this->data));
$this->_loadMeta();
} else if (is_numeric($val)) {
if (!$obj = self::one(array(static::$pk => $val))) {
throw new RecordNotFoundException("Nothing to be found with id $val");
}
$this->hydrate($obj->toArray());
}
}
/**
* most of the magic in here makes it all work
* - handles all getters and setters on columns and relations
*
* @param string $method
* @param Array $params
* @return mixed
*/
final public function __call($method,$params=array()) {
$name = Builder::unCamelCase(substr($method,3,strlen($method)));
if (strpos($method,'get')===0) {
if (array_key_exists($name,$this->data)) {
return $this->data[$name];
}
if (isset(static::$relations[$name])) {
$class = substr($method,3,strlen($method));
if (count($params)) {
if ($params[0] === true) {
return @$this->relation_data[$name.'_all'] ?: $this->relation_data[$name.'_all'] = $class::find(array(static::$relations[$name]['fk'] => $this->getId()));
}
$qparams = array_merge(array($this->getId()),(array)@$params[1]);
$qk = md5(serialize(array($name,$params[0],$qparams)));
return @$this->relation_data[$qk] ?: $this->relation_data[$qk] = $class::select('`'.static::$relations[$name]['fk'].'` = ? and '.$params[0],$qparams);
}
return @$this->relation_data[$name] ?: $this->relation_data[$name] = $class::one(array(static::$relations[$name]['fk'] => $this->getId()));
}
}
else if (strpos($method,'set')===0) {
$this->changed[$name] = true;
$this->data[$name] = array_shift($params);
return $this;
}
throw new BadMethodCallException("No amount of magic can make $method work..");
}
/**
* simple output object data as array
*
* @return Array
*/
final public function toArray() {
return $this->data;
}
/**
* simple output object pk id
*
* @return integer
*/
final public function getId() {
return $this->id;
}
/**
* store supplied data and bring object state to current
*
* @param Array $data
* @return $this
*/
final public function hydrate(Array $data) {
$this->id = $data[static::$pk];
$this->data = $data;
$this->_loadMeta();
$this->changed = array();
return $this;
}
/**
* create an object with a defined relation to this one.
*
* @param BaseTable $obj
* @return BaseTable
*/
final public function create(BaseTable $obj) {
return $obj->{'set'.Builder::camelCase(static::$relations[Builder::unCamelCase(get_class($obj))]['fk'])}($this->id);
}
/**
* insert or update modified object data into self::$table and any associated metadata
*
* @return void
*/
public function save() {
if (empty($this->changed)) return;
$data = array_intersect_key($this->data,$this->changed);
// use proper sql NULL for values set to php null
foreach ($data as $key => $value) {
if ($value === null) {
$data[$key] = new PlainSql('NULL');
}
}
if ($this->id) {
$query = 'update `'.static::$table.'` set `'.implode('` = ?, `',array_keys($data)).'` = ? where `'.static::$pk.'` = '.$this->id.' limit 1';
}
else {
$query = 'insert into `'.static::$table.'` (`'.implode('`,`',array_keys($data))."`) values (".rtrim(str_repeat('?,',count($data)),',').")";
}
Db::execute($query,array_values($data));
if ($this->id === null) {
$this->id = Db::pdo()->lastInsertId();
}
$this->meta->{'set'.Builder::camelCase(static::$meta_field)}($this->id)->save();
$this->hydrate(self::one(array(static::$pk => $this->id))->toArray());
}
/**
* delete this object's record from self::$table and any associated meta data
*
* @return void
*/
public function delete() {
Db::execute('delete from `'.static::$table.'` where `'.static::$pk.'` = ? limit 1',$this->getId());
$this->meta->delete();
}
/**
* add an array of key/val to the metadata
*
* @param Array $data
* @return $this
*/
public function addMeta(Array $data) {
foreach ($data as $field => $val) {
$this->setMeta($field,$val);
}
return $this;
}
/**
* set a field of metadata
*
* @param string $field
* @param string $val
* @return $this
*/
public function setMeta($field,$val) {
if (empty($this->meta[$field])) {
$meta_class = static::$meta_class;
$this->meta[$field] = new $meta_class(array('key' => $field,'val' => $val));
}
else {
$this->meta[$field]->setVal($val);
}
return $this;
}
/**
* get a field of metadata
*
* @param string $field
* @return mixed
*/
public function getMeta($field) {
return isset($this->meta[$field]) ? $this->meta[$field]->getVal() : null;
}
/**
* internally fetch and load any associated metadata
*
* @return void
*/
private function _loadMeta() {
if (!$meta_class = static::$meta_class) {
return $this->meta = new ResultSet;
}
foreach ($meta_class::find(array(static::$meta_field => $this->getId())) as $obj) {
$meta[$obj->getKey()] = $obj;
}
$this->meta = new ResultSet((array)@$meta);
}
}