Passed
Push — 4.8 ( abf72c...e8c14a )
by Ingo
08:31 queued 11s
created

DataObject::dbObject()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 9
nop 1
dl 0
loc 33
rs 8.9777
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\ORM;
4
5
use BadMethodCallException;
6
use Exception;
7
use InvalidArgumentException;
8
use LogicException;
9
use SilverStripe\Core\ClassInfo;
10
use SilverStripe\Core\Config\Config;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\Core\Resettable;
13
use SilverStripe\Dev\Debug;
14
use SilverStripe\Dev\Deprecation;
15
use SilverStripe\Forms\FieldList;
16
use SilverStripe\Forms\FormField;
17
use SilverStripe\Forms\FormScaffolder;
18
use SilverStripe\Forms\CompositeValidator;
19
use SilverStripe\i18n\i18n;
20
use SilverStripe\i18n\i18nEntityProvider;
21
use SilverStripe\ORM\Connect\MySQLSchemaManager;
22
use SilverStripe\ORM\FieldType\DBComposite;
23
use SilverStripe\ORM\FieldType\DBDatetime;
24
use SilverStripe\ORM\FieldType\DBEnum;
25
use SilverStripe\ORM\FieldType\DBField;
26
use SilverStripe\ORM\Filters\SearchFilter;
27
use SilverStripe\ORM\Queries\SQLDelete;
28
use SilverStripe\ORM\Search\SearchContext;
29
use SilverStripe\ORM\RelatedData\RelatedDataService;
30
use SilverStripe\ORM\UniqueKey\UniqueKeyInterface;
31
use SilverStripe\ORM\UniqueKey\UniqueKeyService;
32
use SilverStripe\Security\Member;
33
use SilverStripe\Security\Permission;
34
use SilverStripe\Security\Security;
35
use SilverStripe\View\SSViewer;
36
use SilverStripe\View\ViewableData;
37
use stdClass;
38
39
/**
40
 * A single database record & abstract class for the data-access-model.
41
 *
42
 * <h2>Extensions</h2>
43
 *
44
 * See {@link Extension} and {@link DataExtension}.
45
 *
46
 * <h2>Permission Control</h2>
47
 *
48
 * Object-level access control by {@link Permission}. Permission codes are arbitrary
49
 * strings which can be selected on a group-by-group basis.
50
 *
51
 * <code>
52
 * class Article extends DataObject implements PermissionProvider {
53
 *  static $api_access = true;
54
 *
55
 *  function canView($member = false) {
56
 *    return Permission::check('ARTICLE_VIEW');
57
 *  }
58
 *  function canEdit($member = false) {
59
 *    return Permission::check('ARTICLE_EDIT');
60
 *  }
61
 *  function canDelete() {
62
 *    return Permission::check('ARTICLE_DELETE');
63
 *  }
64
 *  function canCreate() {
65
 *    return Permission::check('ARTICLE_CREATE');
66
 *  }
67
 *  function providePermissions() {
68
 *    return array(
69
 *      'ARTICLE_VIEW' => 'Read an article object',
70
 *      'ARTICLE_EDIT' => 'Edit an article object',
71
 *      'ARTICLE_DELETE' => 'Delete an article object',
72
 *      'ARTICLE_CREATE' => 'Create an article object',
73
 *    );
74
 *  }
75
 * }
76
 * </code>
77
 *
78
 * Object-level access control by {@link Group} membership:
79
 * <code>
80
 * class Article extends DataObject {
81
 *   static $api_access = true;
82
 *
83
 *   function canView($member = false) {
84
 *     if(!$member) $member = Security::getCurrentUser();
85
 *     return $member->inGroup('Subscribers');
86
 *   }
87
 *   function canEdit($member = false) {
88
 *     if(!$member) $member = Security::getCurrentUser();
89
 *     return $member->inGroup('Editors');
90
 *   }
91
 *
92
 *   // ...
93
 * }
94
 * </code>
95
 *
96
 * If any public method on this class is prefixed with an underscore,
97
 * the results are cached in memory through {@link cachedCall()}.
98
 *
99
 *
100
 * @todo Add instance specific removeExtension() which undos loadExtraStatics()
101
 *  and defineMethods()
102
 *
103
 * @property int $ID ID of the DataObject, 0 if the DataObject doesn't exist in database.
104
 * @property int $OldID ID of object, if deleted
105
 * @property string $Title
106
 * @property string $ClassName Class name of the DataObject
107
 * @property string $LastEdited Date and time of DataObject's last modification.
108
 * @property string $Created Date and time of DataObject creation.
109
 * @property string $ObsoleteClassName If ClassName no longer exists this will be set to the legacy value
110
 */
111
class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider, Resettable
112
{
113
114
    /**
115
     * Human-readable singular name.
116
     * @var string
117
     * @config
118
     */
119
    private static $singular_name = null;
120
121
    /**
122
     * Human-readable plural name
123
     * @var string
124
     * @config
125
     */
126
    private static $plural_name = null;
127
128
    /**
129
     * Allow API access to this object?
130
     * @todo Define the options that can be set here
131
     * @config
132
     */
133
    private static $api_access = false;
134
135
    /**
136
     * Allows specification of a default value for the ClassName field.
137
     * Configure this value only in subclasses of DataObject.
138
     *
139
     * @config
140
     * @var string
141
     */
142
    private static $default_classname = null;
143
144
    /**
145
     * @deprecated 4.0.0:5.0.0
146
     * @var bool
147
     */
148
    public $destroyed = false;
149
150
    /**
151
     * Data stored in this objects database record. An array indexed by fieldname.
152
     *
153
     * Use {@link toMap()} if you want an array representation
154
     * of this object, as the $record array might contain lazy loaded field aliases.
155
     *
156
     * @var array
157
     */
158
    protected $record;
159
160
    /**
161
     * If selected through a many_many through relation, this is the instance of the through record
162
     *
163
     * @var DataObject
164
     */
165
    protected $joinRecord;
166
167
    /**
168
     * Represents a field that hasn't changed (before === after, thus before == after)
169
     */
170
    const CHANGE_NONE = 0;
171
172
    /**
173
     * Represents a field that has changed type, although not the loosely defined value.
174
     * (before !== after && before == after)
175
     * E.g. change 1 to true or "true" to true, but not true to 0.
176
     * Value changes are by nature also considered strict changes.
177
     */
178
    const CHANGE_STRICT = 1;
179
180
    /**
181
     * Represents a field that has changed the loosely defined value
182
     * (before != after, thus, before !== after))
183
     * E.g. change false to true, but not false to 0
184
     */
185
    const CHANGE_VALUE = 2;
186
187
    /**
188
     * Value for 2nd argument to constructor, indicating that a new record is being created
189
     * Setters will be called on fields passed, and defaults will be populated
190
     */
191
    const CREATE_OBJECT = 0;
192
193
    /**
194
     * Value for 2nd argument to constructor, indicating that a record is a singleton representing the whole type,
195
     * e.g. to call requireTable() in dev/build
196
     * Defaults will not be populated and data passed will be ignored
197
     */
198
    const CREATE_SINGLETON = 1;
199
200
    /**
201
     * Value for 2nd argument to constructor, indicating that a record is being hydrated from the database
202
     * Setter methods are not called, and population via private static $defaults will not occur.
203
     */
204
    const CREATE_HYDRATED = 2;
205
206
    /**
207
     * Value for 2nd argument to constructor, indicating that a record is being hydrated from memory. This can be used
208
     * to initialised a record that doesn't yet have an ID. Setter methods are not called, and population via private
209
     * static $defaults will not occur.
210
     */
211
    const CREATE_MEMORY_HYDRATED = 3;
212
213
    /**
214
     * An array indexed by fieldname, true if the field has been changed.
215
     * Use {@link getChangedFields()} and {@link isChanged()} to inspect
216
     * the changed state.
217
     *
218
     * @var array
219
     */
220
    private $changed = [];
221
222
    /**
223
     * A flag to indicate that a "strict" change of the entire record been forced
224
     * Use {@link getChangedFields()} and {@link isChanged()} to inspect
225
     * the changed state.
226
     *
227
     * @var boolean
228
     */
229
    private $changeForced = false;
230
231
    /**
232
     * The database record (in the same format as $record), before
233
     * any changes.
234
     * @var array
235
     */
236
    protected $original = [];
237
238
    /**
239
     * Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete()
240
     * @var boolean
241
     */
242
    protected $brokenOnDelete = false;
243
244
    /**
245
     * Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite()
246
     * @var boolean
247
     */
248
    protected $brokenOnWrite = false;
249
250
    /**
251
     * Should dataobjects be validated before they are written?
252
     *
253
     * Caution: Validation can contain safeguards against invalid/malicious data,
254
     * and check permission levels (e.g. on {@link Group}). Therefore it is recommended
255
     * to only disable validation for very specific use cases.
256
     *
257
     * @config
258
     * @var boolean
259
     */
260
    private static $validation_enabled = true;
261
262
    /**
263
     * Static caches used by relevant functions.
264
     *
265
     * @var array
266
     */
267
    protected static $_cache_get_one;
268
269
    /**
270
     * Cache of field labels
271
     *
272
     * @var array
273
     */
274
    protected static $_cache_field_labels = [];
275
276
    /**
277
     * Base fields which are not defined in static $db
278
     *
279
     * @config
280
     * @var array
281
     */
282
    private static $fixed_fields = [
283
        'ID' => 'PrimaryKey',
284
        'ClassName' => 'DBClassName',
285
        'LastEdited' => 'DBDatetime',
286
        'Created' => 'DBDatetime',
287
    ];
288
289
    /**
290
     * Override table name for this class. If ignored will default to FQN of class.
291
     * This option is not inheritable, and must be set on each class.
292
     * If left blank naming will default to the legacy (3.x) behaviour.
293
     *
294
     * @var string
295
     */
296
    private static $table_name = null;
297
298
    /**
299
     * Non-static relationship cache, indexed by component name.
300
     *
301
     * @var DataObject[]
302
     */
303
    protected $components = [];
304
305
    /**
306
     * Non-static cache of has_many and many_many relations that can't be written until this object is saved.
307
     *
308
     * @var UnsavedRelationList[]
309
     */
310
    protected $unsavedRelations;
311
312
    /**
313
     * List of relations that should be cascade deleted, similar to `owns`
314
     * Note: This will trigger delete on many_many objects, not only the mapping table.
315
     * For many_many through you can specify the components you want to delete separately
316
     * (many_many or has_many sub-component)
317
     *
318
     * @config
319
     * @var array
320
     */
321
    private static $cascade_deletes = [];
322
323
    /**
324
     * List of relations that should be cascade duplicate.
325
     * many_many duplications are shallow only.
326
     *
327
     * Note: If duplicating a many_many through you should refer to the
328
     * has_many intermediary relation instead, otherwise extra fields
329
     * will be omitted from the duplicated relation.
330
     *
331
     * @var array
332
     */
333
    private static $cascade_duplicates = [];
334
335
    /**
336
     * Get schema object
337
     *
338
     * @return DataObjectSchema
339
     */
340
    public static function getSchema()
341
    {
342
        return Injector::inst()->get(DataObjectSchema::class);
343
    }
344
345
    /**
346
     * Construct a new DataObject.
347
     *
348
     * @param array $record Initial record content, or rehydrated record content, depending on $creationType
349
     * @param int|boolean $creationType Set to DataObject::CREATE_OBJECT, DataObject::CREATE_HYDRATED,
350
     *   DataObject::CREATE_MEMORY_HYDRATED or DataObject::CREATE_SINGLETON. Used by Silverstripe internals and best
351
     *   left as the default by regular users.
352
     * @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects.
353
     */
354
    public function __construct($record = [], $creationType = self::CREATE_OBJECT, $queryParams = [])
355
    {
356
        parent::__construct();
357
358
        // Legacy $record default
359
        if ($record === null) {
0 ignored issues
show
introduced by
The condition $record === null is always false.
Loading history...
360
            $record = [];
361
        }
362
363
        // Legacy $isSingleton boolean
364
        if (!is_int($creationType)) {
365
            if (!is_bool($creationType)) {
0 ignored issues
show
introduced by
The condition is_bool($creationType) is always true.
Loading history...
366
                user_error('Creation type is neither boolean (old isSingleton arg) nor integer (new arg), please review your code', E_USER_WARNING);
367
            }
368
            $creationType = $creationType ? self::CREATE_SINGLETON : self::CREATE_OBJECT;
369
        }
370
371
        // Set query params on the DataObject to tell the lazy loading mechanism the context the object creation context
372
        $this->setSourceQueryParams($queryParams);
373
374
        // Set $this->record to $record, but ignore NULLs
375
        $this->record = [];
376
377
        switch ($creationType) {
378
            // Hydrate a record
379
            case self::CREATE_HYDRATED:
380
            case self::CREATE_MEMORY_HYDRATED:
381
                $this->hydrate($record, $creationType === self::CREATE_HYDRATED);
382
                break;
383
384
            // Create a new object, using the constructor argument as the initial content
385
            case self::CREATE_OBJECT:
386
                if ($record instanceof stdClass) {
0 ignored issues
show
introduced by
$record is never a sub-type of stdClass.
Loading history...
387
                    $record = (array)$record;
388
                }
389
390
                if (!is_array($record)) {
0 ignored issues
show
introduced by
The condition is_array($record) is always true.
Loading history...
391
                    if (is_object($record)) {
392
                        $passed = "an object of type '" . get_class($record) . "'";
393
                    } else {
394
                        $passed = "The value '$record'";
395
                    }
396
397
                    user_error(
398
                        "DataObject::__construct passed $passed.  It's supposed to be passed an array,"
399
                        . " taken straight from the database.  Perhaps you should use DataList::create()->First(); instead?",
400
                        E_USER_WARNING
401
                    );
402
                    $record = [];
403
                }
404
405
                // Default columns
406
                $this->record['ID'] = empty($record['ID']) ? 0 : $record['ID'];
407
                $this->record['ClassName'] = static::class;
408
                $this->record['RecordClassName'] = static::class;
409
                unset($record['ID']);
410
                $this->original = $this->record;
411
412
                $this->populateDefaults();
413
414
                // prevent populateDefaults() and setField() from marking overwritten defaults as changed
415
                $this->changed = [];
416
                $this->changeForced = false;
417
418
                // Set the data passed in the constructor, allowing for defaults and calling setters
419
                // This will mark fields as changed
420
                if ($record) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $record of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
421
                    $this->update($record);
422
                }
423
                break;
424
425
            case self::CREATE_SINGLETON:
426
                // No setting happens for a singleton
427
                $this->record['ID'] = 0;
428
                $this->record['ClassName'] = static::class;
429
                $this->record['RecordClassName'] = static::class;
430
                $this->original = $this->record;
431
                $this->changed = [];
432
                $this->changeForced = false;
433
                break;
434
435
            default:
436
                throw new \LogicException('Bad creationType ' . $this->creationType);
0 ignored issues
show
Bug Best Practice introduced by
The property creationType does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
437
        }
438
    }
439
440
    /**
441
     * Constructor hydration logic for CREATE_HYDRATED and CREATE_MEMORY_HYDRATED.
442
     * @param array $record
443
     * @param bool $mustHaveID If true, an exception will be thrown if $record doesn't have an ID.
444
     */
445
    private function hydrate(array $record, bool $mustHaveID)
446
    {
447
        if ($mustHaveID && empty($record['ID'])) {
448
            // CREATE_HYDRATED requires an ID to be included in the record
449
            throw new \InvalidArgumentException(
450
                "Hydrated records must be passed a record array including an ID."
451
            );
452
        } elseif (empty($record['ID'])) {
453
            // CREATE_MEMORY_HYDRATED implicitely set the record ID to 0 if not provided
454
            $record['ID'] = 0;
455
        }
456
457
        $this->record = $record;
458
459
        // Identify fields that should be lazy loaded, but only on existing records
460
        // Get all field specs scoped to class for later lazy loading
461
        $fields = static::getSchema()->fieldSpecs(
462
            static::class,
463
            DataObjectSchema::INCLUDE_CLASS | DataObjectSchema::DB_ONLY
464
        );
465
        foreach ($fields as $field => $fieldSpec) {
466
            $fieldClass = strtok($fieldSpec, ".");
467
            if (!array_key_exists($field, $record)) {
468
                $this->record[$field . '_Lazy'] = $fieldClass;
469
            }
470
        }
471
472
        $this->original = $this->record;
473
        $this->changed = [];
474
        $this->changeForced = false;
475
    }
476
477
    /**
478
     * Destroy all of this objects dependant objects and local caches.
479
     * You'll need to call this to get the memory of an object that has components or extensions freed.
480
     */
481
    public function destroy()
482
    {
483
        $this->flushCache(false);
484
    }
485
486
    /**
487
     * Create a duplicate of this node. Can duplicate many_many relations
488
     *
489
     * @param bool $doWrite Perform a write() operation before returning the object.
490
     * If this is true, it will create the duplicate in the database.
491
     * @param array|null|false $relations List of relations to duplicate.
492
     * Will default to `cascade_duplicates` if null.
493
     * Set to 'false' to force none.
494
     * Set to specific array of names to duplicate to override these.
495
     * Note: If using versioned, this will additionally failover to `owns` config.
496
     * @return static A duplicate of this node. The exact type will be the type of this node.
497
     */
498
    public function duplicate($doWrite = true, $relations = null)
499
    {
500
        // Handle legacy behaviour
501
        if (is_string($relations) || $relations === true) {
0 ignored issues
show
introduced by
The condition $relations === true is always false.
Loading history...
502
            if ($relations === true) {
503
                $relations = 'many_many';
504
            }
505
            Deprecation::notice('5.0', 'Use cascade_duplicates config instead of providing a string to duplicate()');
506
            $relations = array_keys($this->config()->get($relations)) ?: [];
507
        }
508
509
        // Get duplicates
510
        if ($relations === null) {
511
            $relations = $this->config()->get('cascade_duplicates');
512
            // Remove any duplicate entries before duplicating them
513
            if (is_array($relations)) {
514
                $relations = array_unique($relations);
515
            }
516
        }
517
518
        // Create unsaved raw duplicate
519
        $map = $this->toMap();
520
        unset($map['Created']);
521
        /** @var static $clone */
522
        $clone = Injector::inst()->create(static::class, $map, false, $this->getSourceQueryParams());
523
        $clone->ID = 0;
524
525
        // Note: Extensions such as versioned may update $relations here
526
        $clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite, $relations);
527
        if ($relations) {
528
            $this->duplicateRelations($this, $clone, $relations);
529
        }
530
        if ($doWrite) {
531
            $clone->write();
532
        }
533
        $clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite, $relations);
534
535
        return $clone;
536
    }
537
538
    /**
539
     * Copies the given relations from this object to the destination
540
     *
541
     * @param DataObject $sourceObject the source object to duplicate from
542
     * @param DataObject $destinationObject the destination object to populate with the duplicated relations
543
     * @param array $relations List of relations
544
     */
545
    protected function duplicateRelations($sourceObject, $destinationObject, $relations)
