-
Notifications
You must be signed in to change notification settings - Fork 824
/
DataObject.php
1767 lines (1538 loc) · 54.8 KB
/
DataObject.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
/**
* @package sapphire
* @subpackage core
*/
/**
* A single database record & abstract class for the data-access-model.
*/
class DataObject extends Controller {
/**
* Data stored in this objects database record. An array indexed
* by fieldname.
* @var array
*/
protected $record;
/**
* An array indexed by fieldname, true if the field has been changed.
* @var array
*/
protected $changed;
/**
* The database record (in the same format as $record), before
* any changes.
* @var array
*/
protected $original;
protected $defs;
protected $fieldObjects;
/**
* The one-to-one, one-to-many and many-to-one components
* indexed by component name.
* @var array
*/
protected $components;
/**
* True if this DataObject has been destroyed.
* @var boolean
*/
public $destroyed = false;
/**
* Human-readable singular name.
* @var string
*/
static $singular_name = null;
/**
* Human-readable pluaral name
* @var string
*/
static $plural_name = null;
/**
* Construct a new DataObject.
*
* @param array|null $record This will be null for a new database record. Alternatively, you can pass an array of
* field values. Normally this contructor is only used by the internal systems that get objects from the database.
* @param boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods. Singletons
* don't have their defaults set.
*/
function __construct($record = null, $isSingleton = false) {
// Set the fields data.
if(!$record) {
$record = array("ID" => 0);
}
if(!is_array($record)) {
if(is_object($record)) $passed = "an object of type '$record->class'";
else $passed = "The value '$record'";
user_error("DataObject::__construct passed $passed. It's supposed to be passed an array,
taken straight from the database. Perhaps you should use DataObject::get_one instead?", E_USER_WARNING);
$record = null;
}
$this->record = $this->original = $record;
// Keep track of the modification date of all the data sourced to make this page
// From this we create a Last-Modified HTTP header
if(isset($record['LastEdited'])) {
HTTP::register_modification_date($record['LastEdited']);
}
parent::__construct();
// Must be called after parent constructor
if(!$isSingleton && !$this->record['ID']) {
$this->populateDefaults();
}
// prevent populateDefaults() and setField() from marking overwritten defaults as changed
$this->changed = array();
}
/**
* Destroy all of this objects dependant objects.
* You'll need to call this to get the memory of an object that has components or extensions freed.
*/
function destroy() {
$this->extension_instances = null;
$this->components = null;
$this->destroyed = true;
}
/**
* Create a duplicate of this node.
*
* @param $doWrite Perform a write() operation before returning the object. If this is true, it will create the duplicate in the database.
*
* @return DataObject A duplicate of this node. The exact type will be the type of this node.
*/
function duplicate($doWrite = true) {
$className = $this->class;
$clone = new $className( $this->record );
$clone->ID = 0;
if($doWrite) $clone->write();
return $clone;
}
/**
* Set the ClassName attribute; $this->class is also updated.
*
* @param string $className The new ClassName attribute
*/
function setClassName($className) {
$this->class = trim($className);
$this->setField("ClassName", $className);
}
/**
* Create a new instance of a different class from this object's record
* This is useful when dynamically changing the type of an instance. Specifically,
* it ensures that the instance of the class is a match for the className of the
* record.
*
* @param string $newClassName The name of the new class
*
* @return DataObject The new instance of the new class, The exact type will be of the class name provided.
*/
function newClassInstance($newClassName) {
$newRecord = $this->record;
//$newRecord['RecordClassName'] = $newRecord['ClassName'] = $newClassName;
$newInstance = new $newClassName($newRecord);
$newInstance->setClassName($newClassName);
$newInstance->forceChange();
return $newInstance;
}
/**
* Adds methods from the extensions.
* Called by Object::__construct() once per class.
*/
function defineMethods() {
if($this->class == 'DataObject') return;
parent::defineMethods();
// Define the extra db fields
if($this->extension_instances) foreach($this->extension_instances as $i => $instance) {
$instance->loadExtraDBFields();
}
// Set up accessors for joined items
if($manyMany = $this->many_many()) {
foreach($manyMany as $relationship => $class) {
$this->addWrapperMethod($relationship, 'getManyManyComponents');
}
}
if($hasMany = $this->has_many()) {
foreach($hasMany as $relationship => $class) {
$this->addWrapperMethod($relationship, 'getComponents');
}
}
if($hasOne = $this->has_one()) {
foreach($hasOne as $relationship => $class) {
$this->addWrapperMethod($relationship, 'getComponent');
}
}
}
/**
* Returns true if this object "exists", i.e., has a sensible value.
* The default behaviour for a DataObject is to return true if
* the object exists in the database, you can override this in subclasses.
*
* @return boolean true if this object exists
*/
public function exists() {
return ($this->record && $this->record['ID'] > 0);
}
public function isEmpty(){
$isEmpty = true;
if($this->record){
foreach($this->record as $k=>$v){
if($k != "ID"){
$isEmpty = $isEmpty && !$v;
}
}
}
return $isEmpty;
}
/**
* Get the user friendly singular name of this DataObject.
* If the name is not defined (by redefining $singular_name in the subclass),
* this returns the class name.
*
* @return string User friendly singular name of this DataObject
*/
function singular_name() {
$name = $this->stat('singular_name');
if(!$name) {
$name = ucwords(trim(strtolower(ereg_replace('([A-Z])',' \\1',$this->class))));
}
return $name;
}
/**
* Get the user friendly plural name of this DataObject
* If the name is not defined (by renaming $plural_name in the subclass),
* this returns a pluralised version of the class name.
*
* @return string User friendly plural name of this DataObject
*/
function plural_name() {
if($name = $this->stat('plural_name')) {
return $name;
} else {
$name = $this->singular_name();
if(substr($name,-1) == 'e') $name = substr($name,0,-1);
else if(substr($name,-1) == 'y') $name = substr($name,0,-1) . 'ie';
return ucfirst($name . 's');
}
}
/**
* Returns the associated database record - in this case, the object itself.
* This is included so that you can call $dataOrController->data() and get a DataObject all the time.
*
* @return DataObject Associated database record
*/
public function data() {
return $this;
}
/**
* Convert this object to a map.
*
* @return array The data as a map.
*/
public function toMap() {
return $this->record;
}
/**
* Pass a number of field changes in a map.
* Doesn't write to the database. To write the data,
* use the write() method.
*
* @param array $data A map of field name to data values to update.
*/
public function update($data) {
foreach($data as $k => $v) {
$this->$k = $v;
}
}
/**
* Pass changes as a map, and try to
* get automatic casting for these fields.
* Doesn't write to the database. To write the data,
* use the write() method.
*
* @param array $data A map of field name to data values to update.
*/
public function castedUpdate($data) {
foreach($data as $k => $v) {
$this->setCastedField($k,$v);
}
}
/**
* Forces the record to think that all its data has changed.
* Doesn't write to the database.
*/
public function forceChange() {
foreach($this->record as $fieldName => $fieldVal)
$this->changed[$fieldName] = 1;
}
/**
* Event handler called before writing to the database.
* You can overload this to clean up or otherwise process data before writing it to the
* database. Don't forget to call parent::onBeforeWrite(), though!
*/
protected function onBeforeWrite() {
$this->brokenOnWrite = false;
$dummy = null;
$this->extend('augmentBeforeWrite', $dummy);
}
/**
* Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite()
* @var boolean
*/
protected $brokenOnWrite = false;
/**
* Event handler called before deleting from the database.
* You can overload this to clean up or otherwise process data before delete this
* record. Don't forget to call parent::onBeforeDelete(), though!
*/
protected function onBeforeDelete() {
$this->brokenOnDelete = false;
}
/**
* Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete()
* @var boolean
*/
protected $brokenOnDelete = false;
/**
* Load the default values in from the self::$defaults array.
* Will traverse the defaults of the current class and all its parent classes.
* Called by the constructor when creating new records.
*/
public function populateDefaults() {
$classes = array_reverse(ClassInfo::ancestry($this));
foreach($classes as $class) {
$singleton = ($class == $this->class) ? $this : singleton($class);
$defaults = $singleton->stat('defaults');
if($defaults) foreach($defaults as $fieldName => $fieldValue) {
// SRM 2007-03-06: Stricter check
if(!isset($this->$fieldName)) {
$this->$fieldName = $fieldValue;
}
// Set many-many defaults with an array of ids
if(is_array($fieldValue) && $this->many_many($fieldName)) {
$manyManyJoin = $this->$fieldName();
$manyManyJoin->setByIdList($fieldValue);
}
}
if($class == 'DataObject') {
break;
}
}
}
/**
* Writes all changes to this object to the database.
* - It will insert a record whenever ID isn't set, otherwise update.
* - All relevant tables will be updated.
* - $this->onBeforeWrite() gets called beforehand.
* - Extensions such as Versioned will ammend the database-write to ensure that a version is saved.
* - Calls to {@link DataObjectLog} can be used to see everything that's been changed.
*
* @param boolean $showDebug Show debugging information
* @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
* @param boolean $forceWrite Write to database even if there are no changes
*
* @return int The ID of the record
*/
public function write($showDebug = false, $forceInsert = false, $forceWrite = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if(!$this->changed) {
return $this->record['ID'];
}
foreach($this->getClassAncestry() as $ancestor) {
if(ClassInfo::hasTable($ancestor)) $ancestry[] = $ancestor;
}
// Look for some changes to make
unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
if(!$this->record['ID']) {
$baseTable = $ancestry[0];
DB::query("INSERT INTO `{$baseTable}` SET Created = NOW()");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $value) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->fieldExists($fieldName)) {
$manipulation[$class]['fields'][$fieldName] = $value ? ("'" . addslashes($value) . "'") : singleton($fieldType)->nullValue();
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "now()";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "now()";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(ClassInfo::hasTable($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
// Write ComponentSets as necessary
if($this->components) {
foreach($this->components as $component) {
$component->write($firstWrite);
}
}
if(!isset($this->record['Created'])) {
$this->record['Created'] = date('Y-m-d H:i:s');
}
$this->record['LastEdited'] = date('Y-m-d H:i:s');
return $this->record['ID'];
}
/**
* Perform a write without affecting the version table.
* On objects without versioning.
*
* @return int The ID of the record
*/
public function writeWithoutVersion() {
$this->changed['Version'] = 1;
if(!isset($this->record['Version'])) {
$this->record['Version'] = -1;
}
return $this->write();
}
/**
* Delete this data object.
* $this->onBeforeDelete() gets called.
* Note that in Versioned objects, both Stage and Live will be deleted.
*/
public function delete() {
$this->brokenOnDelete = true;
$this->onBeforeDelete();
if($this->brokenOnDelete) {
user_error("$this->class has a broken onBeforeDelete() function. Make sure that you call parent::onBeforeDelete().", E_USER_ERROR);
}
foreach($this->getClassAncestry() as $ancestor) {
if(ClassInfo::hastable($ancestor)) {
$sql = new SQLQuery();
$sql->delete = true;
$sql->from[$ancestor] = "`$ancestor`";
$sql->where[] = "ID = $this->ID";
$this->extend('augmentSQL', $sql);
$sql->execute();
}
}
$this->OldID = $this->ID;
$this->ID = 0;
DataObjectLog::deletedObject($this);
}
/**
* Delete the record with the given ID.
*
* @param string $className The class name of the record to be deleted
* @param int $id ID of record to be deleted
*/
public static function delete_by_id($className, $id) {
$obj = DataObject::get_by_id($className, $id);
if($obj) {
$obj->delete();
} else {
user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
}
}
/**
* A cache used by getClassAncestry()
* @var array
*/
protected static $ancestry;
/**
* Get the class ancestry, including the current class name.
* The ancestry will be returned as an array of class names, where the 0th element
* will be the class that inherits directly from DataObject, and the last element
* will be the current class.
*
* @return array Class ancestry
*/
public function getClassAncestry() {
if(!isset(DataObject::$ancestry[$this->class])) {
DataObject::$ancestry[$this->class] = array($this->class);
while(($class = get_parent_class(DataObject::$ancestry[$this->class][0])) != "DataObject") {
array_unshift(DataObject::$ancestry[$this->class], $class);
}
}
return DataObject::$ancestry[$this->class];
}
/**
* Return a component object from a one to one relationship, as a DataObject.
* If no component is available, an 'empty component' will be returned.
*
* @param string $componentName Name of the component
*
* @return DataObject The component object. It's exact type will be that of the component.
*/
public function getComponent($componentName) {
if(isset($this->components[$componentName])) {
return $this->components[$componentName];
}
if($componentClass = $this->has_one($componentName)) {
$childID = $this->getField($componentName . 'ID');
if($childID && is_numeric($childID)) {
$component = DataObject::get_by_id($componentClass,$childID);
}
// If no component exists, create placeholder object
if(!isset($component)) {
$component = $this->createComponent($componentName);
// We may have had an orphaned ID that needs to be cleaned up
$this->setField($componentName . 'ID', 0);
}
// If no component exists, create placeholder object
if(!$component) {
$component = $this->createComponent($componentName);
}
$this->components[$componentName] = $component;
return $component;
} else {
user_error("DataObject::getComponent(): Unknown 1-to-1 component '$componentName' on class '$this->class'", E_USER_ERROR);
}
}
/**
* A cache used by component getting classes
* @var array
*/
protected $componentCache;
/**
* Returns a one-to-many component, as a ComponentSet.
*
* @param string $componentName Name of the component
* @param string $filter A filter to be inserted into the WHERE clause
* @param string $sort A sort expression to be inserted into the ORDER BY clause. If omitted, the static field $default_sort on the component class will be used.
* @param string $join A single join clause. This can be used for filtering, only 1 instance of each DataObject will be returned.
* @param string $limit A limit expression to be inserted into the LIMIT clause
* @param string $having A filter to be inserted into the HAVING clause
*
* @return ComponentSet The components of the one-to-many relationship.
*/
public function getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = "", $having = "") {
// TODO Does not take different SQL-parameters into account on subsequent calls
if(isset($this->componentCache[$componentName])) {
return $this->componentCache[$componentName];
}
if(!$componentClass = $this->has_many($componentName)) {
user_error("DataObject::getComponents(): Unknown 1-to-many component '$componentName' on class '$this->class'", E_USER_ERROR);
}
$componentObj = singleton($componentClass);
$id = $this->getField("ID");
$joinField = $this->getComponentJoinField($componentName);
// get filter
$combinedFilter = "$joinField = '$id'";
if($filter) $combinedFilter .= " AND {$filter}";
$result = $componentObj->instance_get($combinedFilter, $sort, $join, $limit, "ComponentSet", $having);
if(!$result) {
$result = new ComponentSet();
}
$result->setComponentInfo("1-to-many", $this, null, null, $componentClass, $joinField);
// If this record isn't in the database, then we want to hold onto this specific ComponentSet,
// because it's the only copy of the data that we have.
if(!$this->isInDB()) {
$this->setComponent($componentName, $result);
}
return $result;
}
/**
* Tries to find the db-key for storing a relation (defaults to "ParentID" if no relation is found).
* The iteration is necessary because the most specific class does not always have a database-table.
*
* @param string $componentName Name of one to many component
*
* @return string Fieldname for the parent-relation
*/
public function getComponentJoinField($componentName) {
if(!$componentClass = $this->has_many($componentName)) {
user_error("DataObject::getComsponents(): Unknown 1-to-many component '$componentName' on class '$this->class'", E_USER_ERROR);
}
$componentObj = singleton($componentClass);
// get has-one relations
$reversedComponentRelations = array_flip($componentObj->has_one());
// get all parentclasses for the current class which have tables
$allClasses = ClassInfo::ancestry($this->class);
// use most specific relation by default (turn around order)
$allClasses = array_reverse($allClasses);
// traverse up through all classes with database-tables, starting with the most specific
// (mostly the classname of the calling DataObject)
foreach($allClasses as $class) {
// if this class does a "has-one"-representation, use it
if(isset($reversedComponentRelations[$class])) {
$joinField = $reversedComponentRelations[$class] . 'ID';
break;
}
}
if(!isset($joinField)) {
$joinField = 'ParentID';
}
return $joinField;
}
/**
* Sets the component of a relationship.
*
* @param string $componentName Name of the component
* @param DataObject|ComponentSet $componentValue Value of the component
*/
public function setComponent($componentName, $componentValue) {
$this->componentCache[$componentName] = $componentValue;
}
/**
* Returns a many-to-many component, as a ComponentSet.
* @param string $componentName Name of the many-many component
* @return ComponentSet The set of components
*
* TODO Implement query-params
*/
public function getManyManyComponents($componentName, $filter = "", $sort = "", $join = "", $limit = "", $having = "") {
if(isset($this->components[$componentName])) return $this->components[$componentName];
list($parentClass, $componentClass, $parentField, $componentField, $table) = $this->many_many($componentName);
if($this->ID && is_numeric($this->ID)) {
if($componentClass) {
$componentObj = singleton($componentClass);
// Join expression is done on SiteTree.ID even if we link to Page; it helps work around
// database inconsistencies
$componentBaseClass = ClassInfo::baseDataClass($componentClass);
$query = $componentObj->extendedSQL(
"`$table`.$parentField = $this->ID", // filter
$sort,
$limit,
"INNER JOIN `$table` ON `$table`.$componentField = `$componentBaseClass`.ID", // join
$having // having
);
array_unshift($query->select, "`$table`.*");
if($filter) $query->where[] = $filter;
if($join) $query->from[] = $join;
$records = $query->execute();
$result = $this->buildDataObjectSet($records, "ComponentSet", $query, $componentBaseClass);
if(!$result) {
$result = new ComponentSet();
}
}
} else {
$result = new ComponentSet();
}
$result->setComponentInfo("many-to-many", $this, $parentClass, $table, $componentClass);
$this->components[$componentName] = $result;
return $result;
}
/**
* Creates an empty component for the given one-one or one-many relationship
*
* @param string $componentName
*
* @return DataObject The empty component. The exact class will be that of the components class.
*/
protected function createComponent($componentName) {
if(($componentClass = $this->has_one($componentName)) || ($componentClass = $this->has_many($componentName))) {
$component = new $componentClass(null);
return $component;
} else {
user_error("DataObject::createComponent(): Unknown 1-to-1 or 1-to-many component '$componentName' on class '$this->class'", E_USER_ERROR);
}
}
/**
* Return the class of a one-to-one component. If $component is null, return all of the one-to-one components and their classes.
*
* @param string $component Name of component
*
* @return string|array The class of the one-to-one component, or an array of all one-to-one components and their classes.
*/
public function has_one($component = null) {
$classes = ClassInfo::ancestry($this);
$good = false;
foreach($classes as $class) {
// Wait until after we reach DataObject
if(!$good) {
if($class == 'DataObject') {
$good = true;
}
continue;
}
if($component) {
$candidate = eval("return isset({$class}::\$has_one[\$component]) ? {$class}::\$has_one[\$component] : null;");
if($candidate) {
return $candidate;
}
} else {
eval("\$items = isset(\$items) ? array_merge((array){$class}::\$has_one, (array)\$items) : (array){$class}::\$has_one;");
}
}
return isset($items) ? $items : null;
}
/**
* Return all of the database fields defined in self::$db and all the parent classes.
* Doesn't include any fields specified by self::$has_one. Use $this->has_one() to get these fields
*
* @return array The database fields
*/
public function db() {
$classes = ClassInfo::ancestry($this);
$good = false;
$items = array();
foreach($classes as $class) {
// Wait until after we reach DataObject
if(!$good) {
if($class == 'DataObject') {
$good = true;
}
continue;
}
eval("\$items = array_merge((array){$class}::\$db, (array)\$items);");
}
return $items;
}
/**
* Return the class of a one-to-many component. If $component is null, return all of the one-to-many components
* and their classes.
*
* @param string $component Name of component
*
* @return string|array The class of the one-to-many component, or an array of all one-to-many components and their classes.
*/
public function has_many($component = null) {
$classes = ClassInfo::ancestry($this);
$good = false;
foreach($classes as $class) {
// Wait until after we reach DataObject
if(!$good) {
if($class == 'DataObject') {
$good = true;
}
continue;
}
if($component) {
$candidate = eval("return isset({$class}::\$has_many[\$component]) ? {$class}::\$has_many[\$component] : null;");
if($candidate) {
return $candidate;
}
} else {
eval("\$items = isset(\$items) ? array_merge((array){$class}::\$has_many, (array)\$items) : (array){$class}::\$has_many;");
}
}
return isset($items) ? $items : null;
}
/**
* Return information about a many-to-many component.
* The return value is an array of (parentclass, childclass). If $component is null, then all many-many
* components are returned.
*
* @param string $component Name of component
*
* @return array An array of (parentclass, childclass), or an array of all many-many components
*/
public function many_many($component = null) {
$classes = ClassInfo::ancestry($this);
$good = false;
foreach($classes as $class) {
// Wait until after we reach DataObject
if(!$good) {
if($class == 'DataObject') {
$good = true;
}
continue;
}
if($class == 'DataObject' || $class == 'ViewableData') {
continue;
}
if($component) {
// Try many_many
$candidate = eval("return isset({$class}::\$many_many[\$component]) ? {$class}::\$many_many[\$component] : null;");
if($candidate) {
$parentField = $class . "ID";
$childField = ($class == $candidate) ? "ChildID" : $candidate . "ID";
return array($class, $candidate, $parentField, $childField, "{$class}_$component");
}
// Try belongs_many_many
$candidate = eval("return isset({$class}::\$belongs_many_many[\$component]) ? {$class}::\$belongs_many_many[\$component] : null;");
if($candidate) {
$childField = $candidate . "ID";
// We need to find the inverse component name
$otherManyMany = eval("return {$candidate}::\$many_many;");
if(!$otherManyMany) {
Debug::message("Inverse component of $candidate not found");
}
foreach($otherManyMany as $inverseComponentName => $candidateClass) {
if($candidateClass == $class || is_subclass_of($class, $candidateClass)) {
$parentField = ($class == $candidate) ? "ChildID" : $candidateClass . "ID";
// HACK HACK HACK!
if($component == 'NestedProducts') {
$parentField = $candidateClass . "ID";
}
return array($class, $candidate, $parentField, $childField, "{$candidate}_$inverseComponentName");
}
}
user_error("Orphaned \$belongs_many_many value for $this->class.$component", E_USER_ERROR);
}
} else {
eval("\$items = isset(\$items) ? array_merge((array){$class}::\$many_many, (array)\$items) : (array){$class}::\$many_many;");
eval("\$items = array_merge((array){$class}::\$belongs_many_many, (array)\$items);");
}
}
return isset($items) ? $items : null;
}
/**
* Checks if the given fields have been filled out.
* Pass this method a number of field names, it will return true if they all have values.
*
* @param array|string $args,... The field names may be passed either as an array, or as multiple parameters.
*
* @return boolean True if all fields have values, otherwise false
*/
public function filledOut($args) {
// Field names can be passed as arguments or an array
if(!is_array($args)) $args = func_get_args();
foreach($args as $arg) {
if(!$this->$arg) {
return false;
}
}
return true;
}
/**
* Gets the value of a field.
* Called by {@link __get()} and any getFieldName() methods you might create.
*
* @param string $field The name of the field
*
* @return mixed The field value
*/
protected function getField($field) {
return isset($this->record[$field]) ? $this->record[$field] : null;
}
/**
* Return a map of all the fields for this record.
*
* @return array A map of field names to field values.
*/
public function getAllFields() {
return $this->record;
}
/**
* Return the fields that have changed.
* The change level affects what the functions defines as "changed":
* Level 1 will return strict changes, even !== ones.
* Level 2 is more lenient, it will onlr return real data changes, for example a change from 0 to null
* would not be included.
*
* @param boolean $databaseFieldsOnly Get only database fields that have changed
* @param int $changeLevel The strictness of what is defined as change
*/
public function getChangedFields($databaseFieldsOnly = false, $changeLevel = 1) {
if($databaseFieldsOnly) {
$customDatabaseFields = $this->customDatabaseFields();