-
Notifications
You must be signed in to change notification settings - Fork 820
/
DataObject.php
4083 lines (3598 loc) · 133 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
/**
* A single database record & abstract class for the data-access-model.
*
* <h2>Extensions</h2>
*
* See {@link Extension} and {@link DataExtension}.
*
* <h2>Permission Control</h2>
*
* Object-level access control by {@link Permission}. Permission codes are arbitrary
* strings which can be selected on a group-by-group basis.
*
* <code>
* class Article extends DataObject implements PermissionProvider {
* static $api_access = true;
*
* function canView($member = false) {
* return Permission::check('ARTICLE_VIEW');
* }
* function canEdit($member = false) {
* return Permission::check('ARTICLE_EDIT');
* }
* function canDelete() {
* return Permission::check('ARTICLE_DELETE');
* }
* function canCreate() {
* return Permission::check('ARTICLE_CREATE');
* }
* function providePermissions() {
* return array(
* 'ARTICLE_VIEW' => 'Read an article object',
* 'ARTICLE_EDIT' => 'Edit an article object',
* 'ARTICLE_DELETE' => 'Delete an article object',
* 'ARTICLE_CREATE' => 'Create an article object',
* );
* }
* }
* </code>
*
* Object-level access control by {@link Group} membership:
* <code>
* class Article extends DataObject {
* static $api_access = true;
*
* function canView($member = false) {
* if(!$member) $member = Member::currentUser();
* return $member->inGroup('Subscribers');
* }
* function canEdit($member = false) {
* if(!$member) $member = Member::currentUser();
* return $member->inGroup('Editors');
* }
*
* // ...
* }
* </code>
*
* If any public method on this class is prefixed with an underscore,
* the results are cached in memory through {@link cachedCall()}.
*
*
* @todo Add instance specific removeExtension() which undos loadExtraStatics()
* and defineMethods()
*
* @package framework
* @subpackage model
*
* @property integer ID ID of the DataObject, 0 if the DataObject doesn't exist in database.
* @property string ClassName Class name of the DataObject
* @property string LastEdited Date and time of DataObject's last modification.
* @property string Created Date and time of DataObject creation.
*/
class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider {
/**
* Human-readable singular name.
* @var string
* @config
*/
private static $singular_name = null;
/**
* Human-readable plural name
* @var string
* @config
*/
private static $plural_name = null;
/**
* Allow API access to this object?
* @todo Define the options that can be set here
* @config
*/
private static $api_access = false;
/**
* True if this DataObject has been destroyed.
* @var boolean
*/
public $destroyed = false;
/**
* The DataModel from this this object comes
*/
protected $model;
/**
* Data stored in this objects database record. An array indexed by fieldname.
*
* Use {@link toMap()} if you want an array representation
* of this object, as the $record array might contain lazy loaded field aliases.
*
* @var array
*/
protected $record;
/**
* Represents a field that hasn't changed (before === after, thus before == after)
*/
const CHANGE_NONE = 0;
/**
* Represents a field that has changed type, although not the loosely defined value.
* (before !== after && before == after)
* E.g. change 1 to true or "true" to true, but not true to 0.
* Value changes are by nature also considered strict changes.
*/
const CHANGE_STRICT = 1;
/**
* Represents a field that has changed the loosely defined value
* (before != after, thus, before !== after))
* E.g. change false to true, but not false to 0
*/
const CHANGE_VALUE = 2;
/**
* An array indexed by fieldname, true if the field has been changed.
* Use {@link getChangedFields()} and {@link isChanged()} to inspect
* the changed state.
*
* @var array
*/
private $changed;
/**
* The database record (in the same format as $record), before
* any changes.
* @var array
*/
protected $original;
/**
* Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete()
* @var boolean
*/
protected $brokenOnDelete = false;
/**
* Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite()
* @var boolean
*/
protected $brokenOnWrite = false;
/**
* @config
* @var boolean Should dataobjects be validated before they are written?
* Caution: Validation can contain safeguards against invalid/malicious data,
* and check permission levels (e.g. on {@link Group}). Therefore it is recommended
* to only disable validation for very specific use cases.
*/
private static $validation_enabled = true;
/**
* Static caches used by relevant functions.
*/
public static $cache_has_own_table = array();
protected static $_cache_db = array();
protected static $_cache_get_one;
protected static $_cache_get_class_ancestry;
protected static $_cache_composite_fields = array();
protected static $_cache_is_composite_field = array();
protected static $_cache_custom_database_fields = array();
protected static $_cache_field_labels = array();
// base fields which are not defined in static $db
private static $fixed_fields = array(
'ID' => 'Int',
'ClassName' => 'Enum',
'LastEdited' => 'SS_Datetime',
'Created' => 'SS_Datetime',
);
/**
* Non-static relationship cache, indexed by component name.
*/
protected $components;
/**
* Non-static cache of has_many and many_many relations that can't be written until this object is saved.
*/
protected $unsavedRelations;
/**
* Returns when validation on DataObjects is enabled.
*
* @deprecated 3.2 Use the "DataObject.validation_enabled" config setting instead
* @return bool
*/
public static function get_validation_enabled() {
Deprecation::notice('3.2', 'Use the "DataObject.validation_enabled" config setting instead');
return Config::inst()->get('DataObject', 'validation_enabled');
}
/**
* Set whether DataObjects should be validated before they are written.
*
* Caution: Validation can contain safeguards against invalid/malicious data,
* and check permission levels (e.g. on {@link Group}). Therefore it is recommended
* to only disable validation for very specific use cases.
*
* @param $enable bool
* @see DataObject::validate()
* @deprecated 3.2 Use the "DataObject.validation_enabled" config setting instead
*/
public static function set_validation_enabled($enable) {
Deprecation::notice('3.2', 'Use the "DataObject.validation_enabled" config setting instead');
Config::inst()->update('DataObject', 'validation_enabled', (bool)$enable);
}
/**
* @var [string] - class => ClassName field definition cache for self::database_fields
*/
private static $classname_spec_cache = array();
/**
* Clear all cached classname specs. It's necessary to clear all cached subclassed names
* for any classes if a new class manifest is generated.
*/
public static function clear_classname_spec_cache() {
self::$classname_spec_cache = array();
PolymorphicForeignKey::clear_classname_spec_cache();
}
/**
* Determines the specification for the ClassName field for the given class
*
* @param string $class
* @param boolean $queryDB Determine if the DB may be queried for additional information
* @return string Resulting ClassName spec. If $queryDB is true this will include all
* legacy types that no longer have concrete classes in PHP
*/
public static function get_classname_spec($class, $queryDB = true) {
// Check cache
if(!empty(self::$classname_spec_cache[$class])) return self::$classname_spec_cache[$class];
// Build known class names
$classNames = ClassInfo::subclassesFor($class);
// Enhance with existing classes in order to prevent legacy details being lost
if($queryDB && DB::get_schema()->hasField($class, 'ClassName')) {
$existing = DB::query("SELECT DISTINCT \"ClassName\" FROM \"{$class}\"")->column();
$classNames = array_unique(array_merge($classNames, $existing));
}
$spec = "Enum('" . implode(', ', $classNames) . "')";
// Only cache full information if queried
if($queryDB) self::$classname_spec_cache[$class] = $spec;
return $spec;
}
/**
* Return the complete map of fields on this object, including "Created", "LastEdited" and "ClassName".
* See {@link custom_database_fields()} for a getter that excludes these "base fields".
*
* @param string $class
* @param boolean $queryDB Determine if the DB may be queried for additional information
* @return array
*/
public static function database_fields($class, $queryDB = true) {
if(get_parent_class($class) == 'DataObject') {
// Merge fixed with ClassName spec and custom db fields
$fixed = self::$fixed_fields;
unset($fixed['ID']);
return array_merge(
$fixed,
array('ClassName' => self::get_classname_spec($class, $queryDB)),
self::custom_database_fields($class)
);
}
return self::custom_database_fields($class);
}
/**
* Get all database columns explicitly defined on a class in {@link DataObject::$db}
* and {@link DataObject::$has_one}. Resolves instances of {@link CompositeDBField}
* into the actual database fields, rather than the name of the field which
* might not equate a database column.
*
* Does not include "base fields" like "ID", "ClassName", "Created", "LastEdited",
* see {@link database_fields()}.
*
* @uses CompositeDBField->compositeDatabaseFields()
*
* @param string $class
* @return array Map of fieldname to specification, similiar to {@link DataObject::$db}.
*/
public static function custom_database_fields($class) {
if(isset(self::$_cache_custom_database_fields[$class])) {
return self::$_cache_custom_database_fields[$class];
}
$fields = Config::inst()->get($class, 'db', Config::UNINHERITED);
foreach(self::composite_fields($class, false) as $fieldName => $fieldClass) {
// Remove the original fieldname, it's not an actual database column
unset($fields[$fieldName]);
// Add all composite columns
$compositeFields = singleton($fieldClass)->compositeDatabaseFields();
if($compositeFields) foreach($compositeFields as $compositeName => $spec) {
$fields["{$fieldName}{$compositeName}"] = $spec;
}
}
// Add has_one relationships
$hasOne = Config::inst()->get($class, 'has_one', Config::UNINHERITED);
if($hasOne) foreach(array_keys($hasOne) as $field) {
// Check if this is a polymorphic relation, in which case the relation
// is a composite field
if($hasOne[$field] === 'DataObject') {
$relationField = DBField::create_field('PolymorphicForeignKey', null, $field);
$relationField->setTable($class);
if($compositeFields = $relationField->compositeDatabaseFields()) {
foreach($compositeFields as $compositeName => $spec) {
$fields["{$field}{$compositeName}"] = $spec;
}
}
} else {
$fields[$field . 'ID'] = 'ForeignKey';
}
}
$output = (array) $fields;
self::$_cache_custom_database_fields[$class] = $output;
return $output;
}
/**
* Returns the field class if the given db field on the class is a composite field.
* Will check all applicable ancestor classes and aggregate results.
*
* @param string $class Class to check
* @param string $name Field to check
* @param boolean $aggregated True if parent classes should be checked, or false to limit to this class
* @return string Class name of composite field if it exists
*/
public static function is_composite_field($class, $name, $aggregated = true) {
$key = $class . '_' . $name . '_' . (string)$aggregated;
if(!isset(DataObject::$_cache_is_composite_field[$key])) {
$isComposite = null;
if(!isset(DataObject::$_cache_composite_fields[$class])) {
self::cache_composite_fields($class);
}
if(isset(DataObject::$_cache_composite_fields[$class][$name])) {
$isComposite = DataObject::$_cache_composite_fields[$class][$name];
} elseif($aggregated && $class != 'DataObject' && ($parentClass=get_parent_class($class)) != 'DataObject') {
$isComposite = self::is_composite_field($parentClass, $name);
}
DataObject::$_cache_is_composite_field[$key] = ($isComposite) ? $isComposite : false;
}
return DataObject::$_cache_is_composite_field[$key] ?: null;
}
/**
* Returns a list of all the composite if the given db field on the class is a composite field.
* Will check all applicable ancestor classes and aggregate results.
*/
public static function composite_fields($class, $aggregated = true) {
if(!isset(DataObject::$_cache_composite_fields[$class])) self::cache_composite_fields($class);
$compositeFields = DataObject::$_cache_composite_fields[$class];
if($aggregated && $class != 'DataObject' && ($parentClass=get_parent_class($class)) != 'DataObject') {
$compositeFields = array_merge($compositeFields,
self::composite_fields($parentClass));
}
return $compositeFields;
}
/**
* Internal cacher for the composite field information
*/
private static function cache_composite_fields($class) {
$compositeFields = array();
$fields = Config::inst()->get($class, 'db', Config::UNINHERITED);
if($fields) foreach($fields as $fieldName => $fieldClass) {
if(!is_string($fieldClass)) continue;
// Strip off any parameters
$bPos = strpos($fieldClass, '(');
if($bPos !== FALSE) $fieldClass = substr($fieldClass, 0, $bPos);
// Test to see if it implements CompositeDBField
if(ClassInfo::classImplements($fieldClass, 'CompositeDBField')) {
$compositeFields[$fieldName] = $fieldClass;
}
}
DataObject::$_cache_composite_fields[$class] = $compositeFields;
}
/**
* 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.
*/
public function __construct($record = null, $isSingleton = false, $model = null) {
parent::__construct();
// Set the fields data.
if(!$record) {
$record = array(
'ID' => 0,
'ClassName' => get_class($this),
'RecordClassName' => get_class($this)
);
}
if(!is_array($record) && !is_a($record, "stdClass")) {
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 DataList::create()->First(); instead?",
E_USER_WARNING);
$record = null;
}
if(is_a($record, "stdClass")) {
$record = (array)$record;
}
// Set $this->record to $record, but ignore NULLs
$this->record = array();
foreach($record as $k => $v) {
// Ensure that ID is stored as a number and not a string
// To do: this kind of clean-up should be done on all numeric fields, in some relatively
// performant manner
if($v !== null) {
if($k == 'ID' && is_numeric($v)) $this->record[$k] = (int)$v;
else $this->record[$k] = $v;
}
}
// Identify fields that should be lazy loaded, but only on existing records
if(!empty($record['ID'])) {
$currentObj = get_class($this);
while($currentObj != 'DataObject') {
$fields = self::custom_database_fields($currentObj);
foreach($fields as $field => $type) {
if(!array_key_exists($field, $record)) $this->record[$field.'_Lazy'] = $currentObj;
}
$currentObj = get_parent_class($currentObj);
}
}
$this->original = $this->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']);
}
// this must be called before populateDefaults(), as field getters on a DataObject
// may call getComponent() and others, which rely on $this->model being set.
$this->model = $model ? $model : DataModel::inst();
// Must be called after parent constructor
if(!$isSingleton && (!isset($this->record['ID']) || !$this->record['ID'])) {
$this->populateDefaults();
}
// prevent populateDefaults() and setField() from marking overwritten defaults as changed
$this->changed = array();
}
/**
* Set the DataModel
* @param DataModel $model
* @return DataObject $this
*/
public function setDataModel(DataModel $model) {
$this->model = $model;
return $this;
}
/**
* Destroy all of this objects dependant objects and local caches.
* You'll need to call this to get the memory of an object that has components or extensions freed.
*/
public function destroy() {
//$this->destroyed = true;
gc_collect_cycles();
$this->flushCache(false);
}
/**
* Create a duplicate of this node.
* Note: now also duplicates relations.
*
* @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.
*/
public function duplicate($doWrite = true) {
$className = $this->class;
$map = $this->toMap();
unset($map['Created']);
$clone = new $className( $map, false, $this->model );
$clone->ID = 0;
$clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite);
if($doWrite) {
$clone->write();
$this->duplicateManyManyRelations($this, $clone);
}
$clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite);
return $clone;
}
/**
* Copies the many_many and belongs_many_many relations from one object to another instance of the name of object
* The destinationObject must be written to the database already and have an ID. Writing is performed
* automatically when adding the new relations.
*
* @param $sourceObject the source object to duplicate from
* @param $destinationObject the destination object to populate with the duplicated relations
* @return DataObject with the new many_many relations copied in
*/
protected function duplicateManyManyRelations($sourceObject, $destinationObject) {
if (!$destinationObject || $destinationObject->ID < 1) {
user_error("Can't duplicate relations for an object that has not been written to the database",
E_USER_ERROR);
}
//duplicate complex relations
// DO NOT copy has_many relations, because copying the relation would result in us changing the has_one
// relation on the other side of this relation to point at the copy and no longer the original (being a
// has_one, it can only point at one thing at a time). So, all relations except has_many can and are copied
if ($sourceObject->hasOne()) foreach($sourceObject->hasOne() as $name => $type) {
$this->duplicateRelations($sourceObject, $destinationObject, $name);
}
if ($sourceObject->manyMany()) foreach($sourceObject->manyMany() as $name => $type) {
//many_many include belongs_many_many
$this->duplicateRelations($sourceObject, $destinationObject, $name);
}
return $destinationObject;
}
/**
* Helper function to duplicate relations from one object to another
* @param $sourceObject the source object to duplicate from
* @param $destinationObject the destination object to populate with the duplicated relations
* @param $name the name of the relation to duplicate (e.g. members)
*/
private function duplicateRelations($sourceObject, $destinationObject, $name) {
$relations = $sourceObject->$name();
if ($relations) {
if ($relations instanceOf ManyManyList) { //many-to-many relation
$extraFieldNames = $relations->getExtraFields();
if ($relations->Count() > 0) { //with more than one thing it is related to
foreach($relations as $relation) {
// Merge extra fields
$extraFields = array();
foreach ($extraFieldNames as $fieldName => $fieldType) {
$extraFields[$fieldName] = $relation->getField($fieldName);
}
$destinationObject->$name()->add($relation, $extraFields);
}
}
} else if ($relations instanceOf RelationList) { //many-to-something relation
if ($relations->Count() > 0) { //with more than one thing it is related to
foreach($relations as $relation) {
$destinationObject->$name()->add($relation);
}
}
} else { //one-to-one relation
$destinationObject->{"{$name}ID"} = $relations->ID;
}
}
}
public function getObsoleteClassName() {
$className = $this->getField("ClassName");
if (!ClassInfo::exists($className)) return $className;
}
public function getClassName() {
$className = $this->getField("ClassName");
if (!ClassInfo::exists($className)) return get_class($this);
return $className;
}
/**
* Set the ClassName attribute. {@link $class} is also updated.
* Warning: This will produce an inconsistent record, as the object
* instance will not automatically switch to the new subclass.
* Please use {@link newClassInstance()} for this purpose,
* or destroy and reinstanciate the record.
*
* @param string $className The new ClassName attribute (a subclass of {@link DataObject})
* @return DataObject $this
*/
public function setClassName($className) {
$className = trim($className);
if(!$className || !is_subclass_of($className, 'DataObject')) return;
$this->class = $className;
$this->setField("ClassName", $className);
return $this;
}
/**
* 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. Don't set the {@link DataObject->class} or {@link DataObject->ClassName}
* property manually before calling this method, as it will confuse change detection.
*
* If the new class is different to the original class, defaults are populated again
* because this will only occur automatically on instantiation of a DataObject if
* there is no record, or the record has no ID. In this case, we do have an ID but
* we still need to repopulate the defaults.
*
* @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.
*/
public function newClassInstance($newClassName) {
$originalClass = $this->ClassName;
$newInstance = new $newClassName(array_merge(
$this->record,
array(
'ClassName' => $originalClass,
'RecordClassName' => $originalClass,
)
), false, $this->model);
if($newClassName != $originalClass) {
$newInstance->setClassName($newClassName);
$newInstance->populateDefaults();
$newInstance->forceChange();
}
return $newInstance;
}
/**
* Adds methods from the extensions.
* Called by Object::__construct() once per class.
*/
public function defineMethods() {
parent::defineMethods();
// Define the extra db fields - this is only necessary for extensions added in the
// class definition. Object::add_extension() will call this at definition time for
// those objects, which is a better mechanism. Perhaps extensions defined inside the
// class def can somehow be applied at definiton time also?
if($this->extension_instances) foreach($this->extension_instances as $i => $instance) {
if(!$instance->class) {
$class = get_class($instance);
user_error("DataObject::defineMethods(): Please ensure {$class}::__construct() calls"
. " parent::__construct()", E_USER_ERROR);
}
}
if($this->class == 'DataObject') return;
// Set up accessors for joined items
if($manyMany = $this->manyMany()) {
foreach($manyMany as $relationship => $class) {
$this->addWrapperMethod($relationship, 'getManyManyComponents');
}
}
if($hasMany = $this->hasMany()) {
foreach($hasMany as $relationship => $class) {
$this->addWrapperMethod($relationship, 'getComponents');
}
}
if($hasOne = $this->hasOne()) {
foreach($hasOne as $relationship => $class) {
$this->addWrapperMethod($relationship, 'getComponent');
}
}
if($belongsTo = $this->belongsTo()) foreach(array_keys($belongsTo) as $relationship) {
$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 (isset($this->record['ID']) && $this->record['ID'] > 0);
}
/**
* Returns TRUE if all values (other than "ID") are
* considered empty (by weak boolean comparison).
* Only checks for fields listed in {@link custom_database_fields()}
*
* @todo Use DBField->hasValue()
*
* @return boolean
*/
public function isEmpty(){
$isEmpty = true;
$customFields = self::custom_database_fields(get_class($this));
if($map = $this->toMap()){
foreach($map as $k=>$v){
// only look at custom fields
if(!array_key_exists($k, $customFields)) continue;
$dbObj = ($v instanceof DBField) ? $v : $this->dbObject($k);
$isEmpty = ($isEmpty && !$dbObj->exists());
}
}
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
*/
public function singular_name() {
if(!$name = $this->stat('singular_name')) {
$name = ucwords(trim(strtolower(preg_replace('/_?([A-Z])/', ' $1', $this->class))));
}
return $name;
}
/**
* Get the translated user friendly singular name of this DataObject
* same as singular_name() but runs it through the translating function
*
* Translating string is in the form:
* $this->class.SINGULARNAME
* Example:
* Page.SINGULARNAME
*
* @return string User friendly translated singular name of this DataObject
*/
public function i18n_singular_name() {
return _t($this->class.'.SINGULARNAME', $this->singular_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
*/
public function plural_name() {
if($name = $this->stat('plural_name')) {
return $name;
} else {
$name = $this->singular_name();
//if the penultimate character is not a vowel, replace "y" with "ies"
if (preg_match('/[^aeiou]y$/i', $name)) {
$name = substr($name,0,-1) . 'ie';
}
return ucfirst($name . 's');
}
}
/**
* Get the translated user friendly plural name of this DataObject
* Same as plural_name but runs it through the translation function
* Translation string is in the form:
* $this->class.PLURALNAME
* Example:
* Page.PLURALNAME
*
* @return string User friendly translated plural name of this DataObject
*/
public function i18n_plural_name()
{
$name = $this->plural_name();
return _t($this->class.'.PLURALNAME', $name);
}
/**
* Standard implementation of a title/label for a specific
* record. Tries to find properties 'Title' or 'Name',
* and falls back to the 'ID'. Useful to provide
* user-friendly identification of a record, e.g. in errormessages
* or UI-selections.
*
* Overload this method to have a more specialized implementation,
* e.g. for an Address record this could be:
* <code>
* function getTitle() {
* return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
* }
* </code>
*
* @return string
*/
public function getTitle() {
if($this->hasDatabaseField('Title')) return $this->getField('Title');
if($this->hasDatabaseField('Name')) return $this->getField('Name');
return "#{$this->ID}";
}
/**
* 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() {
$this->loadLazyFields();
return $this->record;
}
/**
* Return all currently fetched database fields.
*
* This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
* Obviously, this makes it a lot faster.
*
* @return array The data as a map.
*/
public function getQueriedDatabaseFields() {
return $this->record;
}
/**
* Update a number of fields on this object, given a map of the desired changes.
*
* The field names can be simple names, or you can use a dot syntax to access $has_one relations.
* For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
*
* update() doesn't write the main object, but if you use the dot syntax, it will write()
* the related objects that it alters.
*
* @param array $data A map of field name to data values to update.
* @return DataObject $this
*/
public function update($data) {
foreach($data as $k => $v) {
// Implement dot syntax for updates
if(strpos($k,'.') !== false) {
$relations = explode('.', $k);
$fieldName = array_pop($relations);
$relObj = $this;
foreach($relations as $i=>$relation) {
// no support for has_many or many_many relationships,
// as the updater wouldn't know which object to write to (or create)
if($relObj->$relation() instanceof DataObject) {
$parentObj = $relObj;
$relObj = $relObj->$relation();
// If the intermediate relationship objects have been created, then write them
if($i<sizeof($relation)-1 && !$relObj->ID || (!$relObj->ID && $parentObj != $this)) {
$relObj->write();
$relatedFieldName = $relation."ID";
$parentObj->$relatedFieldName = $relObj->ID;
$parentObj->write();
}
} else {
user_error(
"DataObject::update(): Can't traverse relationship '$relation'," .
"it has to be a has_one relationship or return a single DataObject",
E_USER_NOTICE
);
// unset relation object so we don't write properties to the wrong object
unset($relObj);
break;
}
}
if($relObj) {
$relObj->$fieldName = $v;
$relObj->write();
$relatedFieldName = $relation."ID";
$this->$relatedFieldName = $relObj->ID;
$relObj->flushCache();
} else {
user_error("Couldn't follow dot syntax '$k' on '$this->class' object", E_USER_WARNING);
}
} else {
$this->$k = $v;
}
}
return $this;
}
/**
* 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.
* @return DataObject $this
*/
public function castedUpdate($data) {
foreach($data as $k => $v) {
$this->setCastedField($k,$v);
}
return $this;
}
/**
* Merges data and relations from another object of same class,
* without conflict resolution. Allows to specify which
* dataset takes priority in case its not empty.
* has_one-relations are just transferred with priority 'right'.
* has_many and many_many-relations are added regardless of priority.
*
* Caution: has_many/many_many relations are moved rather than duplicated,
* meaning they are not connected to the merged object any longer.
* Caution: Just saves updated has_many/many_many relations to the database,
* doesn't write the updated object itself (just writes the object-properties).
* Caution: Does not delete the merged object.
* Caution: Does now overwrite Created date on the original object.
*
* @param $obj DataObject
* @param $priority String left|right Determines who wins in case of a conflict (optional)
* @param $includeRelations Boolean Merge any existing relations (optional)
* @param $overwriteWithEmpty Boolean Overwrite existing left values with empty right values.
* Only applicable with $priority='right'. (optional)
* @return Boolean
*/
public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false) {
$leftObj = $this;
if($leftObj->ClassName != $rightObj->ClassName) {
// we can't merge similiar subclasses because they might have additional relations
user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
(expected '{$leftObj->ClassName}').", E_USER_WARNING);
return false;
}
if(!$rightObj->ID) {
user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
to make sure all relations are transferred properly.').", E_USER_WARNING);
return false;
}
// makes sure we don't merge data like ID or ClassName
$leftData = $leftObj->inheritedDatabaseFields();
$rightData = $rightObj->inheritedDatabaseFields();
foreach($rightData as $key=>$rightVal) {
// don't merge conflicting values if priority is 'left'
if($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) continue;
// don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)