546
    {
547
        // Get list of duplicable relation types
548
        $manyMany = $sourceObject->manyMany();
549
        $hasMany = $sourceObject->hasMany();
550
        $hasOne = $sourceObject->hasOne();
551
        $belongsTo = $sourceObject->belongsTo();
552
553
        // Duplicate each relation based on type
554
        foreach ($relations as $relation) {
555
            switch (true) {
556
                case array_key_exists($relation, $manyMany): {
557
                    $this->duplicateManyManyRelation($sourceObject, $destinationObject, $relation);
558
                    break;
559
                }
560
                case array_key_exists($relation, $hasMany): {
561
                    $this->duplicateHasManyRelation($sourceObject, $destinationObject, $relation);
562
                    break;
563
                }
564
                case array_key_exists($relation, $hasOne): {
565
                    $this->duplicateHasOneRelation($sourceObject, $destinationObject, $relation);
566
                    break;
567
                }
568
                case array_key_exists($relation, $belongsTo): {
569
                    $this->duplicateBelongsToRelation($sourceObject, $destinationObject, $relation);
570
                    break;
571
                }
572
                default: {
573
                    $sourceType = get_class($sourceObject);
574
                    throw new InvalidArgumentException(
575
                        "Cannot duplicate unknown relation {$relation} on parent type {$sourceType}"
576
                    );
577
                }
578
            }
579
        }
580
    }
581
582
    /**
583
     * Copies the many_many and belongs_many_many relations from one object to another instance of the name of object.
584
     *
585
     * @deprecated 4.1.0:5.0.0 Use duplicateRelations() instead
586
     * @param DataObject $sourceObject the source object to duplicate from
587
     * @param DataObject $destinationObject the destination object to populate with the duplicated relations
588
     * @param bool|string $filter
589
     */
590
    protected function duplicateManyManyRelations($sourceObject, $destinationObject, $filter)
591
    {
592
        Deprecation::notice('5.0', 'Use duplicateRelations() instead');
593
594
        // Get list of relations to duplicate
595
        if ($filter === 'many_many' || $filter === 'belongs_many_many') {
596
            $relations = $sourceObject->config()->get($filter);
597
        } elseif ($filter === true) {
598
            $relations = $sourceObject->manyMany();
599
        } else {
600
            throw new InvalidArgumentException("Invalid many_many duplication filter");
601
        }
602
        foreach ($relations as $manyManyName => $type) {
603
            $this->duplicateManyManyRelation($sourceObject, $destinationObject, $manyManyName);
604
        }
605
    }
606
607
    /**
608
     * Duplicates a single many_many relation from one object to another.
609
     *
610
     * @param DataObject $sourceObject
611
     * @param DataObject $destinationObject
612
     * @param string $relation
613
     */
614
    protected function duplicateManyManyRelation($sourceObject, $destinationObject, $relation)
615
    {
616
        // Copy all components from source to destination
617
        $source = $sourceObject->getManyManyComponents($relation);
618
        $dest = $destinationObject->getManyManyComponents($relation);
619
620
        if ($source instanceof ManyManyList) {
621
            $extraFieldNames = $source->getExtraFields();
622
        } else {
623
            $extraFieldNames = [];
624
        }
625
626
        foreach ($source as $item) {
627
            // Merge extra fields
628
            $extraFields = [];
629
            foreach ($extraFieldNames as $fieldName => $fieldType) {
630
                $extraFields[$fieldName] = $item->getField($fieldName);
631
            }
632
            $dest->add($item, $extraFields);
633
        }
634
    }
635
636
    /**
637
     * Duplicates a single many_many relation from one object to another.
638
     *
639
     * @param DataObject $sourceObject
640
     * @param DataObject $destinationObject
641
     * @param string $relation
642
     */
643
    protected function duplicateHasManyRelation($sourceObject, $destinationObject, $relation)
644
    {
645
        // Copy all components from source to destination
646
        $source = $sourceObject->getComponents($relation);
647
        $dest = $destinationObject->getComponents($relation);
648
649
        /** @var DataObject $item */
650
        foreach ($source as $item) {
651
            // Don't write on duplicate; Wait until ParentID is available later.
652
            // writeRelations() will eventually write these records when converting
653
            // from UnsavedRelationList
654
            $clonedItem = $item->duplicate(false);
655
            $dest->add($clonedItem);
656
        }
657
    }
658
659
    /**
660
     * Duplicates a single has_one relation from one object to another.
661
     * Note: Child object will be force written.
662
     *
663
     * @param DataObject $sourceObject
664
     * @param DataObject $destinationObject
665
     * @param string $relation
666
     */
667
    protected function duplicateHasOneRelation($sourceObject, $destinationObject, $relation)
668
    {
669
        // Check if original object exists
670
        $item = $sourceObject->getComponent($relation);
671
        if (!$item->isInDB()) {
672
            return;
673
        }
674
675
        $clonedItem = $item->duplicate(false);
676
        $destinationObject->setComponent($relation, $clonedItem);
677
    }
678
679
    /**
680
     * Duplicates a single belongs_to relation from one object to another.
681
     * Note: This will force a write on both parent / child objects.
682
     *
683
     * @param DataObject $sourceObject
684
     * @param DataObject $destinationObject
685
     * @param string $relation
686
     */
687
    protected function duplicateBelongsToRelation($sourceObject, $destinationObject, $relation)
688
    {
689
        // Check if original object exists
690
        $item = $sourceObject->getComponent($relation);
691
        if (!$item->isInDB()) {
692
            return;
693
        }
694
695
        $clonedItem = $item->duplicate(false);
696
        $destinationObject->setComponent($relation, $clonedItem);
697
        // After $clonedItem is assigned the appropriate FieldID / FieldClass, force write
698
        // @todo Write this component in onAfterWrite instead, assigning the FieldID then
699
        // https://github.com/silverstripe/silverstripe-framework/issues/7818
700
        $clonedItem->write();
701
    }
702
703
    /**
704
     * Return obsolete class name, if this is no longer a valid class
705
     *
706
     * @return string
707
     */
708
    public function getObsoleteClassName()
709
    {
710
        $className = $this->getField("ClassName");
711
        if (!ClassInfo::exists($className)) {
712
            return $className;
713
        }
714
        return null;
715
    }
716
717
    /**
718
     * Gets name of this class
719
     *
720
     * @return string
721
     */
722
    public function getClassName()
723
    {
724
        $className = $this->getField("ClassName");
725
        if (!ClassInfo::exists($className)) {
726
            return static::class;
727
        }
728
        return $className;
729
    }
730
731
    /**
732
     * Set the ClassName attribute. {@link $class} is also updated.
733
     * Warning: This will produce an inconsistent record, as the object
734
     * instance will not automatically switch to the new subclass.
735
     * Please use {@link newClassInstance()} for this purpose,
736
     * or destroy and reinstanciate the record.
737
     *
738
     * @param string $className The new ClassName attribute (a subclass of {@link DataObject})
739
     * @return $this
740
     */
741
    public function setClassName($className)
742
    {
743
        $className = trim($className);
744
        if (!$className || !is_subclass_of($className, self::class)) {
745
            return $this;
746
        }
747
748
        $this->setField("ClassName", $className);
749
        $this->setField('RecordClassName', $className);
750
        return $this;
751
    }
752
753
    /**
754
     * Create a new instance of a different class from this object's record.
755
     * This is useful when dynamically changing the type of an instance. Specifically,
756
     * it ensures that the instance of the class is a match for the className of the
757
     * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName}
758
     * property manually before calling this method, as it will confuse change detection.
759
     *
760
     * If the new class is different to the original class, defaults are populated again
761
     * because this will only occur automatically on instantiation of a DataObject if
762
     * there is no record, or the record has no ID. In this case, we do have an ID but
763
     * we still need to repopulate the defaults.
764
     *
765
     * @param string $newClassName The name of the new class
766
     *
767
     * @return DataObject The new instance of the new class, The exact type will be of the class name provided.
768
     */
769
    public function newClassInstance($newClassName)
770
    {
771
        if (!is_subclass_of($newClassName, self::class)) {
772
            throw new InvalidArgumentException("$newClassName is not a valid subclass of DataObject");
773
        }
774
775
        $originalClass = $this->ClassName;
776
777
        /** @var DataObject $newInstance */
778
        $newInstance = Injector::inst()->create($newClassName, $this->record, self::CREATE_MEMORY_HYDRATED);
779
780
        // Modify ClassName
781
        if ($newClassName != $originalClass) {
782
            $newInstance->setClassName($newClassName);
783
            $newInstance->populateDefaults();
784
            $newInstance->forceChange();
785
        }
786
787
        return $newInstance;
788
    }
789
790
    /**
791
     * Adds methods from the extensions.
792
     * Called by Object::__construct() once per class.
793
     */
794
    public function defineMethods()
795
    {
796
        parent::defineMethods();
797
798
        if (static::class === self::class) {
0 ignored issues
show
introduced by
The condition static::class === self::class is always true.
Loading history...
799
            return;
800
        }
801
802
        // Set up accessors for joined items
803
        if ($manyMany = $this->manyMany()) {
804
            foreach ($manyMany as $relationship => $class) {
805
                $this->addWrapperMethod($relationship, 'getManyManyComponents');
806
            }
807
        }
808
        if ($hasMany = $this->hasMany()) {
809
            foreach ($hasMany as $relationship => $class) {
810
                $this->addWrapperMethod($relationship, 'getComponents');
811
            }
812
        }
813
        if ($hasOne = $this->hasOne()) {
814
            foreach ($hasOne as $relationship => $class) {
815
                $this->addWrapperMethod($relationship, 'getComponent');
816
            }
817
        }
818
        if ($belongsTo = $this->belongsTo()) {
819
            foreach (array_keys($belongsTo) as $relationship) {
820
                $this->addWrapperMethod($relationship, 'getComponent');
821
            }
822
        }
823
    }
824
825
    /**
826
     * Returns true if this object "exists", i.e., has a sensible value.
827
     * The default behaviour for a DataObject is to return true if
828
     * the object exists in the database, you can override this in subclasses.
829
     *
830
     * @return boolean true if this object exists
831
     */
832
    public function exists()
833
    {
834
        return (isset($this->record['ID']) && $this->record['ID'] > 0);
835
    }
836
837
    /**
838
     * Returns TRUE if all values (other than "ID") are
839
     * considered empty (by weak boolean comparison).
840
     *
841
     * @return boolean
842
     */
843
    public function isEmpty()
844
    {
845
        $fixed = DataObject::config()->uninherited('fixed_fields');
846
        foreach ($this->toMap() as $field => $value) {
847
            // only look at custom fields
848
            if (isset($fixed[$field])) {
849
                continue;
850
            }
851
852
            $dbObject = $this->dbObject($field);
853
            if (!$dbObject) {
854
                continue;
855
            }
856
            if ($dbObject->exists()) {
857
                return false;
858
            }
859
        }
860
        return true;
861
    }
862
863
    /**
864
     * Pluralise this item given a specific count.
865
     *
866
     * E.g. "0 Pages", "1 File", "3 Images"
867
     *
868
     * @param string $count
869
     * @return string
870
     */
871
    public function i18n_pluralise($count)
872
    {
873
        $default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name();
874
        return i18n::_t(
875
            static::class . '.PLURALS',
876
            $default,
877
            ['count' => $count]
878
        );
879
    }
880
881
    /**
882
     * Get the user friendly singular name of this DataObject.
883
     * If the name is not defined (by redefining $singular_name in the subclass),
884
     * this returns the class name.
885
     *
886
     * @return string User friendly singular name of this DataObject
887
     */
888
    public function singular_name()
889
    {
890
        $name = $this->config()->get('singular_name');
891
        if ($name) {
892
            return $name;
893
        }
894
        return ucwords(trim(strtolower(preg_replace(
895
            '/_?([A-Z])/',
896
            ' $1',
897
            ClassInfo::shortName($this)
898
        ))));
899
    }
900
901
    /**
902
     * Get the translated user friendly singular name of this DataObject
903
     * same as singular_name() but runs it through the translating function
904
     *
905
     * Translating string is in the form:
906
     *     $this->class.SINGULARNAME
907
     * Example:
908
     *     Page.SINGULARNAME
909
     *
910
     * @return string User friendly translated singular name of this DataObject
911
     */
912
    public function i18n_singular_name()
913
    {
914
        return _t(static::class . '.SINGULARNAME', $this->singular_name());
915
    }
916
917
    /**
918
     * Get the user friendly plural name of this DataObject
919
     * If the name is not defined (by renaming $plural_name in the subclass),
920
     * this returns a pluralised version of the class name.
921
     *
922
     * @return string User friendly plural name of this DataObject
923
     */
924
    public function plural_name()
925
    {
926
        if ($name = $this->config()->get('plural_name')) {
927
            return $name;
928
        }
929
        $name = $this->singular_name();
930
        //if the penultimate character is not a vowel, replace "y" with "ies"
931
        if (preg_match('/[^aeiou]y$/i', $name)) {
932
            $name = substr($name, 0, -1) . 'ie';
933
        }
934
        return ucfirst($name . 's');
935
    }
936
937
    /**
938
     * Get the translated user friendly plural name of this DataObject
939
     * Same as plural_name but runs it through the translation function
940
     * Translation string is in the form:
941
     *      $this->class.PLURALNAME
942
     * Example:
943
     *      Page.PLURALNAME
944
     *
945
     * @return string User friendly translated plural name of this DataObject
946
     */
947
    public function i18n_plural_name()
948
    {
949
        return _t(static::class . '.PLURALNAME', $this->plural_name());
950
    }
951
952
    /**
953
     * Standard implementation of a title/label for a specific
954
     * record. Tries to find properties 'Title' or 'Name',
955
     * and falls back to the 'ID'. Useful to provide
956
     * user-friendly identification of a record, e.g. in errormessages
957
     * or UI-selections.
958
     *
959
     * Overload this method to have a more specialized implementation,
960
     * e.g. for an Address record this could be:
961
     * <code>
962
     * function getTitle() {
963
     *   return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
964
     * }
965
     * </code>
966
     *
967
     * @return string
968
     */
969
    public function getTitle()
970
    {
971
        $schema = static::getSchema();
972
        if ($schema->fieldSpec($this, 'Title')) {
973
            return $this->getField('Title');
974
        }
975
        if ($schema->fieldSpec($this, 'Name')) {
976
            return $this->getField('Name');
977
        }
978
979
        return "#{$this->ID}";
980
    }
981
982
    /**
983
     * Returns the associated database record - in this case, the object itself.
984
     * This is included so that you can call $dataOrController->data() and get a DataObject all the time.
985
     *
986
     * @return DataObject Associated database record
987
     */
988
    public function data()
989
    {
990
        return $this;
991
    }
992
993
    /**
994
     * Convert this object to a map.
995
     * Note that it has the following quirks:
996
     *  - custom getters, including those that adjust the result of database fields, won't be executed
997
     *  - NULL values won't be returned.
998
     *
999
     * @return array The data as a map.
1000
     */
1001
    public function toMap()
1002
    {
1003
        $this->loadLazyFields();
1004
        return array_filter($this->record, function ($val) {
1005
            return $val !== null;
1006
        });
1007
    }
1008
1009
    /**
1010
     * Return all currently fetched database fields.
1011
     *
1012
     * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
1013
     * Obviously, this makes it a lot faster.
1014
     *
1015
     * @return array The data as a map.
1016
     */
1017
    public function getQueriedDatabaseFields()
1018
    {
1019
        return $this->record;
1020
    }
1021
1022
    /**
1023
     * Update a number of fields on this object, given a map of the desired changes.
1024
     *
1025
     * The field names can be simple names, or you can use a dot syntax to access $has_one relations.
1026
     * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
1027
     *
1028
     * Doesn't write the main object, but if you use the dot syntax, it will write()
1029
     * the related objects that it alters.
1030
     *
1031
     * When using this method with user supplied data, it's very important to
1032
     * whitelist the allowed keys.
1033
     *
1034
     * @param array $data A map of field name to data values to update.
1035
     * @return DataObject $this
1036
     */
1037
    public function update($data)
1038
    {
1039
        foreach ($data as $key => $value) {
1040
            // Implement dot syntax for updates
1041
            if (strpos($key, '.') !== false) {
1042
                $relations = explode('.', $key);
1043
                $fieldName = array_pop($relations);
1044
                /** @var static $relObj */
1045
                $relObj = $this;
1046
                $relation = null;
1047
                foreach ($relations as $i => $relation) {
1048
                    // no support for has_many or many_many relationships,
1049
                    // as the updater wouldn't know which object to write to (or create)
1050
                    if ($relObj->$relation() instanceof DataObject) {
1051
                        $parentObj = $relObj;
1052
                        $relObj = $relObj->$relation();
1053
                        // If the intermediate relationship objects haven't been created, then write them
1054
                        if ($i < sizeof($relations) - 1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($i < sizeof($relations)...&& $parentObj !== $this, Probably Intended Meaning: $i < sizeof($relations) ...& $parentObj !== $this)
Loading history...
1055
                            $relObj->write();
1056
                            $relatedFieldName = $relation . "ID";
1057
                            $parentObj->$relatedFieldName = $relObj->ID;
1058
                            $parentObj->write();
1059
                        }
1060
                    } else {
1061
                        user_error(
1062
                            "DataObject::update(): Can't traverse relationship '$relation'," .
1063
                            "it has to be a has_one relationship or return a single DataObject",
1064
                            E_USER_NOTICE
1065
                        );
1066
                        // unset relation object so we don't write properties to the wrong object
1067
                        $relObj = null;
1068
                        break;
1069
                    }
1070
                }
1071
1072
                if ($relObj) {
1073
                    $relObj->$fieldName = $value;
1074
                    $relObj->write();
1075
                    $relatedFieldName = $relation . "ID";
1076
                    $this->$relatedFieldName = $relObj->ID;
1077
                    $relObj->flushCache();
1078
                } else {
1079
                    $class = static::class;
1080
                    user_error("Couldn't follow dot syntax '{$key}' on '{$class}' object", E_USER_WARNING);
1081
                }
1082
            } else {
1083
                $this->$key = $value;
1084
            }
1085
        }
1086
        return $this;
1087
    }
1088
1089
    /**
1090
     * Pass changes as a map, and try to
1091
     * get automatic casting for these fields.
1092
     * Doesn't write to the database. To write the data,
1093
     * use the write() method.
1094
     *
1095
     * @param array $data A map of field name to data values to update.
1096
     * @return DataObject $this
1097
     */
1098
    public function castedUpdate($data)
1099
    {
1100
        foreach ($data as $k => $v) {
1101
            $this->setCastedField($k, $v);
1102
        }
1103
        return $this;
1104
    }
1105
1106
    /**
1107
     * Merges data and relations from another object of same class,
1108
     * without conflict resolution. Allows to specify which
1109
     * dataset takes priority in case its not empty.
1110
     * has_one-relations are just transferred with priority 'right'.
1111
     * has_many and many_many-relations are added regardless of priority.
1112
     *
1113
     * Caution: has_many/many_many relations are moved rather than duplicated,
1114
     * meaning they are not connected to the merged object any longer.
1115
     * Caution: Just saves updated has_many/many_many relations to the database,
1116
     * doesn't write the updated object itself (just writes the object-properties).
1117
     * Caution: Does not delete the merged object.
1118
     * Caution: Does now overwrite Created date on the original object.
1119
     *
1120
     * @param DataObject $rightObj
1121
     * @param string $priority left|right Determines who wins in case of a conflict (optional)
1122
     * @param bool $includeRelations Merge any existing relations (optional)
1123
     * @param bool $overwriteWithEmpty Overwrite existing left values with empty right values.
1124
     *                            Only applicable with $priority='right'. (optional)
1125
     * @return Boolean
1126
     */
1127
    public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false)
