-
Notifications
You must be signed in to change notification settings - Fork 821
/
DataObject.php
4587 lines (4146 loc) · 163 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
namespace SilverStripe\ORM;
use BadMethodCallException;
use Exception;
use InvalidArgumentException;
use LogicException;
use SilverStripe\Assets\Storage\DBFile;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Resettable;
use SilverStripe\Dev\Debug;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FormField;
use SilverStripe\Forms\FormScaffolder;
use SilverStripe\Forms\CompositeValidator;
use SilverStripe\Forms\FieldsValidator;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\SearchableDropdownField;
use SilverStripe\i18n\i18n;
use SilverStripe\i18n\i18nEntityProvider;
use SilverStripe\ORM\Connect\MySQLSchemaManager;
use SilverStripe\ORM\FieldType\DBComposite;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\FieldType\DBEnum;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBForeignKey;
use SilverStripe\ORM\Filters\PartialMatchFilter;
use SilverStripe\ORM\Filters\SearchFilter;
use SilverStripe\ORM\Queries\SQLDelete;
use SilverStripe\ORM\Search\SearchContext;
use SilverStripe\ORM\RelatedData\RelatedDataService;
use SilverStripe\ORM\UniqueKey\UniqueKeyInterface;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\Security;
use SilverStripe\View\SSViewer;
use SilverStripe\View\ViewableData;
use stdClass;
/**
* 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 = Security::getCurrentUser();
* return $member->inGroup('Subscribers');
* }
* function canEdit($member = false) {
* if (!$member) $member = Security::getCurrentUser();
* 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()}.
*
* @property int $ID ID of the DataObject, 0 if the DataObject doesn't exist in database.
* @property int $OldID ID of object, if deleted
* @property string $Title
* @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.
* @property string $ObsoleteClassName If ClassName no longer exists this will be set to the legacy value
*/
class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider, Resettable
{
/**
* Human-readable singular name.
* @var string
* @config
*/
private static $singular_name = null;
/**
* Human-readable plural name
* @var string
* @config
*/
private static $plural_name = null;
/**
* @config
*/
private static $api_access = false;
/**
* Allows specification of a default value for the ClassName field.
* Configure this value only in subclasses of DataObject.
*
* @config
* @var string
*/
private static $default_classname = null;
/**
* 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;
/**
* If selected through a many_many through relation, this is the instance of the through record
*
* @var DataObject
*/
protected $joinRecord;
/**
* 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;
/**
* Value for 2nd argument to constructor, indicating that a new record is being created
* Setters will be called on fields passed, and defaults will be populated
*/
const CREATE_OBJECT = 0;
/**
* Value for 2nd argument to constructor, indicating that a record is a singleton representing the whole type,
* e.g. to call requireTable() in dev/build
* Defaults will not be populated and data passed will be ignored
*/
const CREATE_SINGLETON = 1;
/**
* Value for 2nd argument to constructor, indicating that a record is being hydrated from the database
* Setter methods are not called, and population via private static $defaults will not occur.
*/
const CREATE_HYDRATED = 2;
/**
* Value for 2nd argument to constructor, indicating that a record is being hydrated from memory. This can be used
* to initialised a record that doesn't yet have an ID. Setter methods are not called, and population via private
* static $defaults will not occur.
*/
const CREATE_MEMORY_HYDRATED = 3;
/**
* 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 = [];
/**
* A flag to indicate that a "strict" change of the entire record been forced
* Use {@link getChangedFields()} and {@link isChanged()} to inspect
* the changed state.
*
* @var boolean
*/
private $changeForced = false;
/**
* 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;
/**
* 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.
*
* @config
* @var boolean
*/
private static $validation_enabled = true;
/**
* Static caches used by relevant functions.
*
* @var array
*/
protected static $_cache_get_one;
/**
* Cache of field labels
*
* @var array
*/
protected static $_cache_field_labels = [];
/**
* Base fields which are not defined in static $db
*
* @config
* @var array
*/
private static $fixed_fields = [
'ID' => 'PrimaryKey',
'ClassName' => 'DBClassName',
'LastEdited' => 'DBDatetime',
'Created' => 'DBDatetime',
];
/**
* Override table name for this class. If ignored will default to FQN of class.
* This option is not inheritable, and must be set on each class.
* If left blank naming will default to the legacy (3.x) behaviour.
*
* @var string
*/
private static $table_name = null;
/**
* Settings used by the FormScaffolder that scaffolds fields for getCMSFields()
*/
private static array $scaffold_cms_fields_settings = [
'includeRelations' => true,
'tabbed' => true,
'ajaxSafe' => true,
];
/**
* Non-static relationship cache, indexed by component name.
*
* @var DataObject[]
*/
protected $components = [];
/**
* Non-static cache of has_many and many_many relations that can't be written until this object is saved.
*
* @var UnsavedRelationList[]
*/
protected $unsavedRelations;
private array $eagerLoadedData = [];
/**
* List of relations that should be cascade deleted, similar to `owns`
* Note: This will trigger delete on many_many objects, not only the mapping table.
* For many_many through you can specify the components you want to delete separately
* (many_many or has_many sub-component)
*
* @config
* @var array
*/
private static $cascade_deletes = [];
/**
* List of relations that should be cascade duplicate.
* many_many duplications are shallow only.
*
* Note: If duplicating a many_many through you should refer to the
* has_many intermediary relation instead, otherwise extra fields
* will be omitted from the duplicated relation.
*
* @var array
*/
private static $cascade_duplicates = [];
/**
* Used to cache the schema to prevent repeatedly fetching the singleton
* While this is a fast operation, in some scenarios getSchema() is called an extremely large number of times
*
* @internal
*/
private static ?DataObjectSchema $schema = null;
/**
* Get schema object
*
* @return DataObjectSchema
*/
public static function getSchema()
{
if (is_null(DataObject::$schema)) {
DataObject::$schema = Injector::inst()->get(DataObjectSchema::class);
}
return DataObject::$schema;
}
/**
* Construct a new DataObject.
*
* @param array $record Initial record content, or rehydrated record content, depending on $creationType
* @param int|boolean $creationType Set to DataObject::CREATE_OBJECT, DataObject::CREATE_HYDRATED,
* DataObject::CREATE_MEMORY_HYDRATED or DataObject::CREATE_SINGLETON. Used by Silverstripe internals and best
* left as the default by regular users.
* @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects.
*/
public function __construct($record = [], $creationType = DataObject::CREATE_OBJECT, $queryParams = [])
{
parent::__construct();
// Legacy $record default
if ($record === null) {
$record = [];
}
// Legacy $isSingleton boolean
if (!is_int($creationType)) {
if (!is_bool($creationType)) {
user_error('Creation type is neither boolean (old isSingleton arg) nor integer (new arg), please review your code', E_USER_WARNING);
}
$creationType = $creationType ? DataObject::CREATE_SINGLETON : DataObject::CREATE_OBJECT;
}
// Set query params on the DataObject to tell the lazy loading mechanism the context the object creation context
$this->setSourceQueryParams($queryParams);
// Set $this->record to $record, but ignore NULLs
$this->record = [];
switch ($creationType) {
// Hydrate a record
case DataObject::CREATE_HYDRATED:
case DataObject::CREATE_MEMORY_HYDRATED:
$this->hydrate($record, $creationType === DataObject::CREATE_HYDRATED);
break;
// Create a new object, using the constructor argument as the initial content
case DataObject::CREATE_OBJECT:
if ($record instanceof stdClass) {
$record = (array)$record;
}
if (!is_array($record)) {
if (is_object($record)) {
$passed = "an object of type '" . get_class($record) . "'";
} 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 = [];
}
// Default columns
$this->record['ID'] = empty($record['ID']) ? 0 : $record['ID'];
$this->record['ClassName'] = static::class;
$this->record['RecordClassName'] = static::class;
unset($record['ID']);
$this->original = $this->record;
$this->populateDefaults();
// prevent populateDefaults() and setField() from marking overwritten defaults as changed
$this->changed = [];
$this->changeForced = false;
// Set the data passed in the constructor, allowing for defaults and calling setters
// This will mark fields as changed
if ($record) {
$this->update($record);
}
break;
case DataObject::CREATE_SINGLETON:
// No setting happens for a singleton
$this->record['ID'] = 0;
$this->record['ClassName'] = static::class;
$this->record['RecordClassName'] = static::class;
$this->original = $this->record;
$this->changed = [];
$this->changeForced = false;
break;
default:
throw new \LogicException('Bad creationType ' . $this->creationType);
}
}
/**
* Constructor hydration logic for CREATE_HYDRATED and CREATE_MEMORY_HYDRATED.
* @param array $record
* @param bool $mustHaveID If true, an exception will be thrown if $record doesn't have an ID.
*/
private function hydrate(array $record, bool $mustHaveID)
{
if ($mustHaveID && empty($record['ID'])) {
// CREATE_HYDRATED requires an ID to be included in the record
throw new \InvalidArgumentException(
"Hydrated records must be passed a record array including an ID."
);
} elseif (empty($record['ID'])) {
// CREATE_MEMORY_HYDRATED implicitly set the record ID to 0 if not provided
$record['ID'] = 0;
}
$this->record = $record;
// Identify fields that should be lazy loaded, but only on existing records
// Get all field specs scoped to class for later lazy loading
$fields = static::getSchema()->fieldSpecs(
static::class,
DataObjectSchema::INCLUDE_CLASS | DataObjectSchema::DB_ONLY
);
foreach ($fields as $field => $fieldSpec) {
$fieldClass = strtok($fieldSpec ?? '', ".");
if (!array_key_exists($field, $record ?? [])) {
$this->record[$field . '_Lazy'] = $fieldClass;
}
}
// Extension point to hydrate additional fields into this object during construction.
// Return an array of field names => raw values from your augmentHydrateFields extension method.
$extendedAdditionalFields = $this->extend('augmentHydrateFields');
foreach ($extendedAdditionalFields as $additionalFields) {
foreach ($additionalFields as $field => $value) {
$this->record[$field] = $value;
// If a corresponding lazy-load field exists, remove it as the value has been provided
$lazyName = $field . '_Lazy';
if (array_key_exists($lazyName, $this->record ?? [])) {
unset($this->record[$lazyName]);
}
}
}
$this->original = $this->record;
$this->changed = [];
$this->changeForced = false;
}
/**
* Destroy all of this objects dependent 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->flushCache(false);
}
/**
* Create a duplicate of this node. Can duplicate many_many relations
*
* Will default to `cascade_duplicates` if null.
* Set to 'false' to force none.
* Set to specific array of names to duplicate to override these.
* Note: If using versioned, this will additionally failover to `owns` config.
*/
public function duplicate(bool $doWrite = true, array|null $relations = null): static
{
// Get duplicates
if ($relations === null) {
$relations = $this->config()->get('cascade_duplicates');
// Remove any duplicate entries before duplicating them
if (is_array($relations)) {
$relations = array_unique($relations ?? []);
}
}
// Create unsaved raw duplicate
$map = $this->toMap();
unset($map['Created']);
$clone = Injector::inst()->create(static::class, $map, false, $this->getSourceQueryParams());
$clone->ID = 0;
// Note: Extensions such as versioned may update $relations here
$clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite, $relations);
if ($relations) {
$this->duplicateRelations($this, $clone, $relations);
}
if ($doWrite) {
$clone->write();
}
$clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite, $relations);
return $clone;
}
/**
* Copies the given relations from this object to the destination
*
* @param DataObject $sourceObject the source object to duplicate from
* @param DataObject $destinationObject the destination object to populate with the duplicated relations
* @param array $relations List of relations
*/
protected function duplicateRelations($sourceObject, $destinationObject, $relations)
{
// Get list of duplicable relation types
$manyMany = $sourceObject->manyMany();
$hasMany = $sourceObject->hasMany();
$hasOne = $sourceObject->hasOne();
$belongsTo = $sourceObject->belongsTo();
// Duplicate each relation based on type
foreach ($relations as $relation) {
switch (true) {
case array_key_exists($relation, $manyMany): {
$this->duplicateManyManyRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $hasMany): {
$this->duplicateHasManyRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $hasOne): {
$this->duplicateHasOneRelation($sourceObject, $destinationObject, $relation);
break;
}
case array_key_exists($relation, $belongsTo): {
$this->duplicateBelongsToRelation($sourceObject, $destinationObject, $relation);
break;
}
default: {
$sourceType = get_class($sourceObject);
throw new InvalidArgumentException(
"Cannot duplicate unknown relation {$relation} on parent type {$sourceType}"
);
}
}
}
}
/**
* Duplicates a single many_many relation from one object to another.
*
* @param DataObject $sourceObject
* @param DataObject $destinationObject
* @param string $relation
*/
protected function duplicateManyManyRelation($sourceObject, $destinationObject, $relation)
{
// Copy all components from source to destination
$source = $sourceObject->getManyManyComponents($relation);
$dest = $destinationObject->getManyManyComponents($relation);
if ($source instanceof ManyManyList) {
$extraFieldNames = $source->getExtraFields();
} else {
$extraFieldNames = [];
}
foreach ($source as $item) {
// Merge extra fields
$extraFields = [];
foreach ($extraFieldNames as $fieldName => $fieldType) {
$extraFields[$fieldName] = $item->getField($fieldName);
}
$dest->add($item, $extraFields);
}
}
/**
* Duplicates a single many_many relation from one object to another.
*
* @param DataObject $sourceObject
* @param DataObject $destinationObject
* @param string $relation
*/
protected function duplicateHasManyRelation($sourceObject, $destinationObject, $relation)
{
// Copy all components from source to destination
$source = $sourceObject->getComponents($relation);
$dest = $destinationObject->getComponents($relation);
foreach ($source as $item) {
// Don't write on duplicate; Wait until ParentID is available later.
// writeRelations() will eventually write these records when converting
// from UnsavedRelationList
$clonedItem = $item->duplicate(false);
$dest->add($clonedItem);
}
}
/**
* Duplicates a single has_one relation from one object to another.
* Note: Child object will be force written.
*
* @param DataObject $sourceObject
* @param DataObject $destinationObject
* @param string $relation
*/
protected function duplicateHasOneRelation($sourceObject, $destinationObject, $relation)
{
// Check if original object exists
$item = $sourceObject->getComponent($relation);
if (!$item->isInDB()) {
return;
}
$clonedItem = $item->duplicate(false);
$destinationObject->setComponent($relation, $clonedItem);
}
/**
* Duplicates a single belongs_to relation from one object to another.
* Note: This will force a write on both parent / child objects.
*
* @param DataObject $sourceObject
* @param DataObject $destinationObject
* @param string $relation
*/
protected function duplicateBelongsToRelation($sourceObject, $destinationObject, $relation)
{
// Check if original object exists
$item = $sourceObject->getComponent($relation);
if (!$item->isInDB()) {
return;
}
$clonedItem = $item->duplicate(false);
$destinationObject->setComponent($relation, $clonedItem);
// After $clonedItem is assigned the appropriate FieldID / FieldClass, force write
$clonedItem->write();
}
/**
* Return obsolete class name, if this is no longer a valid class
*
* @return string
*/
public function getObsoleteClassName()
{
$className = $this->getField("ClassName");
if (!ClassInfo::exists($className)) {
return $className;
}
return null;
}
/**
* Gets name of this class
*
* @return string
*/
public function getClassName()
{
$className = $this->getField("ClassName");
if (!ClassInfo::exists($className)) {
return static::class;
}
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 $this
*/
public function setClassName($className)
{
$className = trim($className ?? '');
if (!$className || !is_subclass_of($className, DataObject::class)) {
return $this;
}
$this->setField("ClassName", $className);
$this->setField('RecordClassName', $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.
*
* @template T of DataObject
* @param class-string<T> $newClassName The name of the new class
*
* @return T The new instance of the new class, The exact type will be of the class name provided.
*/
public function newClassInstance($newClassName)
{
if (!is_subclass_of($newClassName, DataObject::class)) {
throw new InvalidArgumentException("$newClassName is not a valid subclass of DataObject");
}
$originalClass = $this->ClassName;
/** @var DataObject $newInstance */
$newInstance = Injector::inst()->create($newClassName, $this->record, DataObject::CREATE_MEMORY_HYDRATED);
// Modify ClassName
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();
if (static::class === DataObject::class) {
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 $this->isInDB();
}
/**
* Returns TRUE if all values (other than "ID") are
* considered empty (by weak boolean comparison).
*
* @return boolean
*/
public function isEmpty()
{
$fixed = DataObject::config()->uninherited('fixed_fields');
foreach ($this->toMap() as $field => $value) {
// only look at custom fields
if (isset($fixed[$field])) {
continue;
}
$dbObject = $this->dbObject($field);
if (!$dbObject) {
continue;
}
if ($dbObject->exists()) {
return false;
}
}
return true;
}
/**
* Pluralise this item given a specific count.
*
* E.g. "0 Pages", "1 File", "3 Images"
*
* @param string $count
* @return string
*/
public function i18n_pluralise($count)
{
$default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name();
return i18n::_t(
static::class . '.PLURALS',
$default,
['count' => $count]
);
}
/**
* 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()
{
$name = $this->config()->get('singular_name');
if ($name) {
return $name;
}
return ucwords(trim(strtolower(preg_replace(
'/_?([A-Z])/',
' $1',
ClassInfo::shortName($this) ?? ''
) ?? '')));
}
/**
* 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(static::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->config()->get('plural_name')) {
return $name;
}
$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()
{
return _t(static::class . '.PLURALNAME', $this->plural_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()
{
$schema = static::getSchema();
if ($schema->fieldSpec($this, 'Title')) {
return $this->getField('Title');
}
if ($schema->fieldSpec($this, '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 static Associated database record
*/
public function data()
{
return $this;
}
/**
* Convert this object to a map.
* Note that it has the following quirks:
* - custom getters, including those that adjust the result of database fields, won't be executed
* - NULL values won't be returned.
*
* @return array The data as a map.
*/
public function toMap()
{
$this->loadLazyFields();
return array_filter($this->record ?? [], function ($val) {
return $val !== null;
});
}
/**