-
Notifications
You must be signed in to change notification settings - Fork 54
/
xpdoobject.class.php
2567 lines (2484 loc) · 113 KB
/
xpdoobject.class.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
/*
* Copyright 2010-2015 by MODX, LLC.
*
* This file is part of xPDO.
*
* xPDO is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*/
/**
* The base persistent xPDO object classes.
*
* This file contains the base persistent object classes, which your user-
* defined classes will extend when implementing an xPDO object model.
*
* @package xpdo
* @subpackage om
*/
/**
* The base persistent xPDO object class.
*
* This is the basis for the entire xPDO object model, and can also be used by a
* class generator {@link xPDOGenerator}, ultimately allowing custom classes to
* be user-defined in a web interface and framework-generated at runtime.
*
* @abstract This is an abstract class, and is not represented by an actual
* table; it simply defines the member variables and functions needed for object
* persistence.
*
* @package xpdo
* @subpackage om
*/
class xPDOObject {
/**
* A convenience reference to the xPDO object.
* @var xPDO
* @access public
*/
public $xpdo= null;
/**
* Name of the data source container the object belongs to.
* @var string
* @access public
*/
public $container= null;
/**
* Names of the fields in the data table, fully-qualified with a table name.
*
* NOTE: For use in table joins to qualify fields with the same name.
*
* @var array
* @access public
*/
public $fieldNames= null;
/**
* The actual class name of an instance.
* @var string
*/
public $_class= null;
/**
* The package the class is a part of.
* @var string
*/
public $_package= null;
/**
* An alias for this instance of the class.
* @var string
*/
public $_alias= null;
/**
* The primary key field (or an array of primary key fields) for this object.
* @var string|array
* @access public
*/
public $_pk= null;
/**
* The php native type of the primary key field.
*
* NOTE: Will be an array if multiple primary keys are specified for the object.
*
* @var string|array
* @access public
*/
public $_pktype= null;
/**
* Name of the actual table representing this class.
* @var string
* @access public
*/
public $_table= null;
/**
* An array of meta data for the table.
* @var string
* @access public
*/
public $_tableMeta= null;
/**
* An array of field names that have been modified.
* @var array
* @access public
*/
public $_dirty= array ();
/**
* An array of field names that have not been loaded from the source.
* @var array
* @access public
*/
public $_lazy= array ();
/**
* An array of key-value pairs representing the fields of the instance.
* @var array
* @access public
*/
public $_fields= array ();
/**
* An array of metadata definitions for each field in the class.
* @var array
* @access public
*/
public $_fieldMeta= array ();
/**
* An optional array of field aliases.
* @var array
*/
public $_fieldAliases= array();
/**
* An array of aggregate foreign key relationships for the class.
* @var array
* @access public
*/
public $_aggregates= array ();
/**
* An array of composite foreign key relationships for the class.
* @var array
* @access public
*/
public $_composites= array ();
/**
* An array of object instances related to this object instance.
* @var array
* @access public
*/
public $_relatedObjects= array ();
/**
* A validator object responsible for this object instance.
* @var xPDOValidator
* @access public
*/
public $_validator = null;
/**
* An array of validation rules for this object instance.
* @var array
* @access public
*/
public $_validationRules = array();
/**
* An array of field names that have been already validated.
* @var array
* @access public
*/
public $_validated= array ();
/**
* Indicates if the validation map has been loaded.
* @var boolean
* @access public
*/
public $_validationLoaded= false;
/**
* Indicates if the instance is transient (and thus new).
* @var boolean
* @access public
*/
public $_new= true;
/**
* Indicates the cacheability of the instance.
* @var boolean
*/
public $_cacheFlag= true;
/**
* A collection of various options that can be used on the instance.
* @var array
*/
public $_options= array();
/**
* Responsible for loading a result set from the database.
*
* @static
* @param xPDO &$xpdo A valid xPDO instance.
* @param string $className Name of the class.
* @param xPDOCriteria $criteria A valid xPDOCriteria instance.
* @return PDOStatement A reference to a PDOStatement representing the
* result set.
*/
public static function & _loadRows(& $xpdo, $className, $criteria) {
$rows= null;
if ($criteria->prepare()) {
if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Attempting to execute query using PDO statement object: " . print_r($criteria->sql, true) . print_r($criteria->bindings, true));
$tstart= microtime(true);
if (!$criteria->stmt->execute()) {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
$errorInfo= $criteria->stmt->errorInfo();
$xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Error ' . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($errorInfo, true));
if (($errorInfo[1] == '1146' || $errorInfo[1] == '1') && $xpdo->getOption(xPDO::OPT_AUTO_CREATE_TABLES)) {
if ($xpdo->getManager() && $xpdo->manager->createObjectContainer($className)) {
$tstart= microtime(true);
if (!$criteria->stmt->execute()) {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($criteria->stmt->errorInfo(), true));
} else {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
}
} else {
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $xpdo->errorCode() . " attempting to create object container for class {$className}:\n" . print_r($xpdo->errorInfo(), true));
}
}
} else {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
}
$rows= & $criteria->stmt;
} else {
$errorInfo = $xpdo->errorInfo();
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error preparing statement for query: {$criteria->sql} - " . print_r($errorInfo, true));
if (($errorInfo[1] == '1146' || $errorInfo[1] == '1') && $xpdo->getOption(xPDO::OPT_AUTO_CREATE_TABLES)) {
if ($xpdo->getManager() && $xpdo->manager->createObjectContainer($className)) {
if (!$criteria->prepare()) {
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error preparing statement for query: {$criteria->sql} - " . print_r($errorInfo, true));
} else {
$tstart= microtime(true);
if (!$criteria->stmt->execute()) {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($criteria->stmt->errorInfo(), true));
} else {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
}
}
} else {
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $xpdo->errorCode() . " attempting to create object container for class {$className}:\n" . print_r($xpdo->errorInfo(), true));
}
}
}
return $rows;
}
/**
* Loads an instance from an associative array.
*
* @static
* @param xPDO &$xpdo A valid xPDO instance.
* @param string $className Name of the class.
* @param xPDOQuery|string $criteria A valid xPDOQuery instance or relation alias.
* @param array $row The associative array containing the instance data.
* @return xPDOObject A new xPDOObject derivative representing a data row.
*/
public static function _loadInstance(& $xpdo, $className, $criteria, $row) {
$rowPrefix= '';
if (is_object($criteria) && $criteria instanceof xPDOQuery) {
$alias = $criteria->getAlias();
$actualClass = $criteria->getClass();
} elseif (is_string($criteria) && !empty($criteria)) {
$alias = $criteria;
$actualClass = $className;
} else {
$alias = $className;
$actualClass= $className;
}
if (isset ($row["{$alias}_class_key"])) {
$actualClass= $row["{$alias}_class_key"];
$rowPrefix= $alias . '_';
} elseif (isset($row["{$className}_class_key"])) {
$actualClass= $row["{$className}_class_key"];
$rowPrefix= $className . '_';
} elseif (isset ($row['class_key'])) {
$actualClass= $row['class_key'];
}
/** @var xPDOObject $instance */
$instance= $xpdo->newObject($actualClass);
if (is_object($instance) && $instance instanceof xPDOObject) {
$pk = $xpdo->getPK($actualClass);
if ($pk) {
if (is_array($pk)) $pk = reset($pk);
if (isset($row["{$alias}_{$pk}"])) {
$rowPrefix= $alias . '_';
}
elseif ($actualClass !== $className && $actualClass !== $alias && isset($row["{$actualClass}_{$pk}"])) {
$rowPrefix= $actualClass . '_';
}
elseif ($className !== $alias && isset($row["{$className}_{$pk}"])) {
$rowPrefix= $className . '_';
}
} elseif (strpos(strtolower(key($row)), strtolower($alias . '_')) === 0) {
$rowPrefix= $alias . '_';
} elseif (strpos(strtolower(key($row)), strtolower($className . '_')) === 0) {
$rowPrefix= $className . '_';
}
$parentClass = $className;
$isSubPackage = strpos($className,'.');
if ($isSubPackage !== false) {
$parentClass = substr($className,$isSubPackage+1);
}
if (!$instance instanceof $parentClass) {
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Instantiated a derived class {$actualClass} that is not a subclass of the requested class {$className}");
}
$instance->_lazy= $actualClass !== $className ? array_keys($xpdo->getFieldMeta($actualClass)) : array_keys($instance->_fieldMeta);
$instance->fromArray($row, $rowPrefix, true, true);
$instance->_dirty= array ();
$instance->_new= false;
}
return $instance;
}
/**
* Responsible for loading an instance into a collection.
*
* @static
* @param xPDO &$xpdo A valid xPDO instance.
* @param array &$objCollection The collection to load the instance into.
* @param string $className Name of the class.
* @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
* @param array $row The associative array containing the instance data.
* @param bool $fromCache If the instance is for the cache
* @param bool|int $cacheFlag Indicates if the objects should be cached and
* optionally, by specifying an integer value, for how many seconds.
* @return bool True if a valid instance was loaded, false otherwise.
*/
public static function _loadCollectionInstance(xPDO & $xpdo, array & $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag=true) {
$loaded = false;
if ($obj= xPDOObject :: _loadInstance($xpdo, $className, $criteria, $row)) {
if (($cacheKey= $obj->getPrimaryKey()) && !$obj->isLazy()) {
if (is_array($cacheKey)) {
$pkval= implode('-', $cacheKey);
} else {
$pkval= $cacheKey;
}
/* set OPT_CACHE_DB_COLLECTIONS to 2 to cache instances by primary key from collection result sets */
if ($xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1) == 2 && $xpdo->_cacheEnabled && $cacheFlag) {
if (!$fromCache) {
$pkCriteria = $xpdo->newQuery($className, $cacheKey, $cacheFlag);
$xpdo->toCache($pkCriteria, $obj, $cacheFlag);
} else {
$obj->_cacheFlag= true;
}
}
$objCollection[$pkval]= $obj;
$loaded = true;
} else {
$objCollection[]= $obj;
$loaded = true;
}
}
return $loaded;
}
/**
* Load an instance of an xPDOObject or derivative class.
*
* @static
* @param xPDO &$xpdo A valid xPDO instance.
* @param string $className Name of the class.
* @param mixed $criteria A valid primary key, criteria array, or
* xPDOCriteria instance.
* @param boolean|integer $cacheFlag Indicates if the objects should be
* cached and optionally, by specifying an integer value, for how many
* seconds.
* @return object|null An instance of the requested class, or null if it
* could not be instantiated.
*/
public static function load(xPDO & $xpdo, $className, $criteria, $cacheFlag= true) {
$instance= null;
$fromCache= false;
if ($className= $xpdo->loadClass($className)) {
if (!is_object($criteria)) {
$criteria = $xpdo->getCriteria($className, $criteria, $cacheFlag);
}
if (is_object($criteria)) {
$criteria = $xpdo->addDerivativeCriteria($className, $criteria);
$row= null;
if ($xpdo->_cacheEnabled && $criteria->cacheFlag && $cacheFlag) {
$row= $xpdo->fromCache($criteria, $className);
}
if ($row === null || !is_array($row)) {
if ($rows= xPDOObject :: _loadRows($xpdo, $className, $criteria)) {
$row= $rows->fetch(PDO::FETCH_ASSOC);
$rows->closeCursor();
}
} else {
$fromCache= true;
}
if (!is_array($row)) {
if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Fetched empty result set from statement: " . print_r($criteria->sql, true) . " with bindings: " . print_r($criteria->bindings, true));
} else {
$instance= xPDOObject :: _loadInstance($xpdo, $className, $criteria, $row);
if (is_object($instance)) {
if (!$fromCache && $cacheFlag && $xpdo->_cacheEnabled) {
$xpdo->toCache($criteria, $instance, $cacheFlag);
if ($xpdo->getOption(xPDO::OPT_CACHE_DB_OBJECTS_BY_PK) && ($cacheKey= $instance->getPrimaryKey()) && !$instance->isLazy()) {
$pkCriteria = $xpdo->newQuery($className, $cacheKey, $cacheFlag);
$xpdo->toCache($pkCriteria, $instance, $cacheFlag);
}
}
if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Loaded object instance: " . print_r($instance->toArray('', true), true));
}
}
} else {
$xpdo->log(xPDO::LOG_LEVEL_ERROR, 'No valid statement could be found in or generated from the given criteria.');
}
} else {
$xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Invalid class specified: ' . $className);
}
return $instance;
}
/**
* Load a collection of xPDOObject instances.
*
* @static
* @param xPDO &$xpdo A valid xPDO instance.
* @param string $className Name of the class.
* @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
* @param boolean|integer $cacheFlag Indicates if the objects should be
* cached and optionally, by specifying an integer value, for how many
* seconds.
* @return array An array of xPDOObject instances or an empty array if no instances are loaded.
*/
public static function loadCollection(xPDO & $xpdo, $className, $criteria= null, $cacheFlag= true) {
$objCollection= array ();
$fromCache = false;
if (!$className= $xpdo->loadClass($className)) return $objCollection;
$rows= false;
$fromCache= false;
$collectionCaching = (integer) $xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1);
if (!is_object($criteria)) {
$criteria= $xpdo->getCriteria($className, $criteria, $cacheFlag);
}
if (is_object($criteria)) {
$criteria = $xpdo->addDerivativeCriteria($className, $criteria);
}
if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag) {
$rows= $xpdo->fromCache($criteria);
$fromCache = (is_array($rows) && !empty($rows));
}
if (!$fromCache && is_object($criteria)) {
$rows= xPDOObject :: _loadRows($xpdo, $className, $criteria);
}
if (is_array ($rows)) {
foreach ($rows as $row) {
xPDOObject :: _loadCollectionInstance($xpdo, $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag);
}
} elseif (is_object($rows)) {
$cacheRows = array();
while ($row = $rows->fetch(PDO::FETCH_ASSOC)) {
xPDOObject :: _loadCollectionInstance($xpdo, $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag);
if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag && !$fromCache) $cacheRows[] = $row;
}
if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag && !$fromCache) $rows =& $cacheRows;
}
if (!$fromCache && $xpdo->_cacheEnabled && $collectionCaching > 0 && $cacheFlag && !empty($rows)) {
$xpdo->toCache($criteria, $rows, $cacheFlag);
}
return $objCollection;
}
/**
* Load a collection of xPDOObject instances and a graph of related objects.
*
* @static
* @param xPDO &$xpdo A valid xPDO instance.
* @param string $className Name of the class.
* @param string|array $graph A related object graph in array or JSON
* format, e.g. array('relationAlias'=>array('subRelationAlias'=>array()))
* or {"relationAlias":{"subRelationAlias":{}}}. Note that the empty arrays
* are necessary in order for the relation to be recognized.
* @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
* @param boolean|integer $cacheFlag Indicates if the objects should be
* cached and optionally, by specifying an integer value, for how many
* seconds.
* @return array An array of xPDOObject instances or an empty array if no instances are loaded.
*/
public static function loadCollectionGraph(xPDO & $xpdo, $className, $graph, $criteria, $cacheFlag) {
$objCollection = array();
if ($query= $xpdo->newQuery($className, $criteria, $cacheFlag)) {
$query = $xpdo->addDerivativeCriteria($className, $query);
$query->bindGraph($graph);
$rows = array();
$fromCache = false;
$collectionCaching = (integer) $xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1);
if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag) {
$rows= $xpdo->fromCache($query);
$fromCache = !empty($rows);
}
if (!$fromCache) {
if ($query->prepare()) {
$tstart = microtime(true);
if ($query->stmt->execute()) {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
$objCollection= $query->hydrateGraph($query->stmt, $cacheFlag);
} else {
$xpdo->queryTime += microtime(true) - $tstart;
$xpdo->executedQueries++;
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error {$query->stmt->errorCode()} executing query: {$query->sql} - " . print_r($query->stmt->errorInfo(), true));
}
} else {
$xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error {$xpdo->errorCode()} preparing statement: {$query->sql} - " . print_r($xpdo->errorInfo(), true));
}
} elseif (!empty($rows)) {
$objCollection= $query->hydrateGraph($rows, $cacheFlag);
}
}
return $objCollection;
}
/**
* Get a set of column names from an xPDOObject for use in SQL queries.
*
* @static
* @param xPDO &$xpdo A reference to an initialized xPDO instance.
* @param string $className The class name to get columns from.
* @param string $tableAlias An optional alias for the table in the query.
* @param string $columnPrefix An optional prefix to prepend to each column name.
* @param array $columns An optional array of field names to include or exclude
* (include is default behavior).
* @param boolean $exclude Determines if any specified columns should be included
* or excluded from the set of results.
* @return string A comma-delimited list of the field names for use in a SELECT clause.
*/
public static function getSelectColumns(xPDO & $xpdo, $className, $tableAlias= '', $columnPrefix= '', $columns= array (), $exclude= false) {
$columnarray= array ();
$aColumns= $xpdo->getFields($className);
if ($aColumns) {
if (!empty ($tableAlias)) {
$tableAlias= $xpdo->escape($tableAlias);
$tableAlias.= '.';
}
if (!$exclude && !empty($columns)) {
foreach ($columns as $column) {
if (!in_array($column, array_keys($aColumns))) {
continue;
}
$columnarray[$column]= "{$tableAlias}" . $xpdo->escape($column);
if (!empty ($columnPrefix)) {
$columnarray[$column]= $columnarray[$column] . " AS " . $xpdo->escape("{$columnPrefix}{$column}");
}
}
} else {
foreach (array_keys($aColumns) as $k) {
if ($exclude && in_array($k, $columns)) {
continue;
}
elseif (empty ($columns)) {
$columnarray[$k]= "{$tableAlias}" . $xpdo->escape($k);
}
elseif ($exclude || in_array($k, $columns)) {
$columnarray[$k]= "{$tableAlias}" . $xpdo->escape($k);
} else {
continue;
}
if (!empty ($columnPrefix)) {
$columnarray[$k]= $columnarray[$k] . " AS " . $xpdo->escape("{$columnPrefix}{$k}");
}
}
}
}
return implode(', ', $columnarray);
}
/**
* Constructor
*
* Do not call the constructor directly; see {@link xPDO::newObject()}.
*
* All derivatives of xPDOObject must redeclare this method, and must call
* the parent method explicitly before any additional logic is executed, e.g.
*
* <code>
* public function __construct(xPDO & $xpdo) {
* parent :: __construct($xpdo);
* // Any additional constructor tasks here
* }
* </code>
*
* @access public
* @param xPDO &$xpdo A reference to a valid xPDO instance.
* @return xPDOObject
*/
public function __construct(xPDO & $xpdo) {
$this->xpdo= & $xpdo;
$this->container= $xpdo->config['dbname'];
$this->_class= get_class($this);
$pos= strrpos($this->_class, '_');
if ($pos !== false && substr($this->_class, $pos + 1) == $xpdo->config['dbtype']) {
$this->_class= substr($this->_class, 0, $pos);
}
$this->_package= $xpdo->getPackage($this->_class);
$this->_alias= $this->_class;
$this->_table= $xpdo->getTableName($this->_class);
$this->_tableMeta= $xpdo->getTableMeta($this->_class);
$this->_fields= $xpdo->getFields($this->_class);
$this->_fieldMeta= $xpdo->getFieldMeta($this->_class);
$this->_fieldAliases= $xpdo->getFieldAliases($this->_class);
$this->_aggregates= $xpdo->getAggregates($this->_class);
$this->_composites= $xpdo->getComposites($this->_class);
if ($relatedObjs= array_merge($this->_aggregates, $this->_composites)) {
foreach ($relatedObjs as $aAlias => $aMeta) {
if (!array_key_exists($aAlias, $this->_relatedObjects)) {
if ($aMeta['cardinality'] == 'many') {
$this->_relatedObjects[$aAlias]= array ();
}
else {
$this->_relatedObjects[$aAlias]= null;
}
}
}
}
foreach ($this->_fieldAliases as $fieldAlias => $field) {
$this->addFieldAlias($field, $fieldAlias);
}
$this->setDirty();
}
/**
* Add an alias as a reference to an actual field of the object.
*
* @param string $field The field name to create a reference to.
* @param string $alias The name of the reference.
* @return bool True if the reference is added successfully.
*/
public function addFieldAlias($field, $alias) {
$added = false;
if (array_key_exists($field, $this->_fields)) {
if (!array_key_exists($alias, $this->_fields)) {
$this->_fields[$alias] =& $this->_fields[$field];
if (!array_key_exists($alias, $this->_fieldAliases)) {
$this->_fieldAliases[$alias] = $field;
if (!array_key_exists($alias, $this->xpdo->map[$this->_class]['fieldAliases'])) {
$this->xpdo->map[$this->_class]['fieldAliases'][$alias]= $field;
}
}
$added = true;
} else {
$this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "The alias {$alias} is already in use as a field name in objects of class {$this->_class}", '', __METHOD__, __FILE__, __LINE__);
}
}
return $added;
}
/**
* Get an option value for this instance.
*
* @param string $key The option key to retrieve a value for.
* @param array|null $options An optional array to search for a value in first.
* @param mixed $default A default value to return if no value is found; null is the default.
* @return mixed The value of the option or the provided default if it is not set.
*/
public function getOption($key, $options = null, $default = null) {
if (is_array($options) && array_key_exists($key, $options)) {
$value= $options[$key];
} elseif (array_key_exists($key, $this->_options)) {
$value= $this->_options[$key];
} else {
$value= $this->xpdo->getOption($key, null, $default);
}
return $value;
}
/**
* Set an option value for this instance.
*
* @param string $key The option key to set a value for.
* @param mixed $value A value to assign to the option.
*/
public function setOption($key, $value) {
$this->_options[$key]= $value;
}
public function __get($name) {
if ($this->getOption(xPDO::OPT_HYDRATE_FIELDS) && array_key_exists($name, $this->_fields)) {
return $this->_fields[$name];
} elseif ($this->getOption(xPDO::OPT_HYDRATE_RELATED_OBJECTS)) {
if (array_key_exists($name, $this->_composites)) {
$fkMeta = $this->_composites[$name];
} elseif (array_key_exists($name, $this->_aggregates)) {
$fkMeta = $this->_aggregates[$name];
} else {
return null;
}
} else {
return null;
}
if ($fkMeta['cardinality'] === 'many') {
return $this->getMany($name);
} else {
return $this->getOne($name);
}
}
public function __set($name, $value) {
if ($this->getOption(xPDO::OPT_HYDRATE_FIELDS) && array_key_exists($name, $this->_fields)) {
return $this->_setRaw($name, $value);
} elseif ($this->getOption(xPDO::OPT_HYDRATE_RELATED_OBJECTS)) {
if (array_key_exists($name, $this->_composites)) {
$fkMeta = $this->_composites[$name];
} elseif (array_key_exists($name, $this->_aggregates)) {
$fkMeta = $this->_aggregates[$name];
} else {
return false;
}
} else {
return false;
}
if ($fkMeta['cardinality'] === 'many') {
return $this->addMany($value, $name);
} else {
return $this->addOne($value, $name);
}
}
public function __isset($name) {
return ($this->getOption(xPDO::OPT_HYDRATE_FIELDS) && array_key_exists($name, $this->_fields) && isset($this->_fields[$name]))
|| ($this->getOption(xPDO::OPT_HYDRATE_RELATED_OBJECTS)
&& ((array_key_exists($name, $this->_composites) && isset($this->_composites[$name]))
|| (array_key_exists($name, $this->_aggregates) && isset($this->_aggregates[$name]))));
}
/**
* Set a field value by the field key or name.
*
* @todo Define and implement field validation.
*
* @param string $k The field key or name.
* @param mixed $v The value to set the field to.
* @param string|callable $vType A string indicating the format of the
* provided value parameter, or a callable function that should be used to
* set the field value, overriding the default behavior.
* @return boolean Determines whether the value was set successfully and was
* determined to be dirty (i.e. different from the previous value).
*/
public function set($k, $v= null, $vType= '') {
$set= false;
$callback= '';
$callable= !empty($vType) && is_callable($vType, false, $callback) ? true : false;
if (!$callable && isset($this->_fieldMeta[$k]['callback'])) {
$callable = is_callable($this->_fieldMeta[$k]['callback'], false, $callback);
}
$oldValue= null;
$k = $this->getField($k);
if (is_string($k) && !empty($k)) {
if (array_key_exists($k, $this->_fieldMeta)) {
$oldValue= $this->_fields[$k];
if (isset($this->_fieldMeta[$k]['generated']) && !$this->_fieldMeta[$k]['generated'] === 'callback') {
return false;
}
if ($callable && $callback) {
$set = call_user_func_array($callback, array($k, $v, $this));
} else {
if (is_string($v) && $this->getOption(xPDO::OPT_ON_SET_STRIPSLASHES)) {
$v= stripslashes($v);
}
if ($oldValue !== $v) {
//type validation
$phptype= $this->_fieldMeta[$k]['phptype'];
$dbtype= $this->_fieldMeta[$k]['dbtype'];
$allowNull= isset($this->_fieldMeta[$k]['null']) ? (boolean) $this->_fieldMeta[$k]['null'] : true;
if ($v === null) {
if ($allowNull) {
$this->_fields[$k]= null;
$set= true;
} else {
$this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "{$this->_class}: Attempt to set NOT NULL field {$k} to NULL");
}
}
else {
switch ($phptype) {
case 'timestamp' :
case 'datetime' :
$ts= false;
if (preg_match('/int/i', $dbtype)) {
if (strtolower($vType) == 'integer' || is_int($v) || $v == '0') {
$ts= (integer) $v;
} else {
$ts= strtotime($v);
}
if ($ts === false) {
$ts= 0;
}
$this->_fields[$k]= $ts;
$set= true;
} else {
if ($vType == 'utc' || in_array($v, $this->xpdo->driver->_currentTimestamps) || $v === '0000-00-00 00:00:00') {
$this->_fields[$k]= (string) $v;
$set= true;
} else {
if (strtolower($vType) == 'integer' || is_int($v)) {
$ts= intval($v);
} elseif (is_string($v) && !empty($v)) {
$ts= strtotime($v);
}
if ($ts !== false) {
$this->_fields[$k]= strftime('%Y-%m-%d %H:%M:%S', $ts);
$set= true;
}
}
}
break;
case 'date' :
if (preg_match('/int/i', $dbtype)) {
if (strtolower($vType) == 'integer' || is_int($v) || $v == '0') {
$ts= (integer) $v;
} else {
$ts= strtotime($v);
}
if ($ts === false) {
$ts= 0;
}
$this->_fields[$k]= $ts;
$set= true;
} else {
if ($vType == 'utc' || in_array($v, $this->xpdo->driver->_currentDates) || $v === '0000-00-00') {
$this->_fields[$k]= $v;
$set= true;
} else {
if (strtolower($vType) == 'integer' || is_int($v)) {
$ts= intval($v);
} elseif (is_string($v) && !empty($v)) {
$ts= strtotime($v);
}
$ts= strtotime($v);
if ($ts !== false) {
$this->_fields[$k]= strftime('%Y-%m-%d', $ts);
$set= true;
}
}
}
break;
case 'boolean' :
$this->_fields[$k]= intval($v);
$set= true;
break;
case 'integer' :
$this->_fields[$k]= intval($v);
$set= true;
break;
case 'array' :
if (is_object($v) && $v instanceof xPDOObject) {
$v = $v->toArray();
}
if (is_array($v)) {
$this->_fields[$k]= serialize($v);
$set= true;
}
break;
case 'json' :
if (is_object($v) && $v instanceof xPDOObject) {
$v = $v->toArray();
}
if (is_string($v)) {
$v= $this->xpdo->fromJSON($v, true);
}
if (is_array($v)) {
$this->_fields[$k]= $this->xpdo->toJSON($v);
$set= true;
}
break;
default :
$this->_fields[$k]= $v;
$set= true;
}
}
}
}
} elseif ($this->getOption(xPDO::OPT_HYDRATE_ADHOC_FIELDS)) {
$oldValue= isset($this->_fields[$k]) ? $this->_fields[$k] : null;
if ($callable) {
$set = call_user_func_array($callback, array($k, $v, $this));
} else {
$this->_fields[$k]= $v;
$set= true;
}
}
if ($set && $oldValue !== $this->_fields[$k]) {
$this->setDirty($k);
} else {
$set= false;
}
} else {
$this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'xPDOObject - Called set() with an invalid field name: ' . print_r($k, 1));
}
return $set;
}
/**
* Get a field value (or a set of values) by the field key(s) or name(s).
*
* Warning: do not use the $format parameter if retrieving multiple values of
* different types, as the format string will be applied to all types, most
* likely with unpredictable results. Optionally, you can supply an associate
* array of format strings with the field key as the key for the format array.
*
* @param string|array $k A string (or an array of strings) representing the field
* key or name.
* @param string|array $format An optional variable (or an array of variables) to
* format the return value(s).
* @param mixed $formatTemplate An additional optional variable that can be used in
* formatting the return value(s).
* @return mixed The value(s) of the field(s) requested.
*/
public function get($k, $format = null, $formatTemplate= null) {
$value= null;
if (is_array($k)) {
$lazy = array_intersect($k, $this->_lazy);
if ($lazy) {
$this->_loadFieldData($lazy);
}
foreach ($k as $key) {
if (array_key_exists($key, $this->_fields)) {
if (is_array($format) && isset ($format[$key])) {
$formatTpl= null;
if (is_array ($formatTemplate) && isset ($formatTemplate[$key])) {
$formatTpl= $formatTemplate[$key];
}
$value[$key]= $this->get($key, $format[$key], $formatTpl);
} elseif (!empty ($format) && is_string($format)) {
$value[$key]= $this->get($key, $format, $formatTemplate);
} else {
$value[$key]= $this->get($key);
}
}
}
} elseif (is_string($k) && !empty($k)) {
if (array_key_exists($k, $this->_fields)) {
if ($this->isLazy($k)) {
$this->_loadFieldData($k);
}
$dbType= $this->_getDataType($k);
$fieldType= $this->_getPHPType($k);
$value= $this->_fields[$k];
if ($value !== null) {
switch ($fieldType) {
case 'boolean' :
$value= (boolean) $value;
break;
case 'integer' :
$value= intval($value);
if (is_string($format) && !empty ($format)) {
if (strpos($format, 're:') === 0) {
if (!empty ($formatTemplate) && is_string($formatTemplate)) {
$value= preg_replace(substr($format, 3), $formatTemplate, $value);
}
} else {
$value= sprintf($format, $value);
}
}
break;
case 'float' :
$value= (float) $value;
if (is_string($format) && !empty ($format)) {
if (strpos($format, 're:') === 0) {
if (!empty ($formatTemplate) && is_string($formatTemplate)) {