1128
    {
1129
        $leftObj = $this;
1130
1131
        if ($leftObj->ClassName != $rightObj->ClassName) {
1132
            // we can't merge similiar subclasses because they might have additional relations
1133
            user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
1134
			(expected '{$leftObj->ClassName}').", E_USER_WARNING);
1135
            return false;
1136
        }
1137
1138
        if (!$rightObj->ID) {
1139
            user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
1140
				to make sure all relations are transferred properly.').", E_USER_WARNING);
1141
            return false;
1142
        }
1143
1144
        // makes sure we don't merge data like ID or ClassName
1145
        $rightData = DataObject::getSchema()->fieldSpecs(get_class($rightObj));
1146
        foreach ($rightData as $key => $rightSpec) {
1147
            // Don't merge ID
1148
            if ($key === 'ID') {
1149
                continue;
1150
            }
1151
1152
            // Only merge relations if allowed
1153
            if ($rightSpec === 'ForeignKey' && !$includeRelations) {
1154
                continue;
1155
            }
1156
1157
            // don't merge conflicting values if priority is 'left'
1158
            if ($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) {
1159
                continue;
1160
            }
1161
1162
            // don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
1163
            if ($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) {
1164
                continue;
1165
            }
1166
1167
            // TODO remove redundant merge of has_one fields
1168
            $leftObj->{$key} = $rightObj->{$key};
1169
        }
1170
1171
        // merge relations
1172
        if ($includeRelations) {
1173
            if ($manyMany = $this->manyMany()) {
1174
                foreach ($manyMany as $relationship => $class) {
1175
                    /** @var DataObject $leftComponents */
1176
                    $leftComponents = $leftObj->getManyManyComponents($relationship);
1177
                    $rightComponents = $rightObj->getManyManyComponents($relationship);
1178
                    if ($rightComponents && $rightComponents->exists()) {
1179
                        $leftComponents->addMany($rightComponents->column('ID'));
0 ignored issues
show
Bug introduced by
The method addMany() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1179
                        $leftComponents->/** @scrutinizer ignore-call */ 
1180
                                         addMany($rightComponents->column('ID'));
Loading history...
1180
                    }
1181
                    $leftComponents->write();
1182
                }
1183
            }
1184
1185
            if ($hasMany = $this->hasMany()) {
1186
                foreach ($hasMany as $relationship => $class) {
1187
                    $leftComponents = $leftObj->getComponents($relationship);
1188
                    $rightComponents = $rightObj->getComponents($relationship);
1189
                    if ($rightComponents && $rightComponents->exists()) {
1190
                        $leftComponents->addMany($rightComponents->column('ID'));
1191
                    }
1192
                    $leftComponents->write();
0 ignored issues
show
Bug introduced by
The method write() does not exist on SilverStripe\ORM\UnsavedRelationList. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1192
                    $leftComponents->/** @scrutinizer ignore-call */ 
1193
                                     write();
Loading history...
Bug introduced by
The method write() does not exist on SilverStripe\ORM\HasManyList. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1192
                    $leftComponents->/** @scrutinizer ignore-call */ 
1193
                                     write();
Loading history...
1193
                }
1194
            }
1195
        }
1196
1197
        return true;
1198
    }
1199
1200
    /**
1201
     * Forces the record to think that all its data has changed.
1202
     * Doesn't write to the database. Force-change preseved until
1203
     * next write. Existing CHANGE_VALUE or CHANGE_STRICT values
1204
     * are preserved.
1205
     *
1206
     * @return $this
1207
     */
1208
    public function forceChange()
1209
    {
1210
        // Ensure lazy fields loaded
1211
        $this->loadLazyFields();
1212
1213
        // Populate the null values in record so that they actually get written
1214
        foreach (array_keys(static::getSchema()->fieldSpecs(static::class)) as $fieldName) {
1215
            if (!isset($this->record[$fieldName])) {
1216
                $this->record[$fieldName] = null;
1217
            }
1218
        }
1219
1220
        $this->changeForced = true;
1221
1222
        return $this;
1223
    }
1224
1225
    /**
1226
     * Validate the current object.
1227
     *
1228
     * By default, there is no validation - objects are always valid!  However, you can overload this method in your
1229
     * DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
1230
     *
1231
     * Invalid objects won't be able to be written - a warning will be thrown and no write will occur.  onBeforeWrite()
1232
     * and onAfterWrite() won't get called either.
1233
     *
1234
     * It is expected that you call validate() in your own application to test that an object is valid before
1235
     * attempting a write, and respond appropriately if it isn't.
1236
     *
1237
     * @see {@link ValidationResult}
1238
     * @return ValidationResult
1239
     */
1240
    public function validate()
1241
    {
1242
        $result = ValidationResult::create();
1243
        $this->extend('validate', $result);
1244
        return $result;
1245
    }
1246
1247
    /**
1248
     * Public accessor for {@see DataObject::validate()}
1249
     *
1250
     * @return ValidationResult
1251
     */
1252
    public function doValidate()
1253
    {
1254
        Deprecation::notice('5.0', 'Use validate');
1255
        return $this->validate();
1256
    }
1257
1258
    /**
1259
     * Event handler called before writing to the database.
1260
     * You can overload this to clean up or otherwise process data before writing it to the
1261
     * database.  Don't forget to call parent::onBeforeWrite(), though!
1262
     *
1263
     * This called after {@link $this->validate()}, so you can be sure that your data is valid.
1264
     *
1265
     * @uses DataExtension::onBeforeWrite()
1266
     */
1267
    protected function onBeforeWrite()
1268
    {
1269
        $this->brokenOnWrite = false;
1270
1271
        $dummy = null;
1272
        $this->extend('onBeforeWrite', $dummy);
1273
    }
1274
1275
    /**
1276
     * Event handler called after writing to the database.
1277
     * You can overload this to act upon changes made to the data after it is written.
1278
     * $this->changed will have a record
1279
     * database.  Don't forget to call parent::onAfterWrite(), though!
1280
     *
1281
     * @uses DataExtension::onAfterWrite()
1282
     */
1283
    protected function onAfterWrite()
1284
    {
1285
        $dummy = null;
1286
        $this->extend('onAfterWrite', $dummy);
1287
    }
1288
1289
    /**
1290
     * Find all objects that will be cascade deleted if this object is deleted
1291
     *
1292
     * Notes:
1293
     *   - If this object is versioned, objects will only be searched in the same stage as the given record.
1294
     *   - This will only be useful prior to deletion, as post-deletion this record will no longer exist.
1295
     *
1296
     * @param bool $recursive True if recursive
1297
     * @param ArrayList $list Optional list to add items to
1298
     * @return ArrayList list of objects
1299
     */
1300
    public function findCascadeDeletes($recursive = true, $list = null)
1301
    {
1302
        // Find objects in these relationships
1303
        return $this->findRelatedObjects('cascade_deletes', $recursive, $list);
1304
    }
1305
1306
    /**
1307
     * Event handler called before deleting from the database.
1308
     * You can overload this to clean up or otherwise process data before delete this
1309
     * record.  Don't forget to call parent::onBeforeDelete(), though!
1310
     *
1311
     * @uses DataExtension::onBeforeDelete()
1312
     */
1313
    protected function onBeforeDelete()
1314
    {
1315
        $this->brokenOnDelete = false;
1316
1317
        $dummy = null;
1318
        $this->extend('onBeforeDelete', $dummy);
1319
1320
        // Cascade deletes
1321
        $deletes = $this->findCascadeDeletes(false);
1322
        foreach ($deletes as $delete) {
1323
            $delete->delete();
1324
        }
1325
    }
1326
1327
    protected function onAfterDelete()
1328
    {
1329
        $this->extend('onAfterDelete');
1330
    }
1331
1332
    /**
1333
     * Load the default values in from the self::$defaults array.
1334
     * Will traverse the defaults of the current class and all its parent classes.
1335
     * Called by the constructor when creating new records.
1336
     *
1337
     * @uses DataExtension::populateDefaults()
1338
     * @return DataObject $this
1339
     */
1340
    public function populateDefaults()
1341
    {
1342
        $classes = array_reverse(ClassInfo::ancestry($this));
1343
1344
        foreach ($classes as $class) {
1345
            $defaults = Config::inst()->get($class, 'defaults', Config::UNINHERITED);
1346
1347
            if ($defaults && !is_array($defaults)) {
1348
                user_error(
1349
                    "Bad '" . static::class . "' defaults given: " . var_export($defaults, true),
1350
                    E_USER_WARNING
1351
                );
1352
                $defaults = null;
1353
            }
1354
1355
            if ($defaults) {
1356
                foreach ($defaults as $fieldName => $fieldValue) {
1357
                    // SRM 2007-03-06: Stricter check
1358
                    if (!isset($this->$fieldName) || $this->$fieldName === null) {
1359
                        $this->$fieldName = $fieldValue;
1360
                    }
1361
                    // Set many-many defaults with an array of ids
1362
                    if (is_array($fieldValue) && $this->getSchema()->manyManyComponent(static::class, $fieldName)) {
1363
                        /** @var ManyManyList $manyManyJoin */
1364
                        $manyManyJoin = $this->$fieldName();
1365
                        $manyManyJoin->setByIDList($fieldValue);
1366
                    }
1367
                }
1368
            }
1369
            if ($class == self::class) {
1370
                break;
1371
            }
1372
        }
1373
1374
        $this->extend('populateDefaults');
1375
        return $this;
1376
    }
1377
1378
    /**
1379
     * Determine validation of this object prior to write
1380
     *
1381
     * @return ValidationException Exception generated by this write, or null if valid
1382
     */
1383
    protected function validateWrite()
1384
    {
1385
        if ($this->ObsoleteClassName) {
1386
            return new ValidationException(
1387
                "Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " .
1388
                "you need to change the ClassName before you can write it"
1389
            );
1390
        }
1391
1392
        // Note: Validation can only be disabled at the global level, not per-model
1393
        if (DataObject::config()->uninherited('validation_enabled')) {
1394
            $result = $this->validate();
1395
            if (!$result->isValid()) {
1396
                return new ValidationException($result);
1397
            }
1398
        }
1399
        return null;
1400
    }
1401
1402
    /**
1403
     * Prepare an object prior to write
1404
     *
1405
     * @throws ValidationException
1406
     */
1407
    protected function preWrite()
1408
    {
1409
        // Validate this object
1410
        if ($writeException = $this->validateWrite()) {
1411
            // Used by DODs to clean up after themselves, eg, Versioned
1412
            $this->invokeWithExtensions('onAfterSkippedWrite');
1413
            throw $writeException;
1414
        }
1415
1416
        // Check onBeforeWrite
1417
        $this->brokenOnWrite = true;
1418
        $this->onBeforeWrite();
1419
        if ($this->brokenOnWrite) {
1420
            throw new LogicException(
1421
                static::class . " has a broken onBeforeWrite() function."
1422
                . " Make sure that you call parent::onBeforeWrite()."
1423
            );
1424
        }
1425
    }
1426
1427
    /**
1428
     * Detects and updates all changes made to this object
1429
     *
1430
     * @param bool $forceChanges If set to true, force all fields to be treated as changed
1431
     * @return bool True if any changes are detected
1432
     */
1433
    protected function updateChanges($forceChanges = false)
1434
    {
1435
        if ($forceChanges) {
1436
            // Force changes, but only for loaded fields
1437
            foreach ($this->record as $field => $value) {
1438
                $this->changed[$field] = static::CHANGE_VALUE;
1439
            }
1440
            return true;
1441
        }
1442
        return $this->isChanged();
1443
    }
1444
1445
    /**
1446
     * Writes a subset of changes for a specific table to the given manipulation
1447
     *
1448
     * @param string $baseTable Base table
1449
     * @param string $now Timestamp to use for the current time
1450
     * @param bool $isNewRecord Whether this should be treated as a new record write
1451
     * @param array $manipulation Manipulation to write to
1452
     * @param string $class Class of table to manipulate
1453
     */
1454
    protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class)
1455
    {
1456
        $schema = $this->getSchema();
1457
        $table = $schema->tableName($class);
1458
        $manipulation[$table] = [];
1459
1460
        $changed = $this->getChangedFields();
1461
1462
        // Extract records for this table
1463
        foreach ($this->record as $fieldName => $fieldValue) {
1464
            // we're not attempting to reset the BaseTable->ID
1465
            // Ignore unchanged fields or attempts to reset the BaseTable->ID
1466
            if (empty($changed[$fieldName]) || ($table === $baseTable && $fieldName === 'ID')) {
1467
                continue;
1468
            }
1469
1470
            // Ensure this field pertains to this table
1471
            $specification = $schema->fieldSpec(
1472
                $class,
1473
                $fieldName,
1474
                DataObjectSchema::DB_ONLY | DataObjectSchema::UNINHERITED
1475
            );
1476
            if (!$specification) {
1477
                continue;
1478
            }
1479
1480
            // if database column doesn't correlate to a DBField instance...
1481
            $fieldObj = $this->dbObject($fieldName);
1482
            if (!$fieldObj) {
1483
                $fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
1484
            }
1485
1486
            // Write to manipulation
1487
            $fieldObj->writeToManipulation($manipulation[$table]);
1488
        }
1489
1490
        // Ensure update of Created and LastEdited columns
1491
        if ($baseTable === $table) {
1492
            $manipulation[$table]['fields']['LastEdited'] = $now;
1493
            if ($isNewRecord) {
1494
                $manipulation[$table]['fields']['Created'] = empty($this->record['Created'])
1495
                    ? $now
1496
                    : $this->record['Created'];
1497
                $manipulation[$table]['fields']['ClassName'] = static::class;
1498
            }
1499
        }
1500
1501
        // Inserts done one the base table are performed in another step, so the manipulation should instead
1502
        // attempt an update, as though it were a normal update.
1503
        $manipulation[$table]['command'] = $isNewRecord ? 'insert' : 'update';
1504
        $manipulation[$table]['class'] = $class;
1505
        if ($this->isInDB()) {
1506
            $manipulation[$table]['id'] = $this->record['ID'];
1507
        }
1508
    }
1509
1510
    /**
1511
     * Ensures that a blank base record exists with the basic fixed fields for this dataobject
1512
     *
1513
     * Does nothing if an ID is already assigned for this record
1514
     *
1515
     * @param string $baseTable Base table
1516
     * @param string $now Timestamp to use for the current time
1517
     */
1518
    protected function writeBaseRecord($baseTable, $now)
1519
    {
1520
        // Generate new ID if not specified
1521
        if ($this->isInDB()) {
1522
            return;
1523
        }
1524
1525
        // Perform an insert on the base table
1526
        $manipulation = [];
1527
        $this->prepareManipulationTable($baseTable, $now, true, $manipulation, $this->baseClass());
1528
        DB::manipulate($manipulation);
1529
1530
        $this->changed['ID'] = self::CHANGE_VALUE;
1531
        $this->record['ID'] = DB::get_generated_id($baseTable);
1532
    }
1533
1534
    /**
1535
     * Generate and write the database manipulation for all changed fields
1536
     *
1537
     * @param string $baseTable Base table
1538
     * @param string $now Timestamp to use for the current time
1539
     * @param bool $isNewRecord If this is a new record
1540
     * @throws InvalidArgumentException
1541
     */
1542
    protected function writeManipulation($baseTable, $now, $isNewRecord)
1543
    {
1544
        // Generate database manipulations for each class
1545
        $manipulation = [];
1546
        foreach (ClassInfo::ancestry(static::class, true) as $class) {
1547
            $this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
1548
        }
1549
1550
        // Allow extensions to extend this manipulation
1551
        $this->extend('augmentWrite', $manipulation);
1552
1553
        // New records have their insert into the base data table done first, so that they can pass the
1554
        // generated ID on to the rest of the manipulation
1555
        if ($isNewRecord) {
1556
            $manipulation[$baseTable]['command'] = 'update';
1557
        }
1558
1559
        // Make sure none of our field assignment are arrays
1560
        foreach ($manipulation as $tableManipulation) {
1561
            if (!isset($tableManipulation['fields'])) {
1562
                continue;
1563
            }
1564
            foreach ($tableManipulation['fields'] as $fieldName => $fieldValue) {
1565
                if (is_array($fieldValue)) {
1566
                    $dbObject = $this->dbObject($fieldName);
1567
                    // If the field allows non-scalar values we'll let it do dynamic assignments
1568
                    if ($dbObject && $dbObject->scalarValueOnly()) {
1569
                        throw new InvalidArgumentException(
1570
                            'DataObject::writeManipulation: parameterised field assignments are disallowed'
1571
                        );
1572
                    }
1573
                }
1574
            }
1575
        }
1576
1577
        // Perform the manipulation
1578
        DB::manipulate($manipulation);
1579
    }
1580
1581
    /**
1582
     * Writes all changes to this object to the database.
1583
     *  - It will insert a record whenever ID isn't set, otherwise update.
1584
     *  - All relevant tables will be updated.
1585
     *  - $this->onBeforeWrite() gets called beforehand.
1586
     *  - Extensions such as Versioned will ammend the database-write to ensure that a version is saved.
1587
     *
1588
     * @uses DataExtension::augmentWrite()
1589
     *
1590
     * @param boolean       $showDebug Show debugging information
1591
     * @param boolean       $forceInsert Run INSERT command rather than UPDATE, even if record already exists
1592
     * @param boolean       $forceWrite Write to database even if there are no changes
1593
     * @param boolean|array $writeComponents Call write() on all associated component instances which were previously
1594
     *                      retrieved through {@link getComponent()}, {@link getComponents()} or
1595
     *                      {@link getManyManyComponents()}. Default to `false`. The parameter can also be provided in
1596
     *                      the form of an array: `['recursive' => true, skip => ['Page'=>[1,2,3]]`. This avoid infinite
1597
     *                      loops when one DataObject are components of each other.
1598
     * @return int The ID of the record
1599
     * @throws ValidationException Exception that can be caught and handled by the calling function
1600
     */
1601
    public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false)
1602
    {
1603
        $now = DBDatetime::now()->Rfc2822();
1604
1605
        // Execute pre-write tasks
1606
        $this->preWrite();
1607
1608
        // Check if we are doing an update or an insert
1609
        $isNewRecord = !$this->isInDB() || $forceInsert;
1610
1611
        // Check changes exist, abort if there are none
1612
        $hasChanges = $this->updateChanges($isNewRecord);
1613
        if ($hasChanges || $forceWrite || $isNewRecord) {
1614
            // Ensure Created and LastEdited are populated
1615
            if (!isset($this->record['Created'])) {
1616
                $this->record['Created'] = $now;
1617
            }
1618
            $this->record['LastEdited'] = $now;
1619
1620
            // New records have their insert into the base data table done first, so that they can pass the
1621
            // generated primary key on to the rest of the manipulation
1622
            $baseTable = $this->baseTable();
1623
            $this->writeBaseRecord($baseTable, $now);
1624
1625
            // Write the DB manipulation for all changed fields
1626
            $this->writeManipulation($baseTable, $now, $isNewRecord);
1627
1628
            // If there's any relations that couldn't be saved before, save them now (we have an ID here)
1629
            $this->writeRelations();
1630
            $this->onAfterWrite();
1631
1632
            // Reset isChanged data
1633
            // DBComposites properly bound to the parent record will also have their isChanged value reset
1634
            $this->changed = [];
1635
            $this->changeForced = false;
1636
            $this->original = $this->record;
1637
        } else {
1638
            if ($showDebug) {
1639
                Debug::message("no changes for DataObject");
1640
            }
1641
1642
            // Used by DODs to clean up after themselves, eg, Versioned
1643
            $this->invokeWithExtensions('onAfterSkippedWrite');
1644
        }
1645
1646
        // Write relations as necessary
1647
        if ($writeComponents) {
1648
            $recursive = true;
1649
            $skip = [];
1650
            if (is_array($writeComponents)) {
1651
                $recursive = isset($writeComponents['recursive']) && $writeComponents['recursive'];
1652
                $skip = isset($writeComponents['skip']) && is_array($writeComponents['skip'])
1653
                    ? $writeComponents['skip']
1654
                    : [];
1655
            }
1656
            $this->writeComponents($recursive, $skip);
1657
        }
1658
1659
        // Clears the cache for this object so get_one returns the correct object.
1660
        $this->flushCache();
1661
1662
        return $this->record['ID'];
1663
    }
