-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBasicObject.php
1063 lines (1002 loc) · 30.6 KB
/
BasicObject.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* {@example BasicObjectExample.php}
*/
abstract class BasicObject {
protected $_data;
protected $_old_key = array();
protected $_exists;
public static $output_htmlspecialchars;
/**
* Runs the callback with a output_htmlspecialchars temporary value set
* and returns the value that the callback returned
*/
public static function with_tmp_htmlspecialchars($tmp_value, $callback) {
$current_value = BasicObject::$output_htmlspecialchars;
BasicObject::$output_htmlspecialchars = $tmp_value;
$ret = $callback();
BasicObject::$output_htmlspecialchars = $current_value;
return $ret;
}
/**
* Returns the table name associated with this class.
* @return The name of the table this class is associated with.
*/
// abstract protected static function table_name();
/**
* Returns the table name associated with this class.
* @return The name of the table this class is associated with.
*/
private static function id_name($class_name = null){
$pk = static::primary_key($class_name);
if(count($pk) < 1) {
return null;
}
if(count($pk) > 1) {
return $pk;
}
return $pk[0];
}
private static function primary_key($class_name = null) {
global $db;
static $column_ids = array();
if(class_exists($class_name) && is_subclass_of($class_name, 'BasicObject')){
$table_name = $class_name::table_name();
} elseif($class_name == null) {
$table_name = static::table_name();
} else {
$table_name = $class_name;
}
if(!array_key_exists($table_name, $column_ids)){
$stmt = $db->prepare("
SELECT
`COLUMN_NAME`
FROM
`information_schema`.`key_column_usage` join
`information_schema`.`table_constraints` USING (`CONSTRAINT_NAME`, `CONSTRAINT_SCHEMA`, `TABLE_NAME`)
WHERE
`table_constraints`.`CONSTRAINT_TYPE` = 'PRIMARY KEY' AND
`table_constraints`.`CONSTRAINT_SCHEMA` = ? AND
`table_constraints`.`TABLE_NAME` = ?"
);
$db_name = self::get_database_name();
$stmt->bind_param('ss', $db_name, $table_name);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($index);
$column_ids[$table_name] = array();
while($stmt->fetch()) {
$column_ids[$table_name][] = $index;
}
$stmt->close();
}
return $column_ids[$table_name];
}
private static function unique_identifier($class_name = null) {
if(class_exists($class_name) && is_subclass_of($class_name, 'BasicObject')){
$table_name = $class_name::table_name();
} elseif($class_name == null) {
$table_name = static::table_name();
} else {
$table_name = $class_name;
}
$pk = static::primary_key($class_name);
if(count($pk)==1) {
return "`$table_name`.`{$pk[0]}`";
} elseif(empty($pk)) {
throw new Exception("A table should have a primary key to use BasicObject");
} else {
return 'concat(`'.$table_name.'`.`'.implode("`, '¤', `$table_name`.`", $pk).'`)';
}
}
/**
* @param $array Assoc array of values to set in this instance
* @param $exists Set to true to mark that this is an existing object, and that commits should use update
*/
public function __construct($array = null, $exists=false) {
if($exists && empty($array)) {
throw new Exception("Can't create new instance marked as existing with an empty data array");
}
$this->_exists = $exists;
$this->_data = $array;
}
/**
* Clone is called on the new object once cloning is complete
*/
public function __clone() {
$this->_exists = false;
$this->_data[$this->id_name()]=null;
}
/**
* Returns values in this table or Objects of neighboring tables if there is a foreign key.
* @param array Only alowed when accessing other tables. Extra paramaters for selection
* see selection() for details.
* @returns mixed If the function name is the exact name of a neighboring class, an object or
* a list of objects is returned depending on the direction of the foreign key.
* Oterwise if there exists a value ($object->value) that has the same name as the name called,
* then that value is returned.
*/
public function __call($name, $arguments){
if(class_exists($name) && is_subclass_of($name, 'BasicObject')){
$other_table = $name::table_name();
$con = $this->connection($this->table_name(), $other_table);
if($con) {
if(isset($arguments[0]) && is_array($arguments[0])){
$params = $arguments[0];
} else {
$params = array();
}
if($con['TABLE_NAME'] == $this->table_name()){
// We know them (single value)
$ref_name = $con['COLUMN_NAME'];
return $name::from_id($this->$ref_name);
} else {
// They know us (multiple values)
$params[$con['COLUMN_NAME']] = $this->id;
return $name::selection($params);
}
}
}
if(count($arguments) == 0 && $name != 'table_name'){
try{
return $this->__get($name);
} catch(UndefinedMemberException $e) {
}
}
throw new UndefinedFunctionException("Undefined call to function '".__CLASS__."::$name'");
}
/**
* Returns values in this table or Objects of neighboring tables if there is a foreign key.
* Overload this method to define specific behaviours such as denying access and custom
* formating.
* @returns mixed If there exists a column in the table with the same name the value of the
* field is returned.
* Otherwise if the property name is the exact name of a neighboring class, an object or
* a list of objects is returned depending on the direction of the foreign key.
*/
public function __get($name){
if(!is_bool(BasicObject::$output_htmlspecialchars)) {
if(defined('HTML_ACCESS') && is_bool(HTML_ACCESS)) {
BasicObject::$output_htmlspecialchars = HTML_ACCESS;
} else {
throw new Exception("Neither BasicObject::\$output_htmlspecialchars nor HTML_ACCESS is a boolean");
}
}
if($this->in_table($name, $this->table_name())){
if(isset($this->_data) && array_key_exists($name, $this->_data)) {
$ret = $this->_data[$name];
if(BasicObject::$output_htmlspecialchars && is_string($ret)) {
$ret = htmlspecialchars($ret, ENT_QUOTES, 'utf-8');
}
return $ret;
} else {
return null;
}
}
if(class_exists($name) && is_subclass_of($name, 'BasicObject')){
return $this->$name(array());
}
if($name == 'id'){
$name = $this->id_name();
return $this->$name;
}
throw new UndefinedMemberException("unknown property '$name'");
}
protected function is_protected($name) {
return false;
}
/**
* Returns wether a variable in this object is set.
* @param string property name
* @returns bool Returns True if the value exists an is not null, false otherwise.
*/
public function __isset($name) {
if(isset($this->_data[$name])) {
return true;
}
try{
$data = $this->__get($name);
return isset($data);
} catch(Exception $e) {
return false;
}
}
/**
* Set this function to return the name of a column to sort by that if '@order' is not specified
*/
protected static function default_order() {
return null;
}
/**
* Set the value of a field. Use commit() to write to database.
*/
public function __set($name, $value) {
if($this->is_protected($name)){
$trace = debug_backtrace();
if(!isset($trace[1]) || $trace[1]['object'] != $trace[0]['object']) {
throw new Exception("Trying to set protected member '$name' from public scope.");
}
}
if($name == 'id'){
$name = $this->id_name();
$this->$name = $value;
}
if($this->in_table($name, $this->table_name())) {
$pk = $this->id_name();
if($this->_exists && ((is_array($pk) && in_array($name, $pk)) || $pk == $name)) {
$this->_old_key[$name] = $this->$name;
}
$this->_data[$name] = $value;
} elseif($this->is_table($name) && $this->in_table($this->id_name($name), $this->table_name())) {
$name = $this->id_name($name);
$this->$name = $value->id;
} else {
throw new Exception("unknown property '$name'");
}
}
private function get_fresh_instance() {
$id_name = $this->id_name();
if(!is_array($id_name)) {
if(!isset($this->id)) {
throw new Exception("Primary key is not auto increment and is not set.");
}
return $this->from_id($this->id);
}
$params = array();
foreach($id_name as $col) {
$params[$col] = $this->$col;
}
$ret = $this->selection($params);
return array_shift($ret);
}
private static function changed($old, $cur){
if ( $old != $cur ) return true;
if ( $old === null && $cur !== null ) return true;
if ( $old !== null && $cur === null ) return true;
return false;
}
/**
* Commits all fields to database. If this object was created with "new Object()" a new row
* will be created in the table and this object will atempt to update itself with automagic values.
* If the inhereting class wants to do special things on creation, it is best to overload this method
* and do them again.
*/
public function commit() {
global $db;
$id_name = $this->id_name();
if(isset($this->_exists) && $this->_exists){
$query = "UPDATE `".$this->table_name()."` SET\n";
$old_object = $this->get_fresh_instance();
} else {
$query = "INSERT INTO `".$this->table_name()."` SET\n";
}
$types = '';
$params = array(&$types);
$change = false;
foreach($this->_data as $column => $value){
if(!isset($old_object) || static::changed($old_object->_data[$column], $value) ) {
$change = true;
/* handle null values */
if ( $value === null ){
$query .= " `$column` = NULL,\n";
continue;
}
$params[] = &$this->_data[$column];
$query .= " `$column` = ?,\n";
$types .= 's';
}
}
if(!$change) {
/**
* No change to data means no on change hooks in mysql.
*/
return;
}
$query = substr($query, 0, -2);
if(isset($this->_exists) && $this->_exists){
if(is_array($id_name)) {
$query .= "\nWHERE ";
$subquery = '';
foreach($id_name as $field) {
$dummy[$field] = $this->$field;
if(array_key_exists($field, $this->_old_key)) {
$dummy[$field] = $this->_old_key[$field];
}
$subquery .= "`$field` = ? AND ";
$params[] = &$dummy[$field];
$types .= 's';
}
$query .= substr($subquery, 0, -5);
} else {
$query .= "\nWHERE `$id_name` = ?";
$id = $this->id;
$types .= 's';
$params[] = &$id;
}
}
$stmt = $db->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $params);
if(!$stmt->execute()) {
throw new Exception("Internal error, failed to execute query:\n<pre>$query\n".$stmt->error.'</pre>', $stmt->errno);
}
$stmt->close();
if(!isset($this->_exists) || !$this->_exists){
$this->_exists = true;
if($db->insert_id) {
$object = $this->from_id($db->insert_id);
} else {
$object = self::get_fresh_instance();
}
$this->_data = $object->_data;
}
}
/**
* Deletes this object from the database and calls unset on this object.
*/
public function delete() {
global $db;
if(isset($this->_exists) && $this->_exists){
$types='';
$params = array(&$types);
$query = "DELETE FROM ".$this->table_name();
if(is_array($this->id_name())) {
$query .= "\nWHERE ";
$subquery = '';
foreach($this->id_name() as $field) {
$subquery .= "`$field` = ? AND ";
$dummy[$field] = $this->$field;
$params[] = &$dummy[$field];
$types .= 's';
}
$query .= substr($subquery, 0, -5);
} else {
$query .= "\nWHERE `".$this->id_name()."` = ?";
$id = $this->id;
$types .= 'i';
$params[] = &$id;
}
$stmt = $db->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $params);
$stmt->execute();
if($stmt->affected_rows <= 0) {
$msg = "Failed to delete object: \n";
if(strlen($stmt->error)>0) {
$msg.=$stmt->error."\n";
}
throw new Exception($msg, $stmt->errno);
}
$stmt->close();
}
unset($this);
}
/**
* Returns the Object with object_id = $id.
* @param $id Integer The ID of the Object requested.
* @return Object The Object specified by $id.
*/
public static function from_id($id){
$id_name = static::id_name();
return static::from_field($id_name, $id);
}
protected static function from_field($field, $value, $type='s'){
global $db;
$table_name = static::table_name();
if(!self::in_table($field, $table_name)){
throw new Exception("No such column '$field' in table '$table_name'");
}
$stmt = $db->prepare(
"SELECT *\n".
"FROM `".$table_name."`\n".
"WHERE `".$field."` = ?\n".
"LIMIT 1"
);
$stmt->bind_param($type, $value);
$stmt->execute();
$stmt->store_result();
$fields = $stmt->result_metadata();
while($field = $fields->fetch_field()){
$bind_results[$field->name] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $bind_results);
$object = null;
if($stmt->fetch()) {
$object = new static($bind_results, true);
}
$stmt->close();
return $object;
}
public static function sum($field, $params = array()) {
global $db;
$data = static::build_query($params, '*');
$query = array_shift($data);
$allowed_symbols=array('*', '+', '/', '-', );
if(is_array($field)) {
$f = array_shift($field);
if(!self::in_table($f, static::table_name())){
throw new Exception("No such column '$field' in table '".static::table_name()."'");
}
$exp = "`$f`";
while($f = array_shift($field)) {
if(!in_array($f, $allowed_symbols)) {
throw new Exception("Non allowed symbol '$f' in expression");
}
$exp .= " $f ";
if(!($f = array_shift($field))) {
throw new Exception("Mismatched expression");
}
if(!self::in_table($f, static::table_name())){
throw new Exception("No such column '$f' in table '".static::table_name()."'");
}
$exp .= "`$f`";
}
$query = "SELECT SUM($exp) FROM ($query) q";
} else {
if(!self::in_table($field, static::table_name())){
throw new Exception("No such column '$field' in table '".static::table_name()."'");
}
$query = "SELECT SUM(`$field`) FROM ($query) q";
}
$stmt = $db->prepare($query);
foreach($data as $key => $value) {
$data[$key] = &$data[$key];
}
if(count($params)!=0) {
call_user_func_array(array($stmt, 'bind_param'), $data);
}
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
return $result;
}
/**
* Returns the number of items matching the conditions.
* @param $params Array Se selection for structure of $params.
* @returns Int the number of items matching the conditions.
*/
public static function count($params = array(), $debug = false){
global $db;
$data = static::build_query($params, 'count');
$query = array_shift($data);
if($debug) {
echo "<pre>$query</pre>\n";
var_dump($data);
}
$stmt = $db->prepare($query);
foreach($data as $key => $value) {
$data[$key] = &$data[$key];
}
if(count($data)>1) {
call_user_func_array(array($stmt, 'bind_param'), $data);
}
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
return $result;
}
/**
* Returns a list of Objects of this class where the conditions
* specified in $params are true on all objects.
* @param $params Array An array of conditions.
* If $params is empty, all objects will be returned.
* $params is structured as:
* array(
* '<<column>>:<<operator>>' => <<value>>,
* array(
* 'column' => <<column>>,
* 'value' => <<value>>
* ),
* '@manual_query' => <<valid where clause>>,
* [...,]
* // special clauses
* '@or' => array([<params>]),
* '@and' => array([<params>]),
* '@order' => array(<<order-column>> [, <<order-column>> ...]) | <<order-column>>,
* '@limit' => array(<<limit>> [, <<limit>>]),
* )
* @returns Array An array of Objects.
*/
public static function selection($params = array(), $debug=false){
global $db;
$data = self::build_query($params, '*');
$query = array_shift($data);
$stmt = $db->prepare($query);
if(!$stmt) {
throw new Exception("BasicObject: error parcing query: $query\n $db->error");
}
foreach($data as $key => $value) {
$data[$key] = &$data[$key];
}
if(count($data)>1) {
call_user_func_array(array($stmt, 'bind_param'), $data);
}
if($debug) {
echo "<pre>$query</pre>";
var_dump($data);
}
if($stmt->execute() === false) {
throw new Exception("BasicObject: error while executing query: $db->error", $db->errno);
}
if($stmt->store_result() === false) {
throw new Exception("BasicObject: error in store_result: $db->error", $db->errno);
}
$fields = $stmt->result_metadata();
if($fields === false) {
throw new Exception("BasicObject: error while fetching result metadata: $db->error", $db->errno);
}
while($field = $fields->fetch_field()){
$result[$field->name] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $result);
$ret = array();
while($stmt->fetch()){
// fix result so they don't all referencde the same stuff.
$tmp = array();
foreach($result as $key => $value){
$tmp[$key] = $value;
}
$ret[] = new static($tmp, true);
}
$stmt->close();
return $ret;
}
private static function build_query($params, $select){
$table_name = static::table_name();
$id_name = static::id_name();
$joins = array();
$wheres = '';
$order = array();
$user_params = array();
$types = self::handle_params($params, $joins, $wheres, $order, $table_name, $limit, $user_params, 'AND');
if(count($order) == 0 && strpos(strtolower($wheres),'order by') === false) {
// Set default order
if(static::default_order() != null)
$order[] = static::default_order();
}
$query = "SELECT ";
switch($select) {
case '*':
$query .= "`".$table_name."`.*\n";
$group = "\nGROUP BY ".static::unique_identifier();
break;
case 'count':
$query .= "COUNT(DISTINCT(".static::unique_identifier().")) AS `count`\n";
$group = "";
break;
}
$query .=
"FROM\n".
" `".$table_name."`";
foreach($joins as $table => $join){
$query .= " JOIN\n";
if(isset($join['using'])){
$query .= " `".$table."` USING (`".$join['using']."`)";
} else {
$query .= " `".$table."` ON (".$join['on'].")";
}
}
$query .= "\n";
$result = array();
$prepare_full_params = array(&$query, $types); // note the & in &$query making the changes to $query in subsequent lines matter
if(strlen($wheres) > 0){
$wheres = substr($wheres, 0, -5);
$query .= "WHERE\n$wheres";
foreach($user_params as $user_param){
$prepare_full_params[] = $user_param;
}
}
$query .= $group;
if(count($order) > 0){
$query .= "\nORDER BY\n ";
$query .= implode(",\n ", $order);
}
if(isset($limit)){
$query .= "\n$limit";
}
return $prepare_full_params;
}
private static function handle_params($params, &$joins, &$wheres, &$order, &$table_name, &$limit, &$user_params, $glue = 'AND') {
$columns = self::columns($table_name);
$types = '';
foreach($params as $column => $value){
// give a possibility to have multiple params with the same column.
if(is_int($column) && is_array($value) && isset($value['column']) && isset($value['value'])){
$column = $value['column'];
$value = $value['value'];
}
if($column[0] == '@'){
$column = explode(':', $column);
$column = $column[0];
// special parameter
switch($column){
case '@custom_order':
$order[] = $value;
break;
case '@order':
if(!is_array($value)){
$value = array($value);
}
foreach($value as $o){
$desc = false;
if(substr($o,-5) == ':desc'){
$desc = true;
$o = substr($o, 0,-5);
}
$path = explode('.', $o);
if(count($path)>1){
$o = '`'.self::fix_join($path, $joins, $columns, $table_name).'`';
} elseif(self::in_table($o, $table_name)){
$o = "`$table_name`.`$o`";
} else {
throw new Exception("No such column '$o' in table '$table_name' (value '$value')");
}
if($desc){
$o .= ' DESC';
}
$order[] = $o;
}
break;
case '@limit':
if(is_numeric($value)){
$value = array($value);
}
if(!is_array($value) || count($value) > 2){
throw new Exception("Expected array or number for limit clause");
}
foreach($value as $v){
if(!is_numeric($v) && $v>=0){
throw new Exception("Limit must be numeric clauses only");
}
}
$limit = "LIMIT ".$value[0];
if(count($value) == 2){
$limit .= ', '.$value[1];
}
break;
case '@manual_query':
if(is_array($value)){
$wheres .= " ({$value['where']}) $glue\n";
$types .= $value['types'];
$user_params = array_merge($user_params, $value['params']);
} else {
$wheres .= " ($value) $glue\n";
}
break;
case '@or':
$where = '';
$types .= self::handle_params($value, $joins, $where, $order, $table_name, $limit, $user_params, 'OR');
$wheres .= "(\n".substr($where, 0, -4)."\n) $glue\n";
break;
case '@and':
$where = '';
$types .= self::handle_params($value, $joins, $where, $order, $table_name, $limit, $user_params, 'AND');
$wheres .= "(\n".substr($where, 0, -5)."\n) $glue\n";
break;
default:
throw new Exception("No such operator '".substr($column,1)."' (value '$value')");
}
} else {
$where=array();
// handle operator
$column = explode(':', $column);
if(count($column) > 1) {
// Has operator
$where['operator'] = self::operator($column[1]);
} else {
// default operator
$where['operator'] = '=';
}
$column = $column[0];
$function=NULL;
//Handle functions:
if(preg_match("/(.*)\((.*)\)/",$column, $matches)) {
$function = $matches[1];
$column = $matches[2];
}
// handle column
$path = explode('.', $column);
if(count($path)>1){
$where['column'] = '`'.self::fix_join($path, $joins, $columns, $table_name).'`';
} else {
if(!self::in_table($column, $table_name)){
throw new Exception("No such column '$column' in table '$table_name' (value '$value')");
}
$where['column'] = '`'.$table_name.'`.`'.$column.'`';
}
if($function) {
$where['column'] = "$function({$where['column']})";
}
if($where['operator'] == 'in') {
$wheres .= " {$where['column']} IN (";
if(!is_array($value)){
throw new Exception("Operator 'in' should be coupled with an array of values.");
}
foreach($value as $v){
$types .= 's';
$wheres .= '?, ';
$user_params[] = $v;
}
$wheres = substr($wheres, 0, -2);
$wheres .= ") $glue\n";
} elseif($where['operator'] == 'null') {
$wheres .= " ".$where["column"]." IS NULL $glue\n";
} elseif($where['operator'] == 'not_null') {
$wheres .= " ".$where["column"]." IS NOT NULL $glue\n";
} else {
$user_params[] = $value;
$wheres .= " ".$where["column"]." ".$where['operator']." ? ".$glue."\n";
$types.='s';
}
}
}
return $types;
}
/**
* Update or create an object from an array (often postdata)
* By default this method performs commit() on the object before it is returned, but that
* can be turned of (see @param $options)
*
* @param $array An assoc array (for example from postdata) with $field_name=>$value.
* If ["id"] or [id_name] is set the model is marked as existing,
* otherwise it is treated as a new object.
*
* Note: To use this method with checkboxes a hidden field with the same name and value
* 0 must exist, otherwise the value will not be changed. This is because the function is
* build to allow partial updates of a model and loads any missing data from the database.
*
* @param $options An array with options
* empty_to_null: Set to true to replace all instances of "" with null. (default true)
* commit: Set to false to not perform commit() (default false)
*/
public static function update_attributes($array, $options=array()) {
$defaults = array(
'empty_to_null' => true,
'commit' => false,
);
$options = array_merge($defaults, $options);
if(isset($options["empty_to_null"]) && $options["empty_to_null"] == true) {
foreach($array as $k => $v) {
if($v == "")
$array[$k] = null;
}
}
$obj = new static($array);
//Change [id] to [id_name] if [id] is set but id_name()!='id'
if($obj->id_name() != "id"
&& isset($obj->_data['id'])
&& !is_null($obj->_data['id'])
&& !empty($obj->_data['id'])
&& !isset($obj->_data[$obj->id_name()])) {
$obj->_data[$obj->id_name()] = $obj->_data['id'];
unset($obj->_data['id']);
} else if($obj->id_name() != "id") {
//Prevent errors where the id field has another name and ['id'] is null
unset($obj->_data['id']);
}
$id = $obj->id;
if($id!=null && $id!="") {
$old_obj = static::from_id($id);
$obj->_data = array_merge($old_obj->_data,$obj->_data);
$obj->_exists = true; //Mark as existing
}
if(!isset($options["commit"]) || $options["commit"] == true) {
$obj->commit();
}
return $obj;
}
private static function columns($table){
global $db;
static $columns = array();
if(!isset($columns[$table])){
if(!self::is_table($table)){
throw new Exception("No such table '$table'");
}
$column[$table] = array();
$stmt = $db->prepare(
"SELECT `COLUMN_NAME`\n".
"FROM `information_schema`.`COLUMNS`\n".
"WHERE\n".
" `TABLE_SCHEMA` = ? AND\n".
" `table_name` = ?"
);
$db_name = self::get_database_name();
$stmt->bind_param('ss', $db_name, $table);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column);
while($stmt->fetch()){
$columns[$table][] = $column;
}
$stmt->close();
}
return $columns[$table];
}
private static function operator($expr){
switch($expr){
case "=":
case "!=":
case "<=":
case ">=":
case "<":
case ">":
case "regexp":
case "like":
case "in":
case "null":
case "not_null":
return $expr;
default:
throw new Exception("No such operator '$expr'");
}
}
private static function is_table($table){
global $db;
static $tables;
if(!isset($tables)){
$db_name = static::get_database_name();
$stmt = $db->prepare("
SELECT `table_name`
FROM `information_schema`.`tables`
WHERE `table_schema` = ?
");
$stmt->bind_param('s', $db_name);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($table_);
while($stmt->fetch()){
$tables[] = strtolower($table_);
}
$stmt->close();
}
return in_array(strtolower($table), $tables);
}
private static function fix_join($path, &$joins, $parent_columns, $parent){
$first = array_shift($path);
if(class_exists($first) && is_subclass_of($first, 'BasicObject')){
$first = $first::table_name();
}
if(!self::is_table($first)){
throw new Exception("No such table '$first'");
}
$connection = self::connection($first, $parent);
$columns = self::columns($first);
if($connection){
$joins[$first] = array(
'to' => $parent,
'on' => "`{$connection['TABLE_NAME']}`.`{$connection['COLUMN_NAME']}` = `{$connection['REFERENCED_TABLE_NAME']}`.`{$connection['REFERENCED_COLUMN_NAME']}`"
);
} else {
$parent_id = self::id_name($parent);
$first_id = self::id_name($first);
if(in_array($first_id, $parent_columns)){
$joins[$first] = array(
"to" => $parent,
"on" => "`$parent`.`$first_id` = `$first`.`$first_id`");
} elseif(in_array($parent_id, $columns)) {
$joins[$first] = array(
"to" => $parent,
"on" => "`$parent`.`$parent_id` = `$first`.`$parent_id`");
} else {
throw new Exception("No connection from '$parent' to table '$first'");
}
}
if(count($path) == 1) {
$key = array_shift($path);
if(!in_array($key, $columns)){
throw new Exception("No such column '$key' in table '$first'");
}
return $first.'`.`'.$key;
} else {
return self::fix_join($path, $joins, $columns, $first);
}
}
private static function in_table($column, $table){
static $tables = array();
if(!isset($tables[$table])){
$tables[$table] = self::columns($table);
}
return in_array($column, $tables[$table]);
}
/**
* Return only the first match of the given query
* Takes the same options as selection
*/
public static function first($params = array()) {
$params['@limit']=1;
$sel = static::selection($params);
if(isset($sel[0])) {
return $sel[0];
} else {
return null;
}
}
/**
* Returns the only object that matches the given query
* If there is more than one match an exception is thrown
*/
public static function one($params = array()) {
$sel = static::selection($params);
if(count($sel) <= 1) {
return isset($sel[0]) ? $sel[0] : null;
} else {
throw new Exception("Expected at most one match for query ".print_r($params, true)." but got ".count($sel));
}
}
private static function connection($table1, $table2) {
global $db;
static $data;
if(strcmp($table1, $table2) < 0){
$tmp = $table1;
$table1 = $table2;
$table2 = $tmp;
}
if(!isset($data[$table1]) || !isset($data[$table1][$table2])){
$data[$table1][$table2] = array();
$stmt = $db->prepare("
SELECT
`key_column_usage`.`TABLE_NAME`,
`COLUMN_NAME`,