1664
1665
    /**
1666
     * Writes cached relation lists to the database, if possible
1667
     */
1668
    public function writeRelations()
1669
    {
1670
        if (!$this->isInDB()) {
1671
            return;
1672
        }
1673
1674
        // If there's any relations that couldn't be saved before, save them now (we have an ID here)
1675
        if ($this->unsavedRelations) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->unsavedRelations of type SilverStripe\ORM\UnsavedRelationList[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1676
            foreach ($this->unsavedRelations as $name => $list) {
1677
                $list->changeToList($this->$name());
1678
            }
1679
            $this->unsavedRelations = [];
1680
        }
1681
    }
1682
1683
    /**
1684
     * Write the cached components to the database. Cached components could refer to two different instances of the
1685
     * same record.
1686
     *
1687
     * @param bool $recursive Recursively write components
1688
     * @param array $skip List of DataObject references to skip
1689
     * @return DataObject $this
1690
     */
1691
    public function writeComponents($recursive = false, $skip = [])
1692
    {
1693
        // Make sure we add our current object to the skip list
1694
        $this->skipWriteComponents($recursive, $this, $skip);
1695
1696
        // All our write calls have the same arguments ... just need make sure the skip list is pass by reference
1697
        $args = [
1698
            false, false, false,
1699
            $recursive ? ["recursive" => $recursive, "skip" => &$skip] : false
1700
        ];
1701
1702
        foreach ($this->components as $component) {
1703
            if (!$this->skipWriteComponents($recursive, $component, $skip)) {
1704
                $component->write(...$args);
0 ignored issues
show
Bug introduced by
It seems like $args can also be of type array<string,mixed|true>; however, parameter $showDebug of SilverStripe\ORM\DataObject::write() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1704
                $component->write(/** @scrutinizer ignore-type */ ...$args);
Loading history...
1705
            }
1706
        }
1707
1708
        if ($join = $this->getJoin()) {
1709
            if (!$this->skipWriteComponents($recursive, $join, $skip)) {
1710
                $join->write(...$args);
1711
            }
1712
        }
1713
1714
        return $this;
1715
    }
1716
1717
    /**
1718
     * Check if target is in the skip list and add it if it isn't.
1719
     * @param bool $recursive
1720
     * @param DataObject $target
1721
     * @param array $skip
1722
     * @return bool Whether the target is already in the list
1723
     */
1724
    private function skipWriteComponents($recursive, DataObject $target, array &$skip)
1725
    {
1726
        // skip writing component if it doesn't exist
1727
        if (!$target->exists()) {
1728
            return true;
1729
        }
1730
1731
        // We only care about the skip list if our call is meant to be recursive
1732
        if (!$recursive) {
1733
            return false;
1734
        }
1735
1736
        // Get our Skip array keys
1737
        $classname = get_class($target);
1738
        $id = $target->ID;
1739
1740
        // Check if the target is in the skip list
1741
        if (isset($skip[$classname])) {
1742
            if (in_array($id, $skip[$classname])) {
1743
                // Skip the object
1744
                return true;
1745
            }
1746
        } else {
1747
            // This is the first object of this class
1748
            $skip[$classname] = [];
1749
        }
1750
1751
        // Add the target to our skip list
1752
        $skip[$classname][] = $id;
1753
1754
        return false;
1755
    }
1756
1757
    /**
1758
     * Delete this data object.
1759
     * $this->onBeforeDelete() gets called.
1760
     * Note that in Versioned objects, both Stage and Live will be deleted.
1761
     * @uses DataExtension::augmentSQL()
1762
     */
1763
    public function delete()
1764
    {
1765
        $this->brokenOnDelete = true;
1766
        $this->onBeforeDelete();
1767
        if ($this->brokenOnDelete) {
1768
            throw new LogicException(
1769
                static::class . " has a broken onBeforeDelete() function."
1770
                . " Make sure that you call parent::onBeforeDelete()."
1771
            );
1772
        }
1773
1774
        // Deleting a record without an ID shouldn't do anything
1775
        if (!$this->ID) {
1776
            throw new LogicException("DataObject::delete() called on a DataObject without an ID");
1777
        }
1778
1779
        // TODO: This is quite ugly.  To improve:
1780
        //  - move the details of the delete code in the DataQuery system
1781
        //  - update the code to just delete the base table, and rely on cascading deletes in the DB to do the rest
1782
        //    obviously, that means getting requireTable() to configure cascading deletes ;-)
1783
        $srcQuery = DataList::create(static::class)
1784
            ->filter('ID', $this->ID)
1785
            ->dataQuery()
1786
            ->query();
1787
        $queriedTables = $srcQuery->queriedTables();
1788
        $this->extend('updateDeleteTables', $queriedTables, $srcQuery);
1789
        foreach ($queriedTables as $table) {
1790
            $delete = SQLDelete::create("\"$table\"", ['"ID"' => $this->ID]);
1791
            $this->extend('updateDeleteTable', $delete, $table, $queriedTables, $srcQuery);
1792
            $delete->execute();
1793
        }
1794
        // Remove this item out of any caches
1795
        $this->flushCache();
1796
1797
        $this->onAfterDelete();
1798
1799
        $this->OldID = $this->ID;
1800
        $this->ID = 0;
1801
    }
1802
1803
    /**
1804
     * Delete the record with the given ID.
1805
     *
1806
     * @param string $className The class name of the record to be deleted
1807
     * @param int $id ID of record to be deleted
1808
     */
1809
    public static function delete_by_id($className, $id)
1810
    {
1811
        $obj = DataObject::get_by_id($className, $id);
1812
        if ($obj) {
0 ignored issues
show
introduced by
$obj is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
1813
            $obj->delete();
1814
        } else {
1815
            user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
1816
        }
1817
    }
1818
1819
    /**
1820
     * Get the class ancestry, including the current class name.
1821
     * The ancestry will be returned as an array of class names, where the 0th element
1822
     * will be the class that inherits directly from DataObject, and the last element
1823
     * will be the current class.
1824
     *
1825
     * @return array Class ancestry
1826
     */
1827
    public function getClassAncestry()
1828
    {
1829
        return ClassInfo::ancestry(static::class);
1830
    }
1831
1832
    /**
1833
     * Return a unary component object from a one to one relationship, as a DataObject.
1834
     * If no component is available, an 'empty component' will be returned for
1835
     * non-polymorphic relations, or for polymorphic relations with a class set.
1836
     *
1837
     * @param string $componentName Name of the component
1838
     * @return DataObject The component object. It's exact type will be that of the component.
1839
     * @throws Exception
1840
     */
1841
    public function getComponent($componentName)
1842
    {
1843
        if (isset($this->components[$componentName])) {
1844
            return $this->components[$componentName];
1845
        }
1846
1847
        $schema = static::getSchema();
1848
        if ($class = $schema->hasOneComponent(static::class, $componentName)) {
1849
            $joinField = $componentName . 'ID';
1850
            $joinID = $this->getField($joinField);
1851
1852
            // Extract class name for polymorphic relations
1853
            if ($class === self::class) {
1854
                $class = $this->getField($componentName . 'Class');
1855
                if (empty($class)) {
1856
                    return null;
1857
                }
1858
            }
1859
1860
            if ($joinID) {
1861
                // Ensure that the selected object originates from the same stage, subsite, etc
1862
                $component = DataObject::get($class)
1863
                    ->filter('ID', $joinID)
1864
                    ->setDataQueryParam($this->getInheritableQueryParams())
1865
                    ->first();
1866
            }
1867
1868
            if (empty($component)) {
1869
                $component = Injector::inst()->create($class);
1870
            }
1871
        } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
1872
            $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
1873
            $joinID = $this->ID;
1874
1875
            if ($joinID) {
1876
                // Prepare filter for appropriate join type
1877
                if ($polymorphic) {
1878
                    $filter = [
1879
                        "{$joinField}ID" => $joinID,
1880
                        "{$joinField}Class" => static::class,
1881
                    ];
1882
                } else {
1883
                    $filter = [
1884
                        $joinField => $joinID
1885
                    ];
1886
                }
1887
1888
                // Ensure that the selected object originates from the same stage, subsite, etc
1889
                $component = DataObject::get($class)
1890
                    ->filter($filter)
1891
                    ->setDataQueryParam($this->getInheritableQueryParams())
1892
                    ->first();
1893
            }
1894
1895
            if (empty($component)) {
1896
                $component = Injector::inst()->create($class);
1897
                if ($polymorphic) {
1898
                    $component->{$joinField . 'ID'} = $this->ID;
1899
                    $component->{$joinField . 'Class'} = static::class;
1900
                } else {
1901
                    $component->$joinField = $this->ID;
1902
                }
1903
            }
1904
        } else {
1905
            throw new InvalidArgumentException(
1906
                "DataObject->getComponent(): Could not find component '$componentName'."
1907
            );
1908
        }
1909
1910
        $this->components[$componentName] = $component;
1911
        return $component;
1912
    }
1913
1914
    /**
1915
     * Assign an item to the given component
1916
     *
1917
     * @param string $componentName
1918
     * @param DataObject|null $item
1919
     * @return $this
1920
     */
1921
    public function setComponent($componentName, $item)
1922
    {
1923
        // Validate component
1924
        $schema = static::getSchema();
1925
        if ($class = $schema->hasOneComponent(static::class, $componentName)) {
1926
            // Force item to be written if not by this point
1927
            // @todo This could be lazy-written in a beforeWrite hook, but force write here for simplicity
1928
            // https://github.com/silverstripe/silverstripe-framework/issues/7818
1929
            if ($item && !$item->isInDB()) {
1930
                $item->write();
1931
            }
1932
1933
            // Update local ID
1934
            $joinField = $componentName . 'ID';
1935
            $this->setField($joinField, $item ? $item->ID : null);
1936
            // Update Class (Polymorphic has_one)
1937
            // Extract class name for polymorphic relations
1938
            if ($class === self::class) {
1939
                $this->setField($componentName . 'Class', $item ? get_class($item) : null);
1940
            }
1941
        } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $class is dead and can be removed.
Loading history...
1942
            if ($item) {
1943
                // For belongs_to, add to has_one on other component
1944
                $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
1945
                if (!$polymorphic) {
1946
                    $joinField = substr($joinField, 0, -2);
1947
                }
1948
                $item->setComponent($joinField, $this);
1949
            }
1950
        } else {
1951
            throw new InvalidArgumentException(
1952
                "DataObject->setComponent(): Could not find component '$componentName'."
1953
            );
1954
        }
1955
1956
        $this->components[$componentName] = $item;
1957
        return $this;
1958
    }
1959
1960
    /**
1961
     * Returns a one-to-many relation as a HasManyList
1962
     *
1963
     * @param string $componentName Name of the component
1964
     * @param int|array $id Optional ID(s) for parent of this relation, if not the current record
1965
     * @return HasManyList|UnsavedRelationList The components of the one-to-many relationship.
1966
     */
1967
    public function getComponents($componentName, $id = null)
1968
    {
1969
        if (!isset($id)) {
1970
            $id = $this->ID;
1971
        }
1972
        $result = null;
1973
1974
        $schema = $this->getSchema();
1975
        $componentClass = $schema->hasManyComponent(static::class, $componentName);
1976
        if (!$componentClass) {
1977
            throw new InvalidArgumentException(sprintf(
1978
                "DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
1979
                $componentName,
1980
                static::class
1981
            ));
1982
        }
1983
1984
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
1985
        if (!$id) {
1986
            if (!isset($this->unsavedRelations[$componentName])) {
1987
                $this->unsavedRelations[$componentName] =
1988
                    new UnsavedRelationList(static::class, $componentName, $componentClass);
1989
            }
1990
            return $this->unsavedRelations[$componentName];
1991
        }
1992
1993
        // Determine type and nature of foreign relation
1994
        $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'has_many', $polymorphic);
1995
        /** @var HasManyList $result */
1996
        if ($polymorphic) {
1997
            $result = PolymorphicHasManyList::create($componentClass, $joinField, static::class);
1998
        } else {
1999
            $result = HasManyList::create($componentClass, $joinField);
2000
        }
2001
2002
        return $result
2003
            ->setDataQueryParam($this->getInheritableQueryParams())
2004
            ->forForeignID($id);
2005
    }
2006
2007
    /**
2008
     * Find the foreign class of a relation on this DataObject, regardless of the relation type.
2009
     *
2010
     * @param string $relationName Relation name.
2011
     * @return string Class name, or null if not found.
2012
     */
2013
    public function getRelationClass($relationName)
2014
    {
2015
        // Parse many_many
2016
        $manyManyComponent = $this->getSchema()->manyManyComponent(static::class, $relationName);
2017
        if ($manyManyComponent) {
2018
            return $manyManyComponent['childClass'];
2019
        }
2020
2021
        // Go through all relationship configuration fields.
2022
        $config = $this->config();
2023
        $candidates = array_merge(
2024
            ($relations = $config->get('has_one')) ? $relations : [],
2025
            ($relations = $config->get('has_many')) ? $relations : [],
2026
            ($relations = $config->get('belongs_to')) ? $relations : []
2027
        );
2028
2029
        if (isset($candidates[$relationName])) {
2030
            $remoteClass = $candidates[$relationName];
2031
2032
            // If dot notation is present, extract just the first part that contains the class.
2033
            if (($fieldPos = strpos($remoteClass, '.')) !== false) {
2034
                return substr($remoteClass, 0, $fieldPos);
2035
            }
2036
2037
            // Otherwise just return the class
2038
            return $remoteClass;
2039
        }
2040
2041
        return null;
2042
    }
2043
2044
    /**
2045
     * Given a relation name, determine the relation type
2046
     *
2047
     * @param string $component Name of component
2048
     * @return string has_one, has_many, many_many, belongs_many_many or belongs_to
2049
     */
2050
    public function getRelationType($component)
2051
    {
2052
        $types = ['has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to'];
2053
        $config = $this->config();
2054
        foreach ($types as $type) {
2055
            $relations = $config->get($type);
2056
            if ($relations && isset($relations[$component])) {
2057
                return $type;
2058
            }
2059
        }
2060
        return null;
2061
    }
2062
2063
    /**
2064
     * Given a relation declared on a remote class, generate a substitute component for the opposite
2065
     * side of the relation.
2066
     *
2067
     * Notes on behaviour:
2068
     *  - This can still be used on components that are defined on both sides, but do not need to be.
2069
     *  - All has_ones on remote class will be treated as local has_many, even if they are belongs_to
2070
     *  - Polymorphic relationships do not have two natural endpoints (only on one side)
2071
     *   and thus attempting to infer them will return nothing.
2072
     *  - Cannot be used on unsaved objects.
2073
     *
2074
     * @param string $remoteClass
2075
     * @param string $remoteRelation
2076
     * @return DataList|DataObject The component, either as a list or single object
2077
     * @throws BadMethodCallException
2078
     * @throws InvalidArgumentException
2079
     */
2080
    public function inferReciprocalComponent($remoteClass, $remoteRelation)
2081
    {
2082
        $remote = DataObject::singleton($remoteClass);
2083
        $class = $remote->getRelationClass($remoteRelation);
2084
        $schema = static::getSchema();
2085
2086
        // Validate arguments
2087
        if (!$this->isInDB()) {
2088
            throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects");
2089
        }
2090
        if (empty($class)) {
2091
            throw new InvalidArgumentException(sprintf(
2092
                "%s invoked with invalid relation %s.%s",
2093
                __METHOD__,
2094
                $remoteClass,
2095
                $remoteRelation
2096
            ));
2097
        }
2098
        // If relation is polymorphic, do not infer recriprocal relationship
2099
        if ($class === self::class) {
2100
            return null;
2101
        }
2102
        if (!is_a($this, $class, true)) {
2103
            throw new InvalidArgumentException(sprintf(
2104
                "Relation %s on %s does not refer to objects of type %s",
2105
                $remoteRelation,
2106
                $remoteClass,
2107
                static::class
2108
            ));
2109
        }
2110
2111
        // Check the relation type to mock
2112
        $relationType = $remote->getRelationType($remoteRelation);
2113
        switch ($relationType) {
2114
            case 'has_one': {
2115
                // Mock has_many
2116
                $joinField = "{$remoteRelation}ID";
2117
                $componentClass = $schema->classForField($remoteClass, $joinField);
2118
                $result = HasManyList::create($componentClass, $joinField);
2119
                return $result
2120
                    ->setDataQueryParam($this->getInheritableQueryParams())
2121
                    ->forForeignID($this->ID);
2122
            }
2123
            case 'belongs_to':
2124
            case 'has_many': {
2125
                // These relations must have a has_one on the other end, so find it
2126
                $joinField = $schema->getRemoteJoinField(
2127
                    $remoteClass,
2128
                    $remoteRelation,
2129
                    $relationType,
2130
                    $polymorphic
2131
                );
2132
                // If relation is polymorphic, do not infer recriprocal relationship automatically
2133
                if ($polymorphic) {
2134
                    return null;
2135
                }
2136
                $joinID = $this->getField($joinField);
2137
                if (empty($joinID)) {
2138
                    return null;
2139
                }
2140
                // Get object by joined ID
2141
                return DataObject::get($remoteClass)
2142
                    ->filter('ID', $joinID)
2143
                    ->setDataQueryParam($this->getInheritableQueryParams())
2144
                    ->first();
2145
            }
2146
            case 'many_many':
2147
            case 'belongs_many_many': {
2148
                // Get components and extra fields from parent
2149
                $manyMany = $remote->getSchema()->manyManyComponent($remoteClass, $remoteRelation);
2150
                $extraFields = $schema->manyManyExtraFieldsForComponent($remoteClass, $remoteRelation) ?: [];
2151
2152
                // Reverse parent and component fields and create an inverse ManyManyList
2153
                /** @var RelationList $result */
2154
                $result = Injector::inst()->create(
2155
                    $manyMany['relationClass'],
2156
                    $manyMany['parentClass'], // Substitute parent class for dataClass
2157
                    $manyMany['join'],
2158
                    $manyMany['parentField'], // Reversed parent / child field
2159
                    $manyMany['childField'], // Reversed parent / child field
2160
                    $extraFields,
2161
                    $manyMany['childClass'], // substitute child class for parentClass
2162
                    $remoteClass // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
2163
                );
2164
                $this->extend('updateManyManyComponents', $result);
2165
2166
                // If this is called on a singleton, then we return an 'orphaned relation' that can have the
2167
                // foreignID set elsewhere.
2168
                return $result
2169
                    ->setDataQueryParam($this->getInheritableQueryParams())
2170
                    ->forForeignID($this->ID);
2171
            }
2172
            default: {
2173
                return null;
2174
            }
2175
        }
2176
    }
2177
2178
    /**
2179
     * Returns a many-to-many component, as a ManyManyList.
2180
     * @param string $componentName Name of the many-many component
2181
     * @param int|array $id Optional ID for parent of this relation, if not the current record
2182
     * @return ManyManyList|UnsavedRelationList The set of components
2183
     */
2184
    public function getManyManyComponents($componentName, $id = null)
2185
    {
2186
        if (!isset($id)) {
2187
            $id = $this->ID;
2188
        }
2189
        $schema = static::getSchema();
2190
        $manyManyComponent = $schema->manyManyComponent(static::class, $componentName);
2191
        if (!$manyManyComponent) {
2192
            throw new InvalidArgumentException(sprintf(
2193
                "DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'",
2194
                $componentName,
2195
                static::class
2196
            ));
2197
        }
2198
2199
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
2200
        if (!$id) {
2201
            if (!isset($this->unsavedRelations[$componentName])) {
2202
                $this->unsavedRelations[$componentName] = new UnsavedRelationList(
2203
                    $manyManyComponent['parentClass'],
2204
                    $componentName,
2205
                    $manyManyComponent['childClass']
2206
                );
2207
            }
2208
            return $this->unsavedRelations[$componentName];
2209
        }
2210
2211
        $extraFields = $schema->manyManyExtraFieldsForComponent(static::class, $componentName) ?: [];
2212
        /** @var RelationList $result */
2213
        $result = Injector::inst()->create(
2214
            $manyManyComponent['relationClass'],
2215
            $manyManyComponent['childClass'],
2216
            $manyManyComponent['join'],
2217
            $manyManyComponent['childField'],
2218
            $manyManyComponent['parentField'],
2219
            $extraFields,
2220
            $manyManyComponent['parentClass'],
2221
            static::class // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
2222
        );
2223
2224
        // Store component data in query meta-data
2225
        $result = $result->alterDataQuery(function ($query) use ($extraFields) {
2226
            /** @var DataQuery $query */
2227
            $query->setQueryParam('Component.ExtraFields', $extraFields);
2228
        });
2229
2230
        // If we have a default sort set for our "join" then we should overwrite any default already set.
2231
        $joinSort = Config::inst()->get($manyManyComponent['join'], 'default_sort');
2232
        if (!empty($joinSort)) {
2233
            $result = $result->sort($joinSort);
2234
        }
2235
2236
        $this->extend('updateManyManyComponents', $result);
2237
2238
        // If this is called on a singleton, then we return an 'orphaned relation' that can have the
2239
        // foreignID set elsewhere.
2240
        return $result
2241
            ->setDataQueryParam($this->getInheritableQueryParams())
2242
            ->forForeignID($id);
2243
    }
2244
2245
    /**
2246
     * Return the class of a one-to-one component.  If $component is null, return all of the one-to-one components and
2247
     * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.
2248
     *
2249
     * @return string|array The class of the one-to-one component, or an array of all one-to-one components and
2250
     *                          their classes.
2251
     */
2252
    public function hasOne()
2253
    {
2254
        return (array)$this->config()->get('has_one');
2255
    }
2256
2257
    /**
2258
     * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
2259
     * their class name will be returned.
2260
     *
2261
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2262
     *        the field data stripped off. It defaults to TRUE.
2263
     * @return string|array
2264
     */
2265
    public function belongsTo($classOnly = true)
2266
    {
2267
        $belongsTo = (array)$this->config()->get('belongs_to');
2268
        if ($belongsTo && $classOnly) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $belongsTo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2269
            return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
2270
        } else {
2271
            return $belongsTo ? $belongsTo : [];
2272
        }
2273
    }
2274
2275
    /**
2276
     * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
2277
     * relationships and their classes will be returned.
2278
     *
2279
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2280
     *        the field data stripped off. It defaults to TRUE.
2281
     * @return string|array|false
2282
     */
2283
    public function hasMany($classOnly = true)
2284
    {
2285
        $hasMany = (array)$this->config()->get('has_many');
2286
        if ($hasMany && $classOnly) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $hasMany of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2287
            return preg_replace('/(.+)?\..+/', '$1', $hasMany);
2288
        } else {
2289
            return $hasMany ? $hasMany : [];
2290
        }
2291
    }
2292
2293
    /**
2294
     * Return the many-to-many extra fields specification.
2295
     *
2296
     * If you don't specify a component name, it returns all
2297
     * extra fields for all components available.
2298
     *
2299
     * @return array|null
2300
     */
2301
    public function manyManyExtraFields()
2302
    {
2303
        return $this->config()->get('many_many_extraFields');
2304
    }
2305
2306
    /**
2307
     * Return information about a many-to-many component.
2308
     * The return value is an array of (parentclass, childclass).  If $component is null, then all many-many
2309
     * components are returned.
2310
     *
2311
     * @see DataObjectSchema::manyManyComponent()
2312
     * @return array|null An array of (parentclass, childclass), or an array of all many-many components
2313
     */
2314
    public function manyMany()
2315
    {
2316
        $config = $this->config();
2317
        $manyManys = (array)$config->get('many_many');
2318
        $belongsManyManys = (array)$config->get('belongs_many_many');
2319
        $items = array_merge($manyManys, $belongsManyManys);
2320
        return $items;
2321
    }
2322
2323
    /**
2324
     * This returns an array (if it exists) describing the database extensions that are required, or false if none
2325
     *
2326
     * This is experimental, and is currently only a Postgres-specific enhancement.
2327
     *
2328
     * @param string $class
2329
     * @return array|false
2330
     */
2331
    public function database_extensions($class)
2332
    {
2333
        $extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
2334
        if ($extensions) {
2335
            return $extensions;
2336
        } else {
2337
            return false;
2338
        }
2339
    }
2340
2341
    /**
2342
     * Generates a SearchContext to be used for building and processing
2343
     * a generic search form for properties on this object.
2344
     *
2345
     * @return SearchContext
2346
     */
2347
    public function getDefaultSearchContext()
2348
    {
2349
        return SearchContext::create(
2350
            static::class,
2351
            $this->scaffoldSearchFields(),
2352
            $this->defaultSearchFilters()
2353
        );
2354
    }
2355
2356
    /**
2357
     * Determine which properties on the DataObject are
2358
     * searchable, and map them to their default {@link FormField}
2359
     * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
2360
     *
2361
     * Some additional logic is included for switching field labels, based on
2362
     * how generic or specific the field type is.
2363
     *
2364
     * Used by {@link SearchContext}.
2365
     *
2366
     * @param array $_params
2367
     *   'fieldClasses': Associative array of field names as keys and FormField classes as values
2368
     *   'restrictFields': Numeric array of a field name whitelist
2369
     * @return FieldList
2370
     */
2371
    public function scaffoldSearchFields($_params = null)
2372
    {
2373
        $params = array_merge(
2374
            [
2375
                'fieldClasses' => false,
2376
                'restrictFields' => false
2377
            ],
2378
            (array)$_params
2379
        );
2380
        $fields = new FieldList();
2381
        foreach ($this->searchableFields() as $fieldName => $spec) {
2382
            if ($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) {
2383
                continue;
2384
            }
2385
2386
            // If a custom fieldclass is provided as a string, use it
2387
            $field = null;
2388
            if ($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
2389
                $fieldClass = $params['fieldClasses'][$fieldName];
2390
                $field = new $fieldClass($fieldName);
2391
            // If we explicitly set a field, then construct that
2392
            } elseif (isset($spec['field'])) {
2393
                // If it's a string, use it as a class name and construct
2394
                if (is_string($spec['field'])) {
2395
                    $fieldClass = $spec['field'];
2396
                    $field = new $fieldClass($fieldName);
2397
2398
                // If it's a FormField object, then just use that object directly.
2399
                } elseif ($spec['field'] instanceof FormField) {
2400
                    $field = $spec['field'];
2401
2402
                // Otherwise we have a bug
2403
                } else {
2404
                    user_error("Bad value for searchable_fields, 'field' value: "
2405
                        . var_export($spec['field'], true), E_USER_WARNING);
2406
                }
2407
2408
            // Otherwise, use the database field's scaffolder
2409
            } elseif ($object = $this->relObject($fieldName)) {
2410
                if (is_object($object) && $object->hasMethod('scaffoldSearchField')) {
2411
                    $field = $object->scaffoldSearchField();
2412
                } else {
2413
                    throw new Exception(sprintf(
2414
                        "SearchField '%s' on '%s' does not return a valid DBField instance.",
2415
                        $fieldName,
2416
                        get_class($this)
2417
                    ));
2418
                }
2419
            }
2420
2421
            // Allow fields to opt out of search
2422
            if (!$field) {
2423
                continue;
2424
            }
2425
2426
            if (strstr($fieldName, '.')) {
2427
                $field->setName(str_replace('.', '__', $fieldName));
2428
            }
2429
            $field->setTitle($spec['title']);
2430
2431
            $fields->push($field);
2432
        }
2433
        return $fields;
2434
    }
2435
2436
    /**
2437
     * Scaffold a simple edit form for all properties on this dataobject,
2438
     * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
2439
     * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
2440
     *
2441
     * @uses FormScaffolder
2442
     *
2443
     * @param array $_params Associative array passing through properties to {@link FormScaffolder}.
2444
     * @return FieldList
2445
     */
2446
    public function scaffoldFormFields($_params = null)
2447
    {
2448
        $params = array_merge(
2449
            [
2450
                'tabbed' => false,
2451
                'includeRelations' => false,
2452
                'restrictFields' => false,
2453
                'fieldClasses' => false,
2454
                'ajaxSafe' => false
2455
            ],
2456
            (array)$_params
2457
        );
2458
2459
        $fs = FormScaffolder::create($this);
2460
        $fs->tabbed = $params['tabbed'];
2461
        $fs->includeRelations = $params['includeRelations'];
2462
        $fs->restrictFields = $params['restrictFields'];
2463
        $fs->fieldClasses = $params['fieldClasses'];
2464
        $fs->ajaxSafe = $params['ajaxSafe'];
2465
2466
        $this->extend('updateFormScaffolder', $fs, $this);
2467
2468
        return $fs->getFieldList();
2469
    }
2470
2471
    /**
2472
     * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
2473
     * being called on extensions
2474
     *
2475
     * @param callable $callback The callback to execute
2476
     */
2477
    protected function beforeUpdateCMSFields($callback)
2478
    {
2479
        $this->beforeExtending('updateCMSFields', $callback);
2480
    }
2481
2482
    /**
2483
     * Centerpiece of every data administration interface in Silverstripe,
2484
     * which returns a {@link FieldList} suitable for a {@link Form} object.
2485
     * If not overloaded, we're using {@link scaffoldFormFields()} to automatically
2486
     * generate this set. To customize, overload this method in a subclass
2487
     * or extended onto it by using {@link DataExtension->updateCMSFields()}.
2488
     *
2489
     * <code>
2490
     * class MyCustomClass extends DataObject {
2491
     *  static $db = array('CustomProperty'=>'Boolean');
2492
     *
2493
     *  function getCMSFields() {
2494
     *    $fields = parent::getCMSFields();
2495
     *    $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
2496
     *    return $fields;
2497
     *  }
2498
     * }
2499
     * </code>
2500
     *
2501
     * @see Good example of complex FormField building: SiteTree::getCMSFields()
2502
     *
2503
     * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.
2504
     */
2505
    public function getCMSFields()
2506
    {
2507
        $tabbedFields = $this->scaffoldFormFields([
2508
            // Don't allow has_many/many_many relationship editing before the record is first saved
2509
            'includeRelations' => ($this->ID > 0),
2510
            'tabbed' => true,
2511
            'ajaxSafe' => true
2512
        ]);
2513
2514
        $this->extend('updateCMSFields', $tabbedFields);
2515
2516
        return $tabbedFields;
2517
    }
2518
2519
    /**
2520
     * need to be overload by solid dataobject, so that the customised actions of that dataobject,
2521
     * including that dataobject's extensions customised actions could be added to the EditForm.
2522
     *
2523
     * @return FieldList an Empty FieldList(); need to be overload by solid subclass
2524
     */
2525
    public function getCMSActions()
2526
    {
2527
        $actions = new FieldList();
2528
        $this->extend('updateCMSActions', $actions);
2529
        return $actions;
2530
    }
2531
2532
    /**
2533
     * When extending this class and overriding this method, you will need to instantiate the CompositeValidator by
2534
     * calling parent::getCMSCompositeValidator(). This will ensure that the appropriate extension point is also
2535
     * invoked.
2536
     *
2537
     * You can also update the CompositeValidator by creating an Extension and implementing the
2538
     * updateCMSCompositeValidator(CompositeValidator $compositeValidator) method.
2539
     *
2540
     * @see CompositeValidator for examples of implementation
2541
     * @return CompositeValidator
2542
     */
2543
    public function getCMSCompositeValidator(): CompositeValidator
2544
    {
2545
        $compositeValidator = new CompositeValidator();
2546
2547
        // Support for the old method during the deprecation period
2548
        if ($this->hasMethod('getCMSValidator')) {
2549
            Deprecation::notice(
2550
                '4.6',
2551
                'getCMSValidator() is removed in 5.0 in favour of getCMSCompositeValidator()'
2552
            );
2553
2554
            $compositeValidator->addValidator($this->getCMSValidator());
0 ignored issues
show
Bug introduced by
The method getCMSValidator() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2554
            $compositeValidator->addValidator($this->/** @scrutinizer ignore-call */ getCMSValidator());
Loading history...
2555
        }
2556
2557
        // Extend validator - forward support, will be supported beyond 5.0.0
2558
        $this->invokeWithExtensions('updateCMSCompositeValidator', $compositeValidator);
2559
2560
        return $compositeValidator;
2561
    }
2562
2563
    /**
2564
     * Used for simple frontend forms without relation editing
2565
     * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()}
2566
     * by default. To customize, either overload this method in your
2567
     * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.
2568
     *
2569
     * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API
2570
     *
2571
     * @param array $params See {@link scaffoldFormFields()}
2572
     * @return FieldList Always returns a simple field collection without TabSet.
2573
     */
2574
    public function getFrontEndFields($params = null)
2575
    {
2576
        $untabbedFields = $this->scaffoldFormFields($params);
2577
        $this->extend('updateFrontEndFields', $untabbedFields);
2578
2579
        return $untabbedFields;
2580
    }
2581
2582
    public function getViewerTemplates($suffix = '')
2583
    {
2584
        return SSViewer::get_templates_by_class(static::class, $suffix, $this->baseClass());
2585
    }
2586
2587
    /**
2588
     * Gets the value of a field.
2589
     * Called by {@link __get()} and any getFieldName() methods you might create.
2590
     *
2591
     * @param string $field The name of the field
2592
     * @return mixed The field value
2593
     */
2594
    public function getField($field)
2595
    {
2596
        // If we already have a value in $this->record, then we should just return that
2597
        if (isset($this->record[$field])) {
2598
            return $this->record[$field];
2599
        }
2600
2601
        // Do we have a field that needs to be lazy loaded?
2602
        if (isset($this->record[$field . '_Lazy'])) {
2603
            $tableClass = $this->record[$field . '_Lazy'];
2604
            $this->loadLazyFields($tableClass);
2605
        }
2606
        $schema = static::getSchema();
2607
2608
        // Support unary relations as fields
2609
        if ($schema->unaryComponent(static::class, $field)) {
2610
            return $this->getComponent($field);
2611
        }
2612
2613
        // In case of complex fields, return the DBField object
2614
        if ($schema->compositeField(static::class, $field)) {
2615
            $this->record[$field] = $this->dbObject($field);
2616
        }
2617
2618
        return isset($this->record[$field]) ? $this->record[$field] : null;
2619
    }
2620
2621
    /**
2622
     * Loads all the stub fields that an initial lazy load didn't load fully.
2623
     *
2624
     * @param string $class Class to load the values from. Others are joined as required.
2625
     * Not specifying a tableClass will load all lazy fields from all tables.
2626
     * @return bool Flag if lazy loading succeeded
2627
     */
2628
    protected function loadLazyFields($class = null)
2629
    {
2630
        if (!$this->isInDB() || !is_numeric($this->ID)) {
2631
            return false;
2632
        }
2633
2634
        if (!$class) {
2635
            $loaded = [];
2636
2637
            foreach ($this->record as $key => $value) {
2638
                if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
2639
                    $this->loadLazyFields($value);
2640
                    $loaded[$value] = $value;
2641
                }
2642
            }
2643
2644
            return false;
2645
        }
2646
2647
        $dataQuery = new DataQuery($class);
2648
2649
        // Reset query parameter context to that of this DataObject
2650
        if ($params = $this->getSourceQueryParams()) {
2651
            foreach ($params as $key => $value) {
2652
                $dataQuery->setQueryParam($key, $value);
2653
            }
2654
        }
2655
2656
        // Limit query to the current record, unless it has the Versioned extension,
2657
        // in which case it requires special handling through augmentLoadLazyFields()
2658
        $schema = static::getSchema();
2659
        $baseIDColumn = $schema->sqlColumnForField($this, 'ID');
2660
        $dataQuery->where([
2661
            $baseIDColumn => $this->record['ID']
2662
        ])->limit(1);
2663
2664
        $columns = [];
2665
2666
        // Add SQL for fields, both simple & multi-value
2667
        // TODO: This is copy & pasted from buildSQL(), it could be moved into a method
2668
        $databaseFields = $schema->databaseFields($class, false);
2669
        foreach ($databaseFields as $k => $v) {
2670
            if (!isset($this->record[$k]) || $this->record[$k] === null) {
2671
                $columns[] = $k;
2672
            }
2673
        }
2674
2675
        if ($columns) {
2676
            $query = $dataQuery->query();
2677
            $this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
2678
            $this->extend('augmentSQL', $query, $dataQuery);
2679
2680
            $dataQuery->setQueriedColumns($columns);
2681
            $newData = $dataQuery->execute()->record();
2682
2683
            // Load the data into record
2684
            if ($newData) {
2685
                foreach ($newData as $k => $v) {
2686
                    if (in_array($k, $columns)) {
2687
                        $this->record[$k] = $v;
2688
                        $this->original[$k] = $v;
2689
                        unset($this->record[$k . '_Lazy']);
2690
                    }
2691
                }
2692
2693
            // No data means that the query returned nothing; assign 'null' to all the requested fields
2694
            } else {
2695
                foreach ($columns as $k) {
2696
                    $this->record[$k] = null;
2697
                    $this->original[$k] = null;
2698
                    unset($this->record[$k . '_Lazy']);
2699
                }
2700
            }
2701
        }
2702
        return true;
2703
    }
2704
2705
    /**
2706
     * Return the fields that have changed since the last write.
2707
     *
2708
     * The change level affects what the functions defines as "changed":
2709
     * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
2710
     * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
2711
     *   for example a change from 0 to null would not be included.
2712
     *
2713
     * Example return:
2714
     * <code>
2715
     * array(
2716
     *   'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
2717
     * )
2718
     * </code>
2719
     *
2720
     * @param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true
2721
     * to return all database fields, or an array for an explicit filter. false returns all fields.
2722
     * @param int $changeLevel The strictness of what is defined as change. Defaults to strict
2723
     * @return array
2724
     */
2725
    public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT)
2726
    {
2727
        $changedFields = [];
2728
2729
        // Update the changed array with references to changed obj-fields
2730
        foreach ($this->record as $k => $v) {
2731
            // Prevents DBComposite infinite looping on isChanged
2732
            if (is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
2733
                continue;
2734
            }
2735
            if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
2736
                $this->changed[$k] = self::CHANGE_VALUE;
2737
            }
2738
        }
2739
2740
        // If change was forced, then derive change data from $this->record
2741
        if ($this->changeForced && $changeLevel <= self::CHANGE_STRICT) {
2742
            $changed = array_combine(
2743
                array_keys($this->record),
2744
                array_fill(0, count($this->record), self::CHANGE_STRICT)
2745
            );
2746
            // @todo Find better way to allow versioned to write a new version after forceChange
2747
            unset($changed['Version']);
2748
        } else {
2749
            $changed = $this->changed;
2750
        }
2751
2752
        if (is_array($databaseFieldsOnly)) {
2753
            $fields = array_intersect_key($changed, array_flip($databaseFieldsOnly));
2754
        } elseif ($databaseFieldsOnly) {
2755
            $fieldsSpecs = static::getSchema()->fieldSpecs(static::class);
2756
            $fields = array_intersect_key($changed, $fieldsSpecs);
2757
        } else {
2758
            $fields = $changed;
2759
        }
2760
2761
        // Filter the list to those of a certain change level
2762
        if ($changeLevel > self::CHANGE_STRICT) {
2763
            if ($fields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fields of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2764
                foreach ($fields as $name => $level) {
2765
                    if ($level < $changeLevel) {
2766
                        unset($fields[$name]);
2767
                    }
2768
                }
2769
            }
2770
        }
2771
2772
        if ($fields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fields of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2773
            foreach ($fields as $name => $level) {
2774
                $changedFields[$name] = [
2775
                    'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
2776
                    'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
2777
                    'level' => $level
2778
                ];
2779
            }
2780
        }
2781
2782
        return $changedFields;
2783
    }
2784
2785
    /**
2786
     * Uses {@link getChangedFields()} to determine if fields have been changed
2787
     * since loading them from the database.
2788
     *
2789
     * @param string $fieldName Name of the database field to check, will check for any if not given
2790
     * @param int $changeLevel See {@link getChangedFields()}
2791
     * @return boolean
2792
     */
2793
    public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT)
2794
    {
2795
        $fields = $fieldName ? [$fieldName] : true;
2796
        $changed = $this->getChangedFields($fields, $changeLevel);
2797
        if (!isset($fieldName)) {
2798
            return !empty($changed);
2799
        } else {
2800
            return array_key_exists($fieldName, $changed);
2801
        }
2802
    }
2803
2804
    /**
2805
     * Set the value of the field
2806
     * Called by {@link __set()} and any setFieldName() methods you might create.
2807
     *
2808
     * @param string $fieldName Name of the field
2809
     * @param mixed $val New field value
2810
     * @return $this
2811
     */
2812
    public function setField($fieldName, $val)
2813
    {
2814
        $this->objCacheClear();
2815
        //if it's a has_one component, destroy the cache
2816
        if (substr($fieldName, -2) == 'ID') {
2817
            unset($this->components[substr($fieldName, 0, -2)]);
2818
        }
2819
2820
        // If we've just lazy-loaded the column, then we need to populate the $original array
2821
        if (isset($this->record[$fieldName . '_Lazy'])) {
2822
            $tableClass = $this->record[$fieldName . '_Lazy'];
2823
            $this->loadLazyFields($tableClass);
2824
        }
2825
2826
        // Support component assignent via field setter
2827
        $schema = static::getSchema();
2828
        if ($schema->unaryComponent(static::class, $fieldName)) {
2829
            unset($this->components[$fieldName]);
2830
            // Assign component directly
2831
            if (is_null($val) || $val instanceof DataObject) {
2832
                return $this->setComponent($fieldName, $val);
2833
            }
2834
            // Assign by ID instead of object
2835
            if (is_numeric($val)) {
2836
                $fieldName .= 'ID';
2837
            }
2838
        }
2839
2840
        // Situation 1: Passing an DBField
2841
        if ($val instanceof DBField) {
2842
            $val->setName($fieldName);
2843
            $val->saveInto($this);
2844
2845
            // Situation 1a: Composite fields should remain bound in case they are
2846
            // later referenced to update the parent dataobject
2847
            if ($val instanceof DBComposite) {
2848
                $val->bindTo($this);
2849
                $this->record[$fieldName] = $val;
2850
            }
2851
        // Situation 2: Passing a literal or non-DBField object
2852
        } else {
2853
            // If this is a proper database field, we shouldn't be getting non-DBField objects
2854
            if (is_object($val) && $schema->fieldSpec(static::class, $fieldName)) {
2855
                throw new InvalidArgumentException('DataObject::setField: passed an object that is not a DBField');
2856
            }
2857
2858
            if (!empty($val) && !is_scalar($val)) {
2859
                $dbField = $this->dbObject($fieldName);
2860
                if ($dbField && $dbField->scalarValueOnly()) {
2861
                    throw new InvalidArgumentException(
2862
                        sprintf(
2863
                            'DataObject::setField: %s only accepts scalars',
2864
                            $fieldName
2865
                        )
2866
                    );
2867
                }
2868
            }
2869
2870
            // if a field is not existing or has strictly changed
2871
            if (!array_key_exists($fieldName, $this->original) || $this->original[$fieldName] !== $val) {
2872
                // TODO Add check for php-level defaults which are not set in the db
2873
                // TODO Add check for hidden input-fields (readonly) which are not set in the db
2874
                // At the very least, the type has changed
2875
                $this->changed[$fieldName] = self::CHANGE_STRICT;
2876
2877
                if ((!array_key_exists($fieldName, $this->original) && $val)
2878
                    || (array_key_exists($fieldName, $this->original) && $this->original[$fieldName] != $val)
2879
                ) {
2880
                    // Value has changed as well, not just the type
2881
                    $this->changed[$fieldName] = self::CHANGE_VALUE;
2882
                }
2883
            // Value has been restored to its original, remove any record of the change
2884
            } elseif (isset($this->changed[$fieldName])) {
2885
                unset($this->changed[$fieldName]);
2886
            }
2887
2888
            // Value is saved regardless, since the change detection relates to the last write
2889
            $this->record[$fieldName] = $val;
2890
        }
2891
        return $this;
2892
    }
2893
2894
    /**
2895
     * Set the value of the field, using a casting object.
2896
     * This is useful when you aren't sure that a date is in SQL format, for example.
2897
     * setCastedField() can also be used, by forms, to set related data.  For example, uploaded images
2898
     * can be saved into the Image table.
2899
     *
2900
     * @param string $fieldName Name of the field
2901
     * @param mixed $value New field value
2902
     * @return $this
2903
     */
2904
    public function setCastedField($fieldName, $value)
2905
    {
2906
        if (!$fieldName) {
2907
            throw new InvalidArgumentException("DataObject::setCastedField: Called without a fieldName");
2908
        }
2909
        $fieldObj = $this->dbObject($fieldName);
2910
        if ($fieldObj) {
0 ignored issues
show
introduced by
$fieldObj is of type SilverStripe\ORM\FieldType\DBField, thus it always evaluated to true.
Loading history...
2911
            $fieldObj->setValue($value);
2912
            $fieldObj->saveInto($this);
2913
        } else {
2914
            $this->$fieldName = $value;
2915
        }
2916
        return $this;
2917
    }
2918
2919
    /**
2920
     * {@inheritdoc}
2921
     */
2922
    public function castingHelper($field)
2923
    {
2924
        $fieldSpec = static::getSchema()->fieldSpec(static::class, $field);
2925
        if ($fieldSpec) {
2926
            return $fieldSpec;
2927
        }
2928
2929
        // many_many_extraFields aren't presented by db(), so we check if the source query params
2930
        // provide us with meta-data for a many_many relation we can inspect for extra fields.
2931
        $queryParams = $this->getSourceQueryParams();
2932
        if (!empty($queryParams['Component.ExtraFields'])) {
2933
            $extraFields = $queryParams['Component.ExtraFields'];
2934
2935
            if (isset($extraFields[$field])) {
2936
                return $extraFields[$field];
2937
            }
2938
        }
2939
2940
        return parent::castingHelper($field);
2941
    }
2942
2943
    /**
2944
     * Returns true if the given field exists in a database column on any of
2945
     * the objects tables and optionally look up a dynamic getter with
2946
     * get<fieldName>().
2947
     *
2948
     * @param string $field Name of the field
2949
     * @return boolean True if the given field exists
2950
     */
2951
    public function hasField($field)
2952
    {
2953
        $schema = static::getSchema();
2954
        return (
2955
            array_key_exists($field, $this->record)
2956
            || array_key_exists($field, $this->components)
2957
            || $schema->fieldSpec(static::class, $field)
2958
            || $schema->unaryComponent(static::class, $field)
2959
            || $this->hasMethod("get{$field}")
2960
        );
2961
    }
2962
2963
    /**
2964
     * Returns true if the given field exists as a database column
2965
     *
2966
     * @param string $field Name of the field
2967
     *
2968
     * @return boolean
2969
     */
2970
    public function hasDatabaseField($field)
2971
    {
2972
        $spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY);
2973
        return !empty($spec);
2974
    }
2975
2976
    /**
2977
     * Returns true if the member is allowed to do the given action.
2978
     * See {@link extendedCan()} for a more versatile tri-state permission control.
2979
     *
2980
     * @param string $perm The permission to be checked, such as 'View'.
2981
     * @param Member $member The member whose permissions need checking.  Defaults to the currently logged
2982
     * in user.
2983
     * @param array $context Additional $context to pass to extendedCan()
2984
     *
2985
     * @return boolean True if the the member is allowed to do the given action
2986
     */
2987
    public function can($perm, $member = null, $context = [])
2988
    {
2989
        if (!$member) {
2990
            $member = Security::getCurrentUser();
2991
        }
2992
2993
        if ($member && Permission::checkMember($member, "ADMIN")) {
2994
            return true;
2995
        }
2996
2997
        if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
2998
            $method = 'can' . ucfirst($perm);
2999
            return $this->$method($member);
3000
        }
3001
3002
        $results = $this->extendedCan('can', $member);
3003
        if (isset($results)) {
3004
            return $results;
3005
        }
3006
3007
        return ($member && Permission::checkMember($member, $perm));
3008
    }
3009
3010
    /**
3011
     * Process tri-state responses from permission-alterting extensions.  The extensions are
3012
     * expected to return one of three values:
3013
     *
3014
     *  - false: Disallow this permission, regardless of what other extensions say
3015
     *  - true: Allow this permission, as long as no other extensions return false
3016
     *  - NULL: Don't affect the outcome
3017
     *
3018
     * This method itself returns a tri-state value, and is designed to be used like this:
3019
     *
3020
     * <code>
3021
     * $extended = $this->extendedCan('canDoSomething', $member);
3022
     * if($extended !== null) return $extended;
3023
     * else return $normalValue;
3024
     * </code>
3025
     *
3026
     * @param string $methodName Method on the same object, e.g. {@link canEdit()}
3027
     * @param Member|int $member
3028
     * @param array $context Optional context
3029
     * @return boolean|null
3030
     */
3031
    public function extendedCan($methodName, $member, $context = [])
3032
    {
3033
        $results = $this->extend($methodName, $member, $context);
3034
        if ($results && is_array($results)) {
3035
            // Remove NULLs
3036
            $results = array_filter($results, function ($v) {
3037
                return !is_null($v);
3038
            });
3039
            // If there are any non-NULL responses, then return the lowest one of them.
3040
            // If any explicitly deny the permission, then we don't get access
3041
            if ($results) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3042
                return min($results);
3043
            }
3044
        }
3045
        return null;
3046
    }
3047
3048
    /**
3049
     * @param Member $member
3050
     * @return boolean
3051
     */
3052
    public function canView($member = null)
3053
    {
3054
        $extended = $this->extendedCan(__FUNCTION__, $member);
3055
        if ($extended !== null) {
3056
            return $extended;
3057
        }
3058
        return Permission::check('ADMIN', 'any', $member);
3059
    }
3060
3061
    /**
3062
     * @param Member $member
3063
     * @return boolean
3064
     */
3065
    public function canEdit($member = null)
3066
    {
3067
        $extended = $this->extendedCan(__FUNCTION__, $member);
3068
        if ($extended !== null) {
3069
            return $extended;
3070
        }
3071
        return Permission::check('ADMIN', 'any', $member);
3072
    }
3073
3074
    /**
3075
     * @param Member $member
3076
     * @return boolean
3077
     */
3078
    public function canDelete($member = null)
3079
    {
3080
        $extended = $this->extendedCan(__FUNCTION__, $member);
3081
        if ($extended !== null) {
3082
            return $extended;
3083
        }
3084
        return Permission::check('ADMIN', 'any', $member);
3085
    }
3086
3087
    /**
3088
     * @param Member $member
3089
     * @param array $context Additional context-specific data which might
3090
     * affect whether (or where) this object could be created.
3091
     * @return boolean
3092
     */
3093
    public function canCreate($member = null, $context = [])
3094
    {
3095
        $extended = $this->extendedCan(__FUNCTION__, $member, $context);
3096
        if ($extended !== null) {
3097
            return $extended;
3098
        }
3099
        return Permission::check('ADMIN', 'any', $member);
3100
    }
3101
3102
    /**
3103
     * Debugging used by Debug::show()
3104
     *
3105
     * @return string HTML data representing this object
3106
     */
3107
    public function debug()
3108
    {
3109
        $class = static::class;
3110
        $val = "<h3>Database record: {$class}</h3>\n<ul>\n";
3111
        if ($this->record) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->record of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3112
            foreach ($this->record as $fieldName => $fieldVal) {
3113
                $val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
3114
            }
3115
        }
3116
        $val .= "</ul>\n";
3117
        return $val;
3118
    }
3119
3120
    /**
3121
     * Return the DBField object that represents the given field.
3122
     * This works similarly to obj() with 2 key differences:
3123
     *   - it still returns an object even when the field has no value.
3124
     *   - it only matches fields and not methods
3125
     *   - it matches foreign keys generated by has_one relationships, eg, "ParentID"
3126
     *
3127
     * @param string $fieldName Name of the field
3128
     * @return DBField The field as a DBField object
3129
     */
3130
    public function dbObject($fieldName)
3131
    {
3132
        // Check for field in DB
3133
        $schema = static::getSchema();
3134
        $helper = $schema->fieldSpec(static::class, $fieldName, DataObjectSchema::INCLUDE_CLASS);
3135
        if (!$helper) {
3136
            return null;
3137
        }
3138
3139
        if (!isset($this->record[$fieldName]) && isset($this->record[$fieldName . '_Lazy'])) {
3140
            $tableClass = $this->record[$fieldName . '_Lazy'];
3141
            $this->loadLazyFields($tableClass);
3142
        }
3143
3144
        $value = isset($this->record[$fieldName])
3145
            ? $this->record[$fieldName]
3146
            : null;
3147
3148
        // If we have a DBField object in $this->record, then return that
3149
        if ($value instanceof DBField) {
3150
            return $value;
3151
        }
3152
3153
        $pos = strpos($helper, '.');
3154
        $class = substr($helper, 0, $pos);
3155
        $spec = substr($helper, $pos + 1);
3156
3157
        /** @var DBField $obj */
3158
        $table = $schema->tableName($class);
3159
        $obj = Injector::inst()->create($spec, $fieldName);
3160
        $obj->setTable($table);
3161
        $obj->setValue($value, $this, false);
3162
        return $obj;
3163
    }
3164
3165
    /**
3166
     * Traverses to a DBField referenced by relationships between data objects.
3167
     *
3168
     * The path to the related field is specified with dot separated syntax
3169
     * (eg: Parent.Child.Child.FieldName).
3170
     *
3171
     * If a relation is blank, this will return null instead.
3172
     * If a relation name is invalid (e.g. non-relation on a parent) this
3173
     * can throw a LogicException.
3174
     *
3175
     * @param string $fieldPath List of paths on this object. All items in this path
3176
     * must be ViewableData implementors
3177
     *
3178
     * @return mixed DBField of the field on the object or a DataList instance.
3179
     * @throws LogicException If accessing invalid relations
3180
     */
3181
    public function relObject($fieldPath)
3182
    {
3183
        $object = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $object is dead and can be removed.
Loading history...
3184
        $component = $this;
3185
3186
        // Parse all relations
3187
        foreach (explode('.', $fieldPath) as $relation) {
3188
            if (!$component) {
3189
                return null;
3190
            }
3191
3192
            // Inspect relation type
3193
            if (ClassInfo::hasMethod($component, $relation)) {
3194
                $component = $component->$relation();
3195
            } elseif ($component instanceof Relation || $component instanceof DataList) {
3196
                // $relation could either be a field (aggregate), or another relation
3197
                $singleton = DataObject::singleton($component->dataClass());
0 ignored issues
show
Bug introduced by
The method dataClass() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3197
                $singleton = DataObject::singleton($component->/** @scrutinizer ignore-call */ dataClass());
Loading history...
3198
                $component = $singleton->dbObject($relation) ?: $component->relation($relation);
0 ignored issues
show
Bug introduced by
The method relation() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3198
                $component = $singleton->dbObject($relation) ?: $component->/** @scrutinizer ignore-call */ relation($relation);
Loading history...
3199
            } elseif ($component instanceof DataObject && ($dbObject = $component->dbObject($relation))) {
3200
                $component = $dbObject;
3201
            } elseif ($component instanceof ViewableData && $component->hasField($relation)) {
3202
                $component = $component->obj($relation);
3203
            } else {
3204
                throw new LogicException(
3205
                    "$relation is not a relation/field on " . get_class($component)
3206
                );
3207
            }
3208
        }
3209
        return $component;
3210
    }
3211
3212
    /**
3213
     * Traverses to a field referenced by relationships between data objects, returning the value
3214
     * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)
3215
     *
3216
     * @param string $fieldName string
3217
     * @return mixed Will return null on a missing value
3218
     */
3219
    public function relField($fieldName)
3220
    {
3221
        // Navigate to relative parent using relObject() if needed
3222
        $component = $this;
3223
        if (($pos = strrpos($fieldName, '.')) !== false) {
3224
            $relation = substr($fieldName, 0, $pos);
3225
            $fieldName = substr($fieldName, $pos + 1);
3226
            $component = $this->relObject($relation);
3227
        }
3228
3229
        // Bail if the component is null
3230
        if (!$component) {
3231
            return null;
3232
        }
3233
        if (ClassInfo::hasMethod($component, $fieldName)) {
3234
            return $component->$fieldName();
3235
        }
3236
        return $component->$fieldName;
3237
    }
3238
3239
    /**
3240
     * Temporary hack to return an association name, based on class, to get around the mangle
3241
     * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
3242
     *
3243
     * @param string $className
3244
     * @return string
3245
     */
3246
    public function getReverseAssociation($className)
3247
    {
3248
        if (is_array($this->manyMany())) {
0 ignored issues
show
introduced by
The condition is_array($this->manyMany()) is always true.
Loading history...
3249
            $many_many = array_flip($this->manyMany());
3250
            if (array_key_exists($className, $many_many)) {
3251
                return $many_many[$className];
3252
            }
3253
        }
3254
        if (is_array($this->hasMany())) {
0 ignored issues
show
introduced by
The condition is_array($this->hasMany()) is always true.
Loading history...
3255
            $has_many = array_flip($this->hasMany());
3256
            if (array_key_exists($className, $has_many)) {
3257
                return $has_many[$className];
3258
            }
3259
        }
3260
        if (is_array($this->hasOne())) {
0 ignored issues
show
introduced by
The condition is_array($this->hasOne()) is always true.
Loading history...
3261
            $has_one = array_flip($this->hasOne());
3262
            if (array_key_exists($className, $has_one)) {
3263
                return $has_one[$className];
3264
            }
3265
        }
3266
3267
        return false;
3268
    }
3269
3270
    /**
3271
     * Return all objects matching the filter
3272
     * sub-classes are automatically selected and included
3273
     *
3274
     * @param string $callerClass The class of objects to be returned
3275
     * @param string|array $filter A filter to be inserted into the WHERE clause.
3276
     * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
3277
     * @param string|array $sort A sort expression to be inserted into the ORDER
3278
     * BY clause.  If omitted, self::$default_sort will be used.
3279
     * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
3280
     * @param string|array $limit A limit expression to be inserted into the LIMIT clause.
3281
     * @param string $containerClass The container class to return the results in.
3282
     *
3283
     * @todo $containerClass is Ignored, why?
3284
     *
3285
     * @return DataList The objects matching the filter, in the class specified by $containerClass
3286
     */
3287
    public static function get(
3288
        $callerClass = null,
3289
        $filter = "",
3290
        $sort = "",
3291
        $join = "",
3292
        $limit = null,
3293
        $containerClass = DataList::class
3294
    ) {
3295
        // Validate arguments
3296
        if ($callerClass == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $callerClass of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
3297
            $callerClass = get_called_class();
3298
            if ($callerClass === self::class) {
3299
                throw new InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
3300
            }
3301
            if ($filter || $sort || $join || $limit || ($containerClass !== DataList::class)) {
3302
                throw new InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
3303
                    . ' arguments');
3304
            }
3305
        } elseif ($callerClass === self::class) {
3306
            throw new InvalidArgumentException('DataObject::get() cannot query non-subclass DataObject directly');
3307
        }
3308
        if ($join) {
3309
            throw new InvalidArgumentException(
3310
                'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
3311
            );
3312
        }
3313
3314
        // Build and decorate with args
3315
        $result = DataList::create($callerClass);
3316
        if ($filter) {
3317
            $result = $result->where($filter);
3318
        }
3319
        if ($sort) {
3320
            $result = $result->sort($sort);
3321
        }
3322
        if ($limit && strpos($limit, ',') !== false) {
0 ignored issues
show
Bug introduced by
It seems like $limit can also be of type array; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3322
        if ($limit && strpos(/** @scrutinizer ignore-type */ $limit, ',') !== false) {
Loading history...
3323
            $limitArguments = explode(',', $limit);
0 ignored issues
show
Bug introduced by
It seems like $limit can also be of type array; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3323
            $limitArguments = explode(',', /** @scrutinizer ignore-type */ $limit);
Loading history...
3324
            $result = $result->limit($limitArguments[1], $limitArguments[0]);
3325
        } elseif ($limit) {
3326
            $result = $result->limit($limit);
3327
        }
3328
3329
        return $result;
3330
    }
3331
3332
3333
    /**
3334
     * Return the first item matching the given query.
3335
     *
3336
     * The object returned is cached, unlike DataObject::get()->first() {@link DataList::first()}
3337
     * and DataObject::get()->last() {@link DataList::last()}
3338
     *
3339
     * The filter argument supports parameterised queries (see SQLSelect::addWhere() for syntax examples). Because
3340
     * of that (and differently from e.g. DataList::filter()) you need to manually escape the field names:
3341
     * <code>
3342
     * $member = DataObject::get_one('Member', [ '"FirstName"' => 'John' ]);
3343
     * </code>
3344
     *
3345
     * @param string $callerClass The class of objects to be returned
3346
     * @param string|array $filter A filter to be inserted into the WHERE clause.
3347
     * @param boolean $cache Use caching
3348
     * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
3349
     *
3350
     * @return DataObject|null The first item matching the query
3351
     */
3352
    public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "")
3353
    {
3354
        /** @var DataObject $singleton */
3355
        $singleton = singleton($callerClass);
3356
3357
        $cacheComponents = [$filter, $orderby, $singleton->getUniqueKeyComponents()];
3358
        $cacheKey = md5(serialize($cacheComponents));
3359
3360
        $item = null;
3361
        if (!$cache || !isset(self::$_cache_get_one[$callerClass][$cacheKey])) {
3362
            $dl = DataObject::get($callerClass)->where($filter)->sort($orderby);
3363
            $item = $dl->first();
3364
3365
            if ($cache) {
3366
                self::$_cache_get_one[$callerClass][$cacheKey] = $item;
3367
                if (!self::$_cache_get_one[$callerClass][$cacheKey]) {
3368
                    self::$_cache_get_one[$callerClass][$cacheKey] = false;
3369
                }
3370
            }
3371
        }
3372
3373
        if ($cache) {
3374
            return self::$_cache_get_one[$callerClass][$cacheKey] ?: null;
3375
        }
3376
3377
        return $item;
3378
    }
3379
3380
    /**
3381
     * Flush the cached results for all relations (has_one, has_many, many_many)
3382
     * Also clears any cached aggregate data.
3383
     *
3384
     * @param boolean $persistent When true will also clear persistent data stored in the Cache system.
3385
     *                            When false will just clear session-local cached data
3386
     * @return DataObject $this
3387
     */
3388
    public function flushCache($persistent = true)
3389
    {
3390
        if (static::class == self::class) {
0 ignored issues
show
introduced by
The condition static::class == self::class is always true.
Loading history...
3391
            self::$_cache_get_one = [];
3392
            return $this;
3393
        }
3394
3395
        $classes = ClassInfo::ancestry(static::class);
3396
        foreach ($classes as $class) {
3397
            if (isset(self::$_cache_get_one[$class])) {
3398
                unset(self::$_cache_get_one[$class]);
3399
            }
3400
        }
3401
3402
        $this->extend('flushCache');
3403
3404
        $this->components = [];
3405
        return $this;
3406
    }
3407
3408
    /**
3409
     * Flush the get_one global cache and destroy associated objects.
3410
     */
3411
    public static function flush_and_destroy_cache()
3412
    {
3413
        if (self::$_cache_get_one) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::_cache_get_one of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3414
            foreach (self::$_cache_get_one as $class => $items) {
3415
                if (is_array($items)) {
3416
                    foreach ($items as $item) {
3417
                        if ($item) {
3418
                            $item->destroy();
3419
                        }
3420
                    }
3421
                }
3422
            }
3423
        }
3424
        self::$_cache_get_one = [];
3425
    }
3426
3427
    /**
3428
     * Reset all global caches associated with DataObject.
3429
     */
3430
    public static function reset()
3431
    {
3432
        // @todo Decouple these
3433
        DBEnum::flushCache();
3434
        ClassInfo::reset_db_cache();
3435
        static::getSchema()->reset();
3436
        self::$_cache_get_one = [];
3437
        self::$_cache_field_labels = [];
3438
    }
3439
3440
    /**
3441
     * Return the given element, searching by ID.
3442
     *
3443
     * This can be called either via `DataObject::get_by_id(MyClass::class, $id)`
3444
     * or `MyClass::get_by_id($id)`
3445
     *
3446
     * The object returned is cached, unlike DataObject::get()->byID() {@link DataList::byID()}
3447
     *
3448
     * @param string|int $classOrID The class of the object to be returned, or id if called on target class
3449
     * @param int|bool $idOrCache The id of the element, or cache if called on target class
3450
     * @param boolean $cache See {@link get_one()}
3451
     *
3452
     * @return static The element
3453
     */
3454
    public static function get_by_id($classOrID, $idOrCache = null, $cache = true)
3455
    {
3456
        // Shift arguments if passing id in first or second argument
3457
        list ($class, $id, $cached) = is_numeric($classOrID)
3458
            ? [get_called_class(), $classOrID, isset($idOrCache) ? $idOrCache : $cache]
3459
            : [$classOrID, $idOrCache, $cache];
3460
3461
        // Validate class
3462
        if ($class === self::class) {
3463
            throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly');
3464
        }
3465
3466
        // Pass to get_one
3467
        $column = static::getSchema()->sqlColumnForField($class, 'ID');
3468
        return DataObject::get_one($class, [$column => $id], $cached);
3469
    }
3470
3471
    /**
3472
     * Get the name of the base table for this object
3473
     *
3474
     * @return string
3475
     */
3476
    public function baseTable()
3477
    {
3478
        return static::getSchema()->baseDataTable($this);
3479
    }
3480
3481
    /**
3482
     * Get the base class for this object
3483
     *
3484
     * @return string
3485
     */
3486
    public function baseClass()
3487
    {
3488
        return static::getSchema()->baseDataClass($this);
3489
    }
3490
3491
    /**
3492
     * @var array Parameters used in the query that built this object.
3493
     * This can be used by decorators (e.g. lazy loading) to
3494
     * run additional queries using the same context.
3495
     */
3496
    protected $sourceQueryParams;
3497
3498
    /**
3499
     * @see $sourceQueryParams
3500
     * @return array
3501
     */
3502
    public function getSourceQueryParams()
3503
    {
3504
        return $this->sourceQueryParams;
3505
    }
3506
3507
    /**
3508
     * Get list of parameters that should be inherited to relations on this object
3509
     *
3510
     * @return array
3511
     */
3512
    public function getInheritableQueryParams()
3513
    {
3514
        $params = $this->getSourceQueryParams();
3515
        $this->extend('updateInheritableQueryParams', $params);
3516
        return $params;
3517
    }
3518
3519
    /**
3520
     * @see $sourceQueryParams
3521
     * @param array $array
3522
     */
3523
    public function setSourceQueryParams($array)
3524
    {
3525
        $this->sourceQueryParams = $array;
3526
    }
3527
3528
    /**
3529
     * @see $sourceQueryParams
3530
     * @param string $key
3531
     * @param string $value
3532
     */
3533
    public function setSourceQueryParam($key, $value)
3534
    {
3535
        $this->sourceQueryParams[$key] = $value;
3536
    }
3537
3538
    /**
3539
     * @see $sourceQueryParams
3540
     * @param string $key
3541
     * @return string
3542
     */
3543
    public function getSourceQueryParam($key)
3544
    {
3545
        if (isset($this->sourceQueryParams[$key])) {
3546
            return $this->sourceQueryParams[$key];
3547
        }
3548
        return null;
3549
    }
3550
3551
    //-------------------------------------------------------------------------------------------//
3552
3553
    /**
3554
     * Check the database schema and update it as necessary.
3555
     *
3556
     * @uses DataExtension::augmentDatabase()
3557
     */
3558
    public function requireTable()
3559
    {
3560
        // Only build the table if we've actually got fields
3561
        $schema = static::getSchema();
3562
        $table = $schema->tableName(static::class);
3563
        $fields = $schema->databaseFields(static::class, false);
3564
        $indexes = $schema->databaseIndexes(static::class, false);
3565
        $extensions = self::database_extensions(static::class);
0 ignored issues
show
Bug Best Practice introduced by
The method SilverStripe\ORM\DataObject::database_extensions() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

3565
        /** @scrutinizer ignore-call */ 
3566
        $extensions = self::database_extensions(static::class);
Loading history...
3566
3567
        if (empty($table)) {
3568
            throw new LogicException(
3569
                "Class " . static::class . " not loaded by manifest, or no database table configured"
3570
            );
3571
        }
3572
3573
        if ($fields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fields of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3574
            $hasAutoIncPK = get_parent_class($this) === self::class;
3575
            DB::require_table(
3576
                $table,
3577
                $fields,
0 ignored issues
show
Bug introduced by
$fields of type array is incompatible with the type string expected by parameter $fieldSchema of SilverStripe\ORM\DB::require_table(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3577
                /** @scrutinizer ignore-type */ $fields,
Loading history...
3578
                $indexes,
0 ignored issues
show
Bug introduced by
$indexes of type array is incompatible with the type string expected by parameter $indexSchema of SilverStripe\ORM\DB::require_table(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3578
                /** @scrutinizer ignore-type */ $indexes,
Loading history...
3579
                $hasAutoIncPK,
3580
                $this->config()->get('create_table_options'),
3581
                $extensions
0 ignored issues
show
Bug introduced by
It seems like $extensions can also be of type false; however, parameter $extensions of SilverStripe\ORM\DB::require_table() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3581
                /** @scrutinizer ignore-type */ $extensions
Loading history...
3582
            );
3583
        } else {
3584
            DB::dont_require_table($table);
3585
        }
3586
3587
        // Build any child tables for many_many items
3588
        if ($manyMany = $this->uninherited('many_many')) {
3589
            $extras = $this->uninherited('many_many_extraFields');
3590
            foreach ($manyMany as $component => $spec) {
3591
                // Get many_many spec
3592
                $manyManyComponent = $schema->manyManyComponent(static::class, $component);
3593
                $parentField = $manyManyComponent['parentField'];
3594
                $childField = $manyManyComponent['childField'];
3595
                $tableOrClass = $manyManyComponent['join'];
3596
3597
                // Skip if backed by actual class
3598
                if (class_exists($tableOrClass)) {
3599
                    continue;
3600
                }
3601
3602
                // Build fields
3603
                $manymanyFields = [
3604
                    $parentField => "Int",
3605
                    $childField => "Int",
3606
                ];
3607
                if (isset($extras[$component])) {
3608
                    $manymanyFields = array_merge($manymanyFields, $extras[$component]);
3609
                }
3610
3611
                // Build index list
3612
                $manymanyIndexes = [
3613
                    $parentField => [
3614
                        'type' => 'index',
3615
                        'name' => $parentField,
3616
                        'columns' => [$parentField],
3617
                    ],
3618
                    $childField => [
3619
                        'type' => 'index',
3620
                        'name' => $childField,
3621
                        'columns' => [$childField],
3622
                    ],
3623
                ];
3624
                DB::require_table($tableOrClass, $manymanyFields, $manymanyIndexes, true, null, $extensions);
0 ignored issues
show
Bug introduced by
$manymanyIndexes of type array<mixed,array<string,array|mixed|string>> is incompatible with the type string expected by parameter $indexSchema of SilverStripe\ORM\DB::require_table(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3624
                DB::require_table($tableOrClass, $manymanyFields, /** @scrutinizer ignore-type */ $manymanyIndexes, true, null, $extensions);
Loading history...
Bug introduced by
$manymanyFields of type array|string[] is incompatible with the type string expected by parameter $fieldSchema of SilverStripe\ORM\DB::require_table(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3624
                DB::require_table($tableOrClass, /** @scrutinizer ignore-type */ $manymanyFields, $manymanyIndexes, true, null, $extensions);
Loading history...
3625
            }
3626
        }
3627
3628
        // Let any extentions make their own database fields
3629
        $this->extend('augmentDatabase', $dummy);
3630
    }
3631
3632
    /**
3633
     * Add default records to database. This function is called whenever the
3634
     * database is built, after the database tables have all been created. Overload
3635
     * this to add default records when the database is built, but make sure you
3636
     * call parent::requireDefaultRecords().
3637
     *
3638
     * @uses DataExtension::requireDefaultRecords()
3639
     */
3640
    public function requireDefaultRecords()
3641
    {
3642
        $defaultRecords = $this->config()->uninherited('default_records');
3643
3644
        if (!empty($defaultRecords)) {
3645
            $hasData = DataObject::get_one(static::class);
3646
            if (!$hasData) {
3647
                $className = static::class;
3648
                foreach ($defaultRecords as $record) {
3649
                    $obj = Injector::inst()->create($className, $record);
3650
                    $obj->write();
3651
                }
3652
                DB::alteration_message("Added default records to $className table", "created");
3653
            }
3654
        }
3655
3656
        // Let any extentions make their own database default data
3657
        $this->extend('requireDefaultRecords', $dummy);
3658
    }
3659
3660
    /**
3661
     * Invoked after every database build is complete (including after table creation and
3662
     * default record population).
3663
     *
3664
     * See {@link DatabaseAdmin::doBuild()} for context.
3665
     */
3666
    public function onAfterBuild()
3667
    {
3668
        $this->extend('onAfterBuild');
3669
    }
3670
3671
    /**
3672
     * Get the default searchable fields for this object, as defined in the
3673
     * $searchable_fields list. If searchable fields are not defined on the
3674
     * data object, uses a default selection of summary fields.
3675
     *
3676
     * @return array
3677
     */
3678
    public function searchableFields()
3679
    {
3680
        // can have mixed format, need to make consistent in most verbose form
3681
        $fields = $this->config()->get('searchable_fields');
3682
        $labels = $this->fieldLabels();
3683
3684
        // fallback to summary fields (unless empty array is explicitly specified)
3685
        if (!$fields && !is_array($fields)) {
3686
            $summaryFields = array_keys($this->summaryFields());
3687
            $fields = [];
3688
3689
            // remove the custom getters as the search should not include them
3690
            $schema = static::getSchema();
3691
            if ($summaryFields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $summaryFields of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3692
                foreach ($summaryFields as $key => $name) {
3693
                    $spec = $name;
3694
3695
                    // Extract field name in case this is a method called on a field (e.g. "Date.Nice")
3696
                    if (($fieldPos = strpos($name, '.')) !== false) {
3697
                        $name = substr($name, 0, $fieldPos);
3698
                    }
3699
3700
                    if ($schema->fieldSpec($this, $name)) {
3701
                        $fields[] = $name;
3702
                    } elseif ($this->relObject($spec)) {
3703
                        $fields[] = $spec;
3704
                    }
3705
                }
3706
            }
3707
        }
3708
3709
        // we need to make sure the format is unified before
3710
        // augmenting fields, so extensions can apply consistent checks
3711
        // but also after augmenting fields, because the extension
3712
        // might use the shorthand notation as well
3713
3714
        // rewrite array, if it is using shorthand syntax
3715
        $rewrite = [];
3716
        foreach ($fields as $name => $specOrName) {
3717
            $identifer = (is_int($name)) ? $specOrName : $name;
3718
3719
            if (is_int($name)) {
3720
                // Format: array('MyFieldName')
3721
                $rewrite[$identifer] = [];
3722
            } elseif (is_array($specOrName) && ($relObject = $this->relObject($identifer))) {
3723
                // Format: array('MyFieldName' => array(
3724
                //   'filter => 'ExactMatchFilter',
3725
                //   'field' => 'NumericField', // optional
3726
                //   'title' => 'My Title', // optional
3727
                // ))
3728
                $rewrite[$identifer] = array_merge(
3729
                    ['filter' => $relObject->config()->get('default_search_filter_class')],
3730
                    (array)$specOrName
3731
                );
3732
            } else {
3733
                // Format: array('MyFieldName' => 'ExactMatchFilter')
3734
                $rewrite[$identifer] = [
3735
                    'filter' => $specOrName,
3736
                ];
3737
            }
3738
            if (!isset($rewrite[$identifer]['title'])) {
3739
                $rewrite[$identifer]['title'] = (isset($labels[$identifer]))
3740
                    ? $labels[$identifer] : FormField::name_to_label($identifer);
3741
            }
3742
            if (!isset($rewrite[$identifer]['filter'])) {
3743
                /** @skipUpgrade */
3744
                $rewrite[$identifer]['filter'] = 'PartialMatchFilter';
3745
            }
3746
        }
3747
3748
        $fields = $rewrite;
3749
3750
        // apply DataExtensions if present
3751
        $this->extend('updateSearchableFields', $fields);
3752
3753
        return $fields;
3754
    }
3755
3756
    /**
3757
     * Get any user defined searchable fields labels that
3758
     * exist. Allows overriding of default field names in the form
3759
     * interface actually presented to the user.
3760
     *
3761
     * The reason for keeping this separate from searchable_fields,
3762
     * which would be a logical place for this functionality, is to
3763
     * avoid bloating and complicating the configuration array. Currently
3764
     * much of this system is based on sensible defaults, and this property
3765
     * would generally only be set in the case of more complex relationships
3766
     * between data object being required in the search interface.
3767
     *
3768
     * Generates labels based on name of the field itself, if no static property
3769
     * {@link self::field_labels} exists.
3770
     *
3771
     * @uses $field_labels
3772
     * @uses FormField::name_to_label()
3773
     *
3774
     * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
3775
     *
3776
     * @return array Array of all element labels
3777
     */
3778
    public function fieldLabels($includerelations = true)
3779
    {
3780
        $cacheKey = static::class . '_' . $includerelations;
3781
3782
        if (!isset(self::$_cache_field_labels[$cacheKey])) {
3783
            $customLabels = $this->config()->get('field_labels');
3784
            $autoLabels = [];
3785
3786
            // get all translated static properties as defined in i18nCollectStatics()
3787
            $ancestry = ClassInfo::ancestry(static::class);
3788
            $ancestry = array_reverse($ancestry);
3789
            if ($ancestry) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ancestry of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3790
                foreach ($ancestry as $ancestorClass) {
3791
                    if ($ancestorClass === ViewableData::class) {
3792
                        break;
3793
                    }
3794
                    $types = [
3795
                        'db' => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
3796
                    ];
3797
                    if ($includerelations) {
3798
                        $types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
3799
                        $types['has_many'] = (array)Config::inst()->get(
3800
                            $ancestorClass,
3801
                            'has_many',
3802
                            Config::UNINHERITED
3803
                        );
3804
                        $types['many_many'] = (array)Config::inst()->get(
3805
                            $ancestorClass,
3806
                            'many_many',
3807
                            Config::UNINHERITED
3808
                        );
3809
                        $types['belongs_many_many'] = (array)Config::inst()->get(
3810
                            $ancestorClass,
3811
                            'belongs_many_many',
3812
                            Config::UNINHERITED
3813
                        );
3814
                    }
3815
                    foreach ($types as $type => $attrs) {
3816
                        foreach ($attrs as $name => $spec) {
3817
                            $autoLabels[$name] = _t(
3818
                                "{$ancestorClass}.{$type}_{$name}",
3819
                                FormField::name_to_label($name)
3820
                            );
3821
                        }
3822
                    }
3823
                }
3824
            }
3825
3826
            $labels = array_merge((array)$autoLabels, (array)$customLabels);
3827
            $this->extend('updateFieldLabels', $labels);
3828
            self::$_cache_field_labels[$cacheKey] = $labels;
3829
        }
3830
3831
        return self::$_cache_field_labels[$cacheKey];
3832
    }
3833
3834
    /**
3835
     * Get a human-readable label for a single field,
3836
     * see {@link fieldLabels()} for more details.
3837
     *
3838
     * @uses fieldLabels()
3839
     * @uses FormField::name_to_label()
3840
     *
3841
     * @param string $name Name of the field
3842
     * @return string Label of the field
3843
     */
3844
    public function fieldLabel($name)
3845
    {
3846
        $labels = $this->fieldLabels();
3847
        return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name);
3848
    }
3849
3850
    /**
3851
     * Get the default summary fields for this object.
3852
     *
3853
     * @todo use the translation apparatus to return a default field selection for the language
3854
     *
3855
     * @return array
3856
     */
3857
    public function summaryFields()
3858
    {
3859
        $rawFields = $this->config()->get('summary_fields');
3860
3861
        // Merge associative / numeric keys
3862
        $fields = [];
3863
        foreach ($rawFields as $key => $value) {
3864
            if (is_int($key)) {
3865
                $key = $value;
3866
            }
3867
            $fields[$key] = $value;
3868
        }
3869
3870
        if (!$fields) {
3871
            $fields = [];
3872
            // try to scaffold a couple of usual suspects
3873
            if ($this->hasField('Name')) {
3874
                $fields['Name'] = 'Name';
3875
            }
3876
            if (static::getSchema()->fieldSpec($this, 'Title')) {
3877
                $fields['Title'] = 'Title';
3878
            }
3879
            if ($this->hasField('Description')) {
3880
                $fields['Description'] = 'Description';
3881
            }
3882
            if ($this->hasField('FirstName')) {
3883
                $fields['FirstName'] = 'First Name';
3884
            }
3885
        }
3886
        $this->extend("updateSummaryFields", $fields);
3887
3888
        // Final fail-over, just list ID field
3889
        if (!$fields) {
3890
            $fields['ID'] = 'ID';
3891
        }
3892
3893
        // Localize fields (if possible)
3894
        foreach ($this->fieldLabels(false) as $name => $label) {
3895
            // only attempt to localize if the label definition is the same as the field name.
3896
            // this will preserve any custom labels set in the summary_fields configuration
3897
            if (isset($fields[$name]) && $name === $fields[$name]) {
3898
                $fields[$name] = $label;
3899
            }
3900
        }
3901
3902
        return $fields;
3903
    }
3904
3905
    /**
3906
     * Defines a default list of filters for the search context.
3907
     *
3908
     * If a filter class mapping is defined on the data object,
3909
     * it is constructed here. Otherwise, the default filter specified in
3910
     * {@link DBField} is used.
3911
     *
3912
     * @todo error handling/type checking for valid FormField and SearchFilter subclasses?
3913
     *
3914
     * @return array
3915
     */
3916
    public function defaultSearchFilters()
3917
    {
3918
        $filters = [];
3919
3920
        foreach ($this->searchableFields() as $name => $spec) {
3921
            if (empty($spec['filter'])) {
3922
                /** @skipUpgrade */
3923
                $filters[$name] = 'PartialMatchFilter';
3924
            } elseif ($spec['filter'] instanceof SearchFilter) {
3925
                $filters[$name] = $spec['filter'];
3926
            } else {
3927
                $filters[$name] = Injector::inst()->create($spec['filter'], $name);
3928
            }
3929
        }
3930
3931
        return $filters;
3932
    }
3933
3934
    /**
3935
     * @return boolean True if the object is in the database
3936
     */
3937
    public function isInDB()
3938
    {
3939
        return is_numeric($this->ID) && $this->ID > 0;
3940
    }
3941
3942
    /*
3943
     * @ignore
3944
     */
3945
    private static $subclass_access = true;
3946
3947
    /**
3948
     * Temporarily disable subclass access in data object qeur
3949
     */
3950
    public static function disable_subclass_access()
3951
    {
3952
        self::$subclass_access = false;
3953
    }
3954
3955
    public static function enable_subclass_access()
3956
    {
3957
        self::$subclass_access = true;
3958
    }
3959
3960
    //-------------------------------------------------------------------------------------------//
3961
3962
    /**
3963
     * Database field definitions.
3964
     * This is a map from field names to field type. The field
3965
     * type should be a class that extends .
3966
     * @var array
3967
     * @config
3968
     */
3969
    private static $db = [];
3970
3971
    /**
3972
     * Use a casting object for a field. This is a map from
3973
     * field name to class name of the casting object.
3974
     *
3975
     * @var array
3976
     */
3977
    private static $casting = [
3978
        "Title" => 'Text',
3979
    ];
3980
3981
    /**
3982
     * Specify custom options for a CREATE TABLE call.
3983
     * Can be used to specify a custom storage engine for specific database table.
3984
     * All options have to be keyed for a specific database implementation,
3985
     * identified by their class name (extending from {@link SS_Database}).
3986
     *
3987
     * <code>
3988
     * array(
3989
     *  'MySQLDatabase' => 'ENGINE=MyISAM'
3990
     * )
3991
     * </code>
3992
     *
3993
     * Caution: This API is experimental, and might not be
3994
     * included in the next major release. Please use with care.
3995
     *
3996
     * @var array
3997
     * @config
3998
     */
3999
    private static $create_table_options = [
4000
        MySQLSchemaManager::ID => 'ENGINE=InnoDB'
4001
    ];
4002
4003
    /**
4004
     * If a field is in this array, then create a database index
4005
     * on that field. This is a map from fieldname to index type.
4006
     * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
4007
     *
4008
     * @var array
4009
     * @config
4010
     */
4011
    private static $indexes = null;
4012
4013
    /**
4014
     * Inserts standard column-values when a DataObject
4015
     * is instantiated. Does not insert default records {@see $default_records}.
4016
     * This is a map from fieldname to default value.
4017
     *
4018
     *  - If you would like to change a default value in a sub-class, just specify it.
4019
     *  - If you would like to disable the default value given by a parent class, set the default value to 0,'',
4020
     *    or false in your subclass.  Setting it to null won't work.
4021
     *
4022
     * @var array
4023
     * @config
4024
     */
4025
    private static $defaults = [];
4026
4027
    /**
4028
     * Multidimensional array which inserts default data into the database
4029
     * on a db/build-call as long as the database-table is empty. Please use this only
4030
     * for simple constructs, not for SiteTree-Objects etc. which need special
4031
     * behaviour such as publishing and ParentNodes.
4032
     *
4033
     * Example:
4034
     * array(
4035
     *  array('Title' => "DefaultPage1", 'PageTitle' => 'page1'),
4036
     *  array('Title' => "DefaultPage2")
4037
     * ).
4038
     *
4039
     * @var array
4040
     * @config
4041
     */
4042
    private static $default_records = null;
4043
4044
    /**
4045
     * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a
4046
     * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class.
4047
     *
4048
     * Note that you cannot have a has_one and belongs_to relationship with the same name.
4049
     *
4050
     * @var array
4051
     * @config
4052
     */
4053
    private static $has_one = [];
4054
4055
    /**
4056
     * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.
4057
     *
4058
     * This does not actually create any data structures, but allows you to query the other object in a one-to-one
4059
     * relationship from the child object. If you have multiple belongs_to links to another object you can use the
4060
     * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use.
4061
     *
4062
     * Note that you cannot have a has_one and belongs_to relationship with the same name.
4063
     *
4064
     * @var array
4065
     * @config
4066
     */
4067
    private static $belongs_to = [];
4068
4069
    /**
4070
     * This defines a one-to-many relationship. It is a map of component name to the remote data class.
4071
     *
4072
     * This relationship type does not actually create a data structure itself - you need to define a matching $has_one
4073
     * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this
4074
     * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show
4075
     * which foreign key to use.
4076
     *
4077
     * @var array
4078
     * @config
4079
     */
4080
    private static $has_many = [];
4081
4082
    /**
4083
     * many-many relationship definitions.
4084
     * This is a map from component name to data type.
4085
     * @var array
4086
     * @config
4087
     */
4088
    private static $many_many = [];
4089
4090
    /**
4091
     * Extra fields to include on the connecting many-many table.
4092
     * This is a map from field name to field type.
4093
     *
4094
     * Example code:
4095
     * <code>
4096
     * public static $many_many_extraFields = array(
4097
     *  'Members' => array(
4098
     *          'Role' => 'Varchar(100)'
4099
     *      )
4100
     * );
4101
     * </code>
4102
     *
4103
     * @var array
4104
     * @config
4105
     */
4106
    private static $many_many_extraFields = [];
4107
4108
    /**
4109
     * The inverse side of a many-many relationship.
4110
     * This is a map from component name to data type.
4111
     * @var array
4112
     * @config
4113
     */
4114
    private static $belongs_many_many = [];
4115
4116
    /**
4117
     * The default sort expression. This will be inserted in the ORDER BY
4118
     * clause of a SQL query if no other sort expression is provided.
4119
     * @var string
4120
     * @config
4121
     */
4122
    private static $default_sort = null;
4123
4124
    /**
4125
     * Default list of fields that can be scaffolded by the ModelAdmin
4126
     * search interface.
4127
     *
4128
     * Overriding the default filter, with a custom defined filter:
4129
     * <code>
4130
     *  static $searchable_fields = array(
4131
     *     "Name" => "PartialMatchFilter"
4132
     *  );
4133
     * </code>
4134
     *
4135
     * Overriding the default form fields, with a custom defined field.
4136
     * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}.
4137
     * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}.
4138
     * <code>
4139
     *  static $searchable_fields = array(
4140
     *    "Name" => array(
4141
     *      "field" => "TextField"
4142
     *    )
4143
     *  );
4144
     * </code>
4145
     *
4146
     * Overriding the default form field, filter and title:
4147
     * <code>
4148
     *  static $searchable_fields = array(
4149
     *    "Organisation.ZipCode" => array(
4150
     *      "field" => "TextField",
4151
     *      "filter" => "PartialMatchFilter",
4152
     *      "title" => 'Organisation ZIP'
4153
     *    )
4154
     *  );
4155
     * </code>
4156
     * @config
4157
     * @var array
4158
     */
4159
    private static $searchable_fields = null;
4160
4161
    /**
4162
     * User defined labels for searchable_fields, used to override
4163
     * default display in the search form.
4164
     * @config
4165
     * @var array
4166
     */
4167
    private static $field_labels = [];
4168
4169
    /**
4170
     * Provides a default list of fields to be used by a 'summary'
4171
     * view of this object.
4172
     * @config
4173
     * @var array
4174
     */
4175
    private static $summary_fields = [];
4176
4177
    public function provideI18nEntities()
4178
    {
4179
        // Note: see http://guides.rubyonrails.org/i18n.html#pluralization for rules
4180
        // Best guess for a/an rule. Better guesses require overriding in subclasses
4181
        $pluralName = $this->plural_name();
4182
        $singularName = $this->singular_name();
4183
        $conjunction = preg_match('/^[aeiou]/i', $singularName) ? 'An ' : 'A ';
4184
        return [
4185
            static::class . '.SINGULARNAME' => $this->singular_name(),
4186
            static::class . '.PLURALNAME' => $pluralName,
4187
            static::class . '.PLURALS' => [
4188
                'one' => $conjunction . $singularName,
4189
                'other' => '{count} ' . $pluralName
4190
            ]
4191
        ];
4192
    }
4193
4194
    /**
4195
     * Returns true if the given method/parameter has a value
4196
     * (Uses the DBField::hasValue if the parameter is a database field)
4197
     *
4198
     * @param string $field The field name
4199
     * @param array $arguments
4200
     * @param bool $cache
4201
     * @return boolean
4202
     */
4203
    public function hasValue($field, $arguments = null, $cache = true)
4204
    {
4205
        // has_one fields should not use dbObject to check if a value is given
4206
        $hasOne = static::getSchema()->hasOneComponent(static::class, $field);
4207
        if (!$hasOne && ($obj = $this->dbObject($field))) {
4208
            return $obj->exists();
4209
        } else {
4210
            return parent::hasValue($field, $arguments, $cache);
4211
        }
4212
    }
4213
4214
    /**
4215
     * If selected through a many_many through relation, this is the instance of the joined record
4216
     *
4217
     * @return DataObject
4218
     */
4219
    public function getJoin()
4220
    {
4221
        return $this->joinRecord;
4222
    }
4223
4224
    /**
4225
     * Set joining object
4226
     *
4227
     * @param DataObject $object
4228
     * @param string $alias Alias
4229
     * @return $this
4230
     */
4231
    public function setJoin(DataObject $object, $alias = null)
4232
    {
4233
        $this->joinRecord = $object;
4234
        if ($alias) {
4235
            if (static::getSchema()->fieldSpec(static::class, $alias)) {
4236
                throw new InvalidArgumentException(
4237
                    "Joined record $alias cannot also be a db field"
4238
                );
4239
            }
4240
            $this->record[$alias] = $object;
4241
        }
4242
        return $this;
4243
    }
4244
4245
    /**
4246
     * Find objects in the given relationships, merging them into the given list
4247
     *
4248
     * @param string $source Config property to extract relationships from
4249
     * @param bool $recursive True if recursive
4250
     * @param ArrayList $list If specified, items will be added to this list. If not, a new
4251
     * instance of ArrayList will be constructed and returned
4252
     * @return ArrayList The list of related objects
4253
     */
4254
    public function findRelatedObjects($source, $recursive = true, $list = null)
4255
    {
4256
        if (!$list) {
4257
            $list = new ArrayList();
4258
        }
4259
4260
        // Skip search for unsaved records
4261
        if (!$this->isInDB()) {
4262
            return $list;
4263
        }
4264
4265
        $relationships = $this->config()->get($source) ?: [];
4266
        foreach ($relationships as $relationship) {
4267
            // Warn if invalid config
4268
            if (!$this->hasMethod($relationship)) {
4269
                trigger_error(sprintf(
4270
                    "Invalid %s config value \"%s\" on object on class \"%s\"",
4271
                    $source,
4272
                    $relationship,
4273
                    get_class($this)
4274
                ), E_USER_WARNING);
4275
                continue;
4276
            }
4277
4278
            // Inspect value of this relationship
4279
            $items = $this->{$relationship}();
4280
4281
            // Merge any new item
4282
            $newItems = $this->mergeRelatedObjects($list, $items);
4283
4284
            // Recurse if necessary
4285
            if ($recursive) {
4286
                foreach ($newItems as $item) {
4287
                    /** @var DataObject $item */
4288
                    $item->findRelatedObjects($source, true, $list);
4289
                }
4290
            }
4291
        }
4292
        return $list;
4293
    }
4294
4295
    /**
4296
     * Helper method to merge owned/owning items into a list.
4297
     * Items already present in the list will be skipped.
4298
     *
4299
     * @param ArrayList $list Items to merge into
4300
     * @param mixed $items List of new items to merge
4301
     * @return ArrayList List of all newly added items that did not already exist in $list
4302
     */
4303
    public function mergeRelatedObjects($list, $items)
4304
    {
4305
        $added = new ArrayList();
4306
        if (!$items) {
4307
            return $added;
4308
        }
4309
        if ($items instanceof DataObject) {
4310
            $items = [$items];
4311
        }
4312
4313
        /** @var DataObject $item */
4314
        foreach ($items as $item) {
4315
            $this->mergeRelatedObject($list, $added, $item);
4316
        }
4317
        return $added;
4318
    }
4319
4320
    /**
4321
     * Generate a unique key for data object
4322
     * the unique key uses the @see DataObject::getUniqueKeyComponents() extension point so unique key modifiers
4323
     * such as versioned or fluent are covered
4324
     * i.e. same data object in different stages or different locales will produce different unique key
4325
     *
4326
     * recommended use:
4327
     * - when you need unique key for caching purposes
4328
     * - when you need unique id on the front end (for example JavaScript needs to target specific element)
4329
     *
4330
     * @return string
4331
     * @throws Exception
4332
     */
4333
    public function getUniqueKey(): string
4334
    {
4335
        /** @var UniqueKeyInterface $service */
4336
        $service = Injector::inst()->get(UniqueKeyInterface::class);
4337
        $keyComponents = $this->getUniqueKeyComponents();
4338
4339
        return $service->generateKey($this, $keyComponents);
4340
    }
4341
4342
    /**
4343
     * Merge single object into a list, but ensures that existing objects are not
4344
     * re-added.
4345
     *
4346
     * @param ArrayList $list Global list
4347
     * @param ArrayList $added Additional list to insert into
4348
     * @param DataObject $item Item to add
4349
     */
4350
    protected function mergeRelatedObject($list, $added, $item)
4351
    {
4352
        // Identify item
4353
        $itemKey = get_class($item) . '/' . $item->ID;
4354
4355
        // Write if saved, versioned, and not already added
4356
        if ($item->isInDB() && !isset($list[$itemKey])) {
4357
            $list[$itemKey] = $item;
4358
            $added[$itemKey] = $item;
4359
        }
4360
4361
        // Add joined record (from many_many through) automatically
4362
        $joined = $item->getJoin();
4363
        if ($joined) {
0 ignored issues
show
introduced by
$joined is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
4364
            $this->mergeRelatedObject($list, $added, $joined);
4365
        }
4366
    }
4367
4368
    /**
4369
     * Extension point to add more cache key components.
4370
     * The framework extend method will return combined values from DataExtension method(s) as an array
4371
     * The method on your DataExtension class should return a single scalar value. For example:
4372
     *
4373
     * public function cacheKeyComponent()
4374
     * {
4375
     *      return (string) $this->owner->MyColumn;
4376
     * }
4377
     *
4378
     * @return array
4379
     */
4380
    private function getUniqueKeyComponents(): array
4381
    {
4382
        return $this->extend('cacheKeyComponent');
4383
    }
4384
4385
    /**
4386
     * Find all other DataObject instances that are related to this DataObject in the database
4387
     * through has_one and many_many relationships. For example:
4388
     * This method is called on a File.  The MyPage model $has_one File.  There is a Page record that has
4389
     * a FileID = $this->ID. This SS_List returned by this method will include that Page instance.
4390
     *
4391
     * @param string[] $excludedClasses
4392
     * @return SS_List
4393
     * @internal
4394
     */
4395
    public function findAllRelatedData(array $excludedClasses = []): SS_List
4396
    {
4397
        $service = Injector::inst()->get(RelatedDataService::class);
4398
        return $service->findAll($this, $excludedClasses);
4399
    }
4400
}
4401