Passed
Push — fix-9163 ( 4cfde3...07a516 )
by Ingo
17:14
created

DataObject::scaffoldSearchFields()   C

Complexity

Conditions 14
Paths 21

Size

Total Lines 63
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 36
nc 21
nop 1
dl 0
loc 63
rs 6.2666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        // The join object can be returned as a component, named for its alias
1848
        if (isset($this->record[$componentName]) && $this->record[$componentName] === $this->joinRecord) {
1849
            return $this->record[$componentName];
1850
        }
1851
1852
        $schema = static::getSchema();
1853
        if ($class = $schema->hasOneComponent(static::class, $componentName)) {
1854
            $joinField = $componentName . 'ID';
1855
            $joinID = $this->getField($joinField);
1856
1857
            // Extract class name for polymorphic relations
1858
            if ($class === self::class) {
1859
                $class = $this->getField($componentName . 'Class');
1860
                if (empty($class)) {
1861
                    return null;
1862
                }
1863
            }
1864
1865
            if ($joinID) {
1866
                // Ensure that the selected object originates from the same stage, subsite, etc
1867
                $component = DataObject::get($class)
1868
                    ->filter('ID', $joinID)
1869
                    ->setDataQueryParam($this->getInheritableQueryParams())
1870
                    ->first();
1871
            }
1872
1873
            if (empty($component)) {
1874
                $component = Injector::inst()->create($class);
1875
            }
1876
        } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
1877
            $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
1878
            $joinID = $this->ID;
1879
1880
            if ($joinID) {
1881
                // Prepare filter for appropriate join type
1882
                if ($polymorphic) {
1883
                    $filter = [
1884
                        "{$joinField}ID" => $joinID,
1885
                        "{$joinField}Class" => static::class,
1886
                    ];
1887
                } else {
1888
                    $filter = [
1889
                        $joinField => $joinID
1890
                    ];
1891
                }
1892
1893
                // Ensure that the selected object originates from the same stage, subsite, etc
1894
                $component = DataObject::get($class)
1895
                    ->filter($filter)
1896
                    ->setDataQueryParam($this->getInheritableQueryParams())
1897
                    ->first();
1898
            }
1899
1900
            if (empty($component)) {
1901
                $component = Injector::inst()->create($class);
1902
                if ($polymorphic) {
1903
                    $component->{$joinField . 'ID'} = $this->ID;
1904
                    $component->{$joinField . 'Class'} = static::class;
1905
                } else {
1906
                    $component->$joinField = $this->ID;
1907
                }
1908
            }
1909
        } else {
1910
            throw new InvalidArgumentException(
1911
                "DataObject->getComponent(): Could not find component '$componentName'."
1912
            );
1913
        }
1914
1915
        $this->components[$componentName] = $component;
1916
        return $component;
1917
    }
1918
1919
    /**
1920
     * Assign an item to the given component
1921
     *
1922
     * @param string $componentName
1923
     * @param DataObject|null $item
1924
     * @return $this
1925
     */
1926
    public function setComponent($componentName, $item)
1927
    {
1928
        // Validate component
1929
        $schema = static::getSchema();
1930
        if ($class = $schema->hasOneComponent(static::class, $componentName)) {
1931
            // Force item to be written if not by this point
1932
            // @todo This could be lazy-written in a beforeWrite hook, but force write here for simplicity
1933
            // https://github.com/silverstripe/silverstripe-framework/issues/7818
1934
            if ($item && !$item->isInDB()) {
1935
                $item->write();
1936
            }
1937
1938
            // Update local ID
1939
            $joinField = $componentName . 'ID';
1940
            $this->setField($joinField, $item ? $item->ID : null);
1941
            // Update Class (Polymorphic has_one)
1942
            // Extract class name for polymorphic relations
1943
            if ($class === self::class) {
1944
                $this->setField($componentName . 'Class', $item ? get_class($item) : null);
1945
            }
1946
        } 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...
1947
            if ($item) {
1948
                // For belongs_to, add to has_one on other component
1949
                $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
1950
                if (!$polymorphic) {
1951
                    $joinField = substr($joinField, 0, -2);
1952
                }
1953
                $item->setComponent($joinField, $this);
1954
            }
1955
        } else {
1956
            throw new InvalidArgumentException(
1957
                "DataObject->setComponent(): Could not find component '$componentName'."
1958
            );
1959
        }
1960
1961
        $this->components[$componentName] = $item;
1962
        return $this;
1963
    }
1964
1965
    /**
1966
     * Returns a one-to-many relation as a HasManyList
1967
     *
1968
     * @param string $componentName Name of the component
1969
     * @param int|array $id Optional ID(s) for parent of this relation, if not the current record
1970
     * @return HasManyList|UnsavedRelationList The components of the one-to-many relationship.
1971
     */
1972
    public function getComponents($componentName, $id = null)
1973
    {
1974
        if (!isset($id)) {
1975
            $id = $this->ID;
1976
        }
1977
        $result = null;
1978
1979
        $schema = $this->getSchema();
1980
        $componentClass = $schema->hasManyComponent(static::class, $componentName);
1981
        if (!$componentClass) {
1982
            throw new InvalidArgumentException(sprintf(
1983
                "DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
1984
                $componentName,
1985
                static::class
1986
            ));
1987
        }
1988
1989
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
1990
        if (!$id) {
1991
            if (!isset($this->unsavedRelations[$componentName])) {
1992
                $this->unsavedRelations[$componentName] =
1993
                    new UnsavedRelationList(static::class, $componentName, $componentClass);
1994
            }
1995
            return $this->unsavedRelations[$componentName];
1996
        }
1997
1998
        // Determine type and nature of foreign relation
1999
        $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'has_many', $polymorphic);
2000
        /** @var HasManyList $result */
2001
        if ($polymorphic) {
2002
            $result = PolymorphicHasManyList::create($componentClass, $joinField, static::class);
2003
        } else {
2004
            $result = HasManyList::create($componentClass, $joinField);
2005
        }
2006
2007
        return $result
2008
            ->setDataQueryParam($this->getInheritableQueryParams())
2009
            ->forForeignID($id);
2010
    }
2011
2012
    /**
2013
     * Find the foreign class of a relation on this DataObject, regardless of the relation type.
2014
     *
2015
     * @param string $relationName Relation name.
2016
     * @return string Class name, or null if not found.
2017
     */
2018
    public function getRelationClass($relationName)
2019
    {
2020
        // Parse many_many
2021
        $manyManyComponent = $this->getSchema()->manyManyComponent(static::class, $relationName);
2022
        if ($manyManyComponent) {
2023
            return $manyManyComponent['childClass'];
2024
        }
2025
2026
        // Go through all relationship configuration fields.
2027
        $config = $this->config();
2028
        $candidates = array_merge(
2029
            ($relations = $config->get('has_one')) ? $relations : [],
2030
            ($relations = $config->get('has_many')) ? $relations : [],
2031
            ($relations = $config->get('belongs_to')) ? $relations : []
2032
        );
2033
2034
        if (isset($candidates[$relationName])) {
2035
            $remoteClass = $candidates[$relationName];
2036
2037
            // If dot notation is present, extract just the first part that contains the class.
2038
            if (($fieldPos = strpos($remoteClass, '.')) !== false) {
2039
                return substr($remoteClass, 0, $fieldPos);
2040
            }
2041
2042
            // Otherwise just return the class
2043
            return $remoteClass;
2044
        }
2045
2046
        return null;
2047
    }
2048
2049
    /**
2050
     * Given a relation name, determine the relation type
2051
     *
2052
     * @param string $component Name of component
2053
     * @return string has_one, has_many, many_many, belongs_many_many or belongs_to
2054
     */
2055
    public function getRelationType($component)
2056
    {
2057
        $types = ['has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to'];
2058
        $config = $this->config();
2059
        foreach ($types as $type) {
2060
            $relations = $config->get($type);
2061
            if ($relations && isset($relations[$component])) {
2062
                return $type;
2063
            }
2064
        }
2065
        return null;
2066
    }
2067
2068
    /**
2069
     * Given a relation declared on a remote class, generate a substitute component for the opposite
2070
     * side of the relation.
2071
     *
2072
     * Notes on behaviour:
2073
     *  - This can still be used on components that are defined on both sides, but do not need to be.
2074
     *  - All has_ones on remote class will be treated as local has_many, even if they are belongs_to
2075
     *  - Polymorphic relationships do not have two natural endpoints (only on one side)
2076
     *   and thus attempting to infer them will return nothing.
2077
     *  - Cannot be used on unsaved objects.
2078
     *
2079
     * @param string $remoteClass
2080
     * @param string $remoteRelation
2081
     * @return DataList|DataObject The component, either as a list or single object
2082
     * @throws BadMethodCallException
2083
     * @throws InvalidArgumentException
2084
     */
2085
    public function inferReciprocalComponent($remoteClass, $remoteRelation)
2086
    {
2087
        $remote = DataObject::singleton($remoteClass);
2088
        $class = $remote->getRelationClass($remoteRelation);
2089
        $schema = static::getSchema();
2090
2091
        // Validate arguments
2092
        if (!$this->isInDB()) {
2093
            throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects");
2094
        }
2095
        if (empty($class)) {
2096
            throw new InvalidArgumentException(sprintf(
2097
                "%s invoked with invalid relation %s.%s",
2098
                __METHOD__,
2099
                $remoteClass,
2100
                $remoteRelation
2101
            ));
2102
        }
2103
        // If relation is polymorphic, do not infer recriprocal relationship
2104
        if ($class === self::class) {
2105
            return null;
2106
        }
2107
        if (!is_a($this, $class, true)) {
2108
            throw new InvalidArgumentException(sprintf(
2109
                "Relation %s on %s does not refer to objects of type %s",
2110
                $remoteRelation,
2111
                $remoteClass,
2112
                static::class
2113
            ));
2114
        }
2115
2116
        // Check the relation type to mock
2117
        $relationType = $remote->getRelationType($remoteRelation);
2118
        switch ($relationType) {
2119
            case 'has_one': {
2120
                // Mock has_many
2121
                $joinField = "{$remoteRelation}ID";
2122
                $componentClass = $schema->classForField($remoteClass, $joinField);
2123
                $result = HasManyList::create($componentClass, $joinField);
2124
                return $result
2125
                    ->setDataQueryParam($this->getInheritableQueryParams())
2126
                    ->forForeignID($this->ID);
2127
            }
2128
            case 'belongs_to':
2129
            case 'has_many': {
2130
                // These relations must have a has_one on the other end, so find it
2131
                $joinField = $schema->getRemoteJoinField(
2132
                    $remoteClass,
2133
                    $remoteRelation,
2134
                    $relationType,
2135
                    $polymorphic
2136
                );
2137
                // If relation is polymorphic, do not infer recriprocal relationship automatically
2138
                if ($polymorphic) {
2139
                    return null;
2140
                }
2141
                $joinID = $this->getField($joinField);
2142
                if (empty($joinID)) {
2143
                    return null;
2144
                }
2145
                // Get object by joined ID
2146
                return DataObject::get($remoteClass)
2147
                    ->filter('ID', $joinID)
2148
                    ->setDataQueryParam($this->getInheritableQueryParams())
2149
                    ->first();
2150
            }
2151
            case 'many_many':
2152
            case 'belongs_many_many': {
2153
                // Get components and extra fields from parent
2154
                $manyMany = $remote->getSchema()->manyManyComponent($remoteClass, $remoteRelation);
2155
                $extraFields = $schema->manyManyExtraFieldsForComponent($remoteClass, $remoteRelation) ?: [];
2156
2157
                // Reverse parent and component fields and create an inverse ManyManyList
2158
                /** @var RelationList $result */
2159
                $result = Injector::inst()->create(
2160
                    $manyMany['relationClass'],
2161
                    $manyMany['parentClass'], // Substitute parent class for dataClass
2162
                    $manyMany['join'],
2163
                    $manyMany['parentField'], // Reversed parent / child field
2164
                    $manyMany['childField'], // Reversed parent / child field
2165
                    $extraFields,
2166
                    $manyMany['childClass'], // substitute child class for parentClass
2167
                    $remoteClass // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
2168
                );
2169
                $this->extend('updateManyManyComponents', $result);
2170
2171
                // If this is called on a singleton, then we return an 'orphaned relation' that can have the
2172
                // foreignID set elsewhere.
2173
                return $result
2174
                    ->setDataQueryParam($this->getInheritableQueryParams())
2175
                    ->forForeignID($this->ID);
2176
            }
2177
            default: {
2178
                return null;
2179
            }
2180
        }
2181
    }
2182
2183
    /**
2184
     * Returns a many-to-many component, as a ManyManyList.
2185
     * @param string $componentName Name of the many-many component
2186
     * @param int|array $id Optional ID for parent of this relation, if not the current record
2187
     * @return ManyManyList|UnsavedRelationList The set of components
2188
     */
2189
    public function getManyManyComponents($componentName, $id = null)
2190
    {
2191
        if (!isset($id)) {
2192
            $id = $this->ID;
2193
        }
2194
        $schema = static::getSchema();
2195
        $manyManyComponent = $schema->manyManyComponent(static::class, $componentName);
2196
        if (!$manyManyComponent) {
2197
            throw new InvalidArgumentException(sprintf(
2198
                "DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'",
2199
                $componentName,
2200
                static::class
2201
            ));
2202
        }
2203
2204
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
2205
        if (!$id) {
2206
            if (!isset($this->unsavedRelations[$componentName])) {
2207
                $this->unsavedRelations[$componentName] = new UnsavedRelationList(
2208
                    $manyManyComponent['parentClass'],
2209
                    $componentName,
2210
                    $manyManyComponent['childClass']
2211
                );
2212
            }
2213
            return $this->unsavedRelations[$componentName];
2214
        }
2215
2216
        $extraFields = $schema->manyManyExtraFieldsForComponent(static::class, $componentName) ?: [];
2217
        /** @var RelationList $result */
2218
        $result = Injector::inst()->create(
2219
            $manyManyComponent['relationClass'],
2220
            $manyManyComponent['childClass'],
2221
            $manyManyComponent['join'],
2222
            $manyManyComponent['childField'],
2223
            $manyManyComponent['parentField'],
2224
            $extraFields,
2225
            $manyManyComponent['parentClass'],
2226
            static::class // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
2227
        );
2228
2229
        // Store component data in query meta-data
2230
        $result = $result->alterDataQuery(function ($query) use ($extraFields) {
2231
            /** @var DataQuery $query */
2232
            $query->setQueryParam('Component.ExtraFields', $extraFields);
2233
        });
2234
2235
        // If we have a default sort set for our "join" then we should overwrite any default already set.
2236
        $joinSort = Config::inst()->get($manyManyComponent['join'], 'default_sort');
2237
        if (!empty($joinSort)) {
2238
            $result = $result->sort($joinSort);
2239
        }
2240
2241
        $this->extend('updateManyManyComponents', $result);
2242
2243
        // If this is called on a singleton, then we return an 'orphaned relation' that can have the
2244
        // foreignID set elsewhere.
2245
        return $result
2246
            ->setDataQueryParam($this->getInheritableQueryParams())
2247
            ->forForeignID($id);
2248
    }
2249
2250
    /**
2251
     * Return the class of a one-to-one component.  If $component is null, return all of the one-to-one components and
2252
     * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.
2253
     *
2254
     * @return string|array The class of the one-to-one component, or an array of all one-to-one components and
2255
     *                          their classes.
2256
     */
2257
    public function hasOne()
2258
    {
2259
        return (array)$this->config()->get('has_one');
2260
    }
2261
2262
    /**
2263
     * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
2264
     * their class name will be returned.
2265
     *
2266
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2267
     *        the field data stripped off. It defaults to TRUE.
2268
     * @return string|array
2269
     */
2270
    public function belongsTo($classOnly = true)
2271
    {
2272
        $belongsTo = (array)$this->config()->get('belongs_to');
2273
        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...
2274
            return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
2275
        } else {
2276
            return $belongsTo ? $belongsTo : [];
2277
        }
2278
    }
2279
2280
    /**
2281
     * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
2282
     * relationships and their classes will be returned.
2283
     *
2284
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2285
     *        the field data stripped off. It defaults to TRUE.
2286
     * @return string|array|false
2287
     */
2288
    public function hasMany($classOnly = true)
2289
    {
2290
        $hasMany = (array)$this->config()->get('has_many');
2291
        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...
2292
            return preg_replace('/(.+)?\..+/', '$1', $hasMany);
2293
        } else {
2294
            return $hasMany ? $hasMany : [];
2295
        }
2296
    }
2297
2298
    /**
2299
     * Return the many-to-many extra fields specification.
2300
     *
2301
     * If you don't specify a component name, it returns all
2302
     * extra fields for all components available.
2303
     *
2304
     * @return array|null
2305
     */
2306
    public function manyManyExtraFields()
2307
    {
2308
        return $this->config()->get('many_many_extraFields');
2309
    }
2310
2311
    /**
2312
     * Return information about a many-to-many component.
2313
     * The return value is an array of (parentclass, childclass).  If $component is null, then all many-many
2314
     * components are returned.
2315
     *
2316
     * @see DataObjectSchema::manyManyComponent()
2317
     * @return array|null An array of (parentclass, childclass), or an array of all many-many components
2318
     */
2319
    public function manyMany()
2320
    {
2321
        $config = $this->config();
2322
        $manyManys = (array)$config->get('many_many');
2323
        $belongsManyManys = (array)$config->get('belongs_many_many');
2324
        $items = array_merge($manyManys, $belongsManyManys);
2325
        return $items;
2326
    }
2327
2328
    /**
2329
     * This returns an array (if it exists) describing the database extensions that are required, or false if none
2330
     *
2331
     * This is experimental, and is currently only a Postgres-specific enhancement.
2332
     *
2333
     * @param string $class
2334
     * @return array|false
2335
     */
2336
    public function database_extensions($class)
2337
    {
2338
        $extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
2339
        if ($extensions) {
2340
            return $extensions;
2341
        } else {
2342
            return false;
2343
        }
2344
    }
2345
2346
    /**
2347
     * Generates a SearchContext to be used for building and processing
2348
     * a generic search form for properties on this object.
2349
     *
2350
     * @return SearchContext
2351
     */
2352
    public function getDefaultSearchContext()
2353
    {
2354
        return SearchContext::create(
2355
            static::class,
2356
            $this->scaffoldSearchFields(),
2357
            $this->defaultSearchFilters()
2358
        );
2359
    }
2360
2361
    /**
2362
     * Determine which properties on the DataObject are
2363
     * searchable, and map them to their default {@link FormField}
2364
     * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
2365
     *
2366
     * Some additional logic is included for switching field labels, based on
2367
     * how generic or specific the field type is.
2368
     *
2369
     * Used by {@link SearchContext}.
2370
     *
2371
     * @param array $_params
2372
     *   'fieldClasses': Associative array of field names as keys and FormField classes as values
2373
     *   'restrictFields': Numeric array of a field name whitelist
2374
     * @return FieldList
2375
     */
2376
    public function scaffoldSearchFields($_params = null)
2377
    {
2378
        $params = array_merge(
2379
            [
2380
                'fieldClasses' => false,
2381
                'restrictFields' => false
2382
            ],
2383
            (array)$_params
2384
        );
2385
        $fields = new FieldList();
2386
        foreach ($this->searchableFields() as $fieldName => $spec) {
2387
            if ($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) {
2388
                continue;
2389
            }
2390
2391
            // If a custom fieldclass is provided as a string, use it
2392
            $field = null;
2393
            if ($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
2394
                $fieldClass = $params['fieldClasses'][$fieldName];
2395
                $field = new $fieldClass($fieldName);
2396
            // If we explicitly set a field, then construct that
2397
            } elseif (isset($spec['field'])) {
2398
                // If it's a string, use it as a class name and construct
2399
                if (is_string($spec['field'])) {
2400
                    $fieldClass = $spec['field'];
2401
                    $field = new $fieldClass($fieldName);
2402
2403
                // If it's a FormField object, then just use that object directly.
2404
                } elseif ($spec['field'] instanceof FormField) {
2405
                    $field = $spec['field'];
2406
2407
                // Otherwise we have a bug
2408
                } else {
2409
                    user_error("Bad value for searchable_fields, 'field' value: "
2410
                        . var_export($spec['field'], true), E_USER_WARNING);
2411
                }
2412
2413
            // Otherwise, use the database field's scaffolder
2414
            } elseif ($object = $this->relObject($fieldName)) {
2415
                if (is_object($object) && $object->hasMethod('scaffoldSearchField')) {
2416
                    $field = $object->scaffoldSearchField();
2417
                } else {
2418
                    throw new Exception(sprintf(
2419
                        "SearchField '%s' on '%s' does not return a valid DBField instance.",
2420
                        $fieldName,
2421
                        get_class($this)
2422
                    ));
2423
                }
2424
            }
2425
2426
            // Allow fields to opt out of search
2427
            if (!$field) {
2428
                continue;
2429
            }
2430
2431
            if (strstr($fieldName, '.')) {
2432
                $field->setName(str_replace('.', '__', $fieldName));
2433
            }
2434
            $field->setTitle($spec['title']);
2435
2436
            $fields->push($field);
2437
        }
2438
        return $fields;
2439
    }
2440
2441
    /**
2442
     * Scaffold a simple edit form for all properties on this dataobject,
2443
     * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
2444
     * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
2445
     *
2446
     * @uses FormScaffolder
2447
     *
2448
     * @param array $_params Associative array passing through properties to {@link FormScaffolder}.
2449
     * @return FieldList
2450
     */
2451
    public function scaffoldFormFields($_params = null)
2452
    {
2453
        $params = array_merge(
2454
            [
2455
                'tabbed' => false,
2456
                'includeRelations' => false,
2457
                'restrictFields' => false,
2458
                'fieldClasses' => false,
2459
                'ajaxSafe' => false
2460
            ],
2461
            (array)$_params
2462
        );
2463
2464
        $fs = FormScaffolder::create($this);
2465
        $fs->tabbed = $params['tabbed'];
2466
        $fs->includeRelations = $params['includeRelations'];
2467
        $fs->restrictFields = $params['restrictFields'];
2468
        $fs->fieldClasses = $params['fieldClasses'];
2469
        $fs->ajaxSafe = $params['ajaxSafe'];
2470
2471
        $this->extend('updateFormScaffolder', $fs, $this);
2472
2473
        return $fs->getFieldList();
2474
    }
2475
2476
    /**
2477
     * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
2478
     * being called on extensions
2479
     *
2480
     * @param callable $callback The callback to execute
2481
     */
2482
    protected function beforeUpdateCMSFields($callback)
2483
    {
2484
        $this->beforeExtending('updateCMSFields', $callback);
2485
    }
2486
2487
    /**
2488
     * Centerpiece of every data administration interface in Silverstripe,
2489
     * which returns a {@link FieldList} suitable for a {@link Form} object.
2490
     * If not overloaded, we're using {@link scaffoldFormFields()} to automatically
2491
     * generate this set. To customize, overload this method in a subclass
2492
     * or extended onto it by using {@link DataExtension->updateCMSFields()}.
2493
     *
2494
     * <code>
2495
     * class MyCustomClass extends DataObject {
2496
     *  static $db = array('CustomProperty'=>'Boolean');
2497
     *
2498
     *  function getCMSFields() {
2499
     *    $fields = parent::getCMSFields();
2500
     *    $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
2501
     *    return $fields;
2502
     *  }
2503
     * }
2504
     * </code>
2505
     *
2506
     * @see Good example of complex FormField building: SiteTree::getCMSFields()
2507
     *
2508
     * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.
2509
     */
2510
    public function getCMSFields()
2511
    {
2512
        $tabbedFields = $this->scaffoldFormFields([
2513
            // Don't allow has_many/many_many relationship editing before the record is first saved
2514
            'includeRelations' => ($this->ID > 0),
2515
            'tabbed' => true,
2516
            'ajaxSafe' => true
2517
        ]);
2518
2519
        $this->extend('updateCMSFields', $tabbedFields);
2520
2521
        return $tabbedFields;
2522
    }
2523
2524
    /**
2525
     * need to be overload by solid dataobject, so that the customised actions of that dataobject,
2526
     * including that dataobject's extensions customised actions could be added to the EditForm.
2527
     *
2528
     * @return FieldList an Empty FieldList(); need to be overload by solid subclass
2529
     */
2530
    public function getCMSActions()
2531
    {
2532
        $actions = new FieldList();
2533
        $this->extend('updateCMSActions', $actions);
2534
        return $actions;
2535
    }
2536
2537
    /**
2538
     * When extending this class and overriding this method, you will need to instantiate the CompositeValidator by
2539
     * calling parent::getCMSCompositeValidator(). This will ensure that the appropriate extension point is also
2540
     * invoked.
2541
     *
2542
     * You can also update the CompositeValidator by creating an Extension and implementing the
2543
     * updateCMSCompositeValidator(CompositeValidator $compositeValidator) method.
2544
     *
2545
     * @see CompositeValidator for examples of implementation
2546
     * @return CompositeValidator
2547
     */
2548
    public function getCMSCompositeValidator(): CompositeValidator
2549
    {
2550
        $compositeValidator = new CompositeValidator();
2551
2552
        // Support for the old method during the deprecation period
2553
        if ($this->hasMethod('getCMSValidator')) {
2554
            Deprecation::notice(
2555
                '4.6',
2556
                'getCMSValidator() is removed in 5.0 in favour of getCMSCompositeValidator()'
2557
            );
2558
2559
            $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

2559
            $compositeValidator->addValidator($this->/** @scrutinizer ignore-call */ getCMSValidator());
Loading history...
2560
        }
2561
2562
        // Extend validator - forward support, will be supported beyond 5.0.0
2563
        $this->invokeWithExtensions('updateCMSCompositeValidator', $compositeValidator);
2564
2565
        return $compositeValidator;
2566
    }
2567
2568
    /**
2569
     * Used for simple frontend forms without relation editing
2570
     * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()}
2571
     * by default. To customize, either overload this method in your
2572
     * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.
2573
     *
2574
     * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API
2575
     *
2576
     * @param array $params See {@link scaffoldFormFields()}
2577
     * @return FieldList Always returns a simple field collection without TabSet.
2578
     */
2579
    public function getFrontEndFields($params = null)
2580
    {
2581
        $untabbedFields = $this->scaffoldFormFields($params);
2582
        $this->extend('updateFrontEndFields', $untabbedFields);
2583
2584
        return $untabbedFields;
2585
    }
2586
2587
    public function getViewerTemplates($suffix = '')
2588
    {
2589
        return SSViewer::get_templates_by_class(static::class, $suffix, $this->baseClass());
2590
    }
2591
2592
    /**
2593
     * Gets the value of a field.
2594
     * Called by {@link __get()} and any getFieldName() methods you might create.
2595
     *
2596
     * @param string $field The name of the field
2597
     * @return mixed The field value
2598
     */
2599
    public function getField($field)
2600
    {
2601
        // If we already have a value in $this->record, then we should just return that
2602
        if (isset($this->record[$field])) {
2603
            return $this->record[$field];
2604
        }
2605
2606
        // Do we have a field that needs to be lazy loaded?
2607
        if (isset($this->record[$field . '_Lazy'])) {
2608
            $tableClass = $this->record[$field . '_Lazy'];
2609
            $this->loadLazyFields($tableClass);
2610
        }
2611
        $schema = static::getSchema();
2612
2613
        // Support unary relations as fields
2614
        if ($schema->unaryComponent(static::class, $field)) {
2615
            return $this->getComponent($field);
2616
        }
2617
2618
        // In case of complex fields, return the DBField object
2619
        if ($schema->compositeField(static::class, $field)) {
2620
            $this->record[$field] = $this->dbObject($field);
2621
        }
2622
2623
        return isset($this->record[$field]) ? $this->record[$field] : null;
2624
    }
2625
2626
    /**
2627
     * Loads all the stub fields that an initial lazy load didn't load fully.
2628
     *
2629
     * @param string $class Class to load the values from. Others are joined as required.
2630
     * Not specifying a tableClass will load all lazy fields from all tables.
2631
     * @return bool Flag if lazy loading succeeded
2632
     */
2633
    protected function loadLazyFields($class = null)
2634
    {
2635
        if (!$this->isInDB() || !is_numeric($this->ID)) {
2636
            return false;
2637
        }
2638
2639
        if (!$class) {
2640
            $loaded = [];
2641
2642
            foreach ($this->record as $key => $value) {
2643
                if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
2644
                    $this->loadLazyFields($value);
2645
                    $loaded[$value] = $value;
2646
                }
2647
            }
2648
2649
            return false;
2650
        }
2651
2652
        $dataQuery = new DataQuery($class);
2653
2654
        // Reset query parameter context to that of this DataObject
2655
        if ($params = $this->getSourceQueryParams()) {
2656
            foreach ($params as $key => $value) {
2657
                $dataQuery->setQueryParam($key, $value);
2658
            }
2659
        }
2660
2661
        // Limit query to the current record, unless it has the Versioned extension,
2662
        // in which case it requires special handling through augmentLoadLazyFields()
2663
        $schema = static::getSchema();
2664
        $baseIDColumn = $schema->sqlColumnForField($this, 'ID');
2665
        $dataQuery->where([
2666
            $baseIDColumn => $this->record['ID']
2667
        ])->limit(1);
2668
2669
        $columns = [];
2670
2671
        // Add SQL for fields, both simple & multi-value
2672
        // TODO: This is copy & pasted from buildSQL(), it could be moved into a method
2673
        $databaseFields = $schema->databaseFields($class, false);
2674
        foreach ($databaseFields as $k => $v) {
2675
            if (!isset($this->record[$k]) || $this->record[$k] === null) {
2676
                $columns[] = $k;
2677
            }
2678
        }
2679
2680
        if ($columns) {
2681
            $query = $dataQuery->query();
2682
            $this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
2683
            $this->extend('augmentSQL', $query, $dataQuery);
2684
2685
            $dataQuery->setQueriedColumns($columns);
2686
            $newData = $dataQuery->execute()->record();
2687
2688
            // Load the data into record
2689
            if ($newData) {
2690
                foreach ($newData as $k => $v) {
2691
                    if (in_array($k, $columns)) {
2692
                        $this->record[$k] = $v;
2693
                        $this->original[$k] = $v;
2694
                        unset($this->record[$k . '_Lazy']);
2695
                    }
2696
                }
2697
2698
            // No data means that the query returned nothing; assign 'null' to all the requested fields
2699
            } else {
2700
                foreach ($columns as $k) {
2701
                    $this->record[$k] = null;
2702
                    $this->original[$k] = null;
2703
                    unset($this->record[$k . '_Lazy']);
2704
                }
2705
            }
2706
        }
2707
        return true;
2708
    }
2709
2710
    /**
2711
     * Return the fields that have changed since the last write.
2712
     *
2713
     * The change level affects what the functions defines as "changed":
2714
     * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
2715
     * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
2716
     *   for example a change from 0 to null would not be included.
2717
     *
2718
     * Example return:
2719
     * <code>
2720
     * array(
2721
     *   'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
2722
     * )
2723
     * </code>
2724
     *
2725
     * @param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true
2726
     * to return all database fields, or an array for an explicit filter. false returns all fields.
2727
     * @param int $changeLevel The strictness of what is defined as change. Defaults to strict
2728
     * @return array
2729
     */
2730
    public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT)
2731
    {
2732
        $changedFields = [];
2733
2734
        // Update the changed array with references to changed obj-fields
2735
        foreach ($this->record as $k => $v) {
2736
            // Prevents DBComposite infinite looping on isChanged
2737
            if (is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
2738
                continue;
2739
            }
2740
            if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
2741
                $this->changed[$k] = self::CHANGE_VALUE;
2742
            }
2743
        }
2744
2745
        // If change was forced, then derive change data from $this->record
2746
        if ($this->changeForced && $changeLevel <= self::CHANGE_STRICT) {
2747
            $changed = array_combine(
2748
                array_keys($this->record),
2749
                array_fill(0, count($this->record), self::CHANGE_STRICT)
2750
            );
2751
            // @todo Find better way to allow versioned to write a new version after forceChange
2752
            unset($changed['Version']);
2753
        } else {
2754
            $changed = $this->changed;
2755
        }
2756
2757
        if (is_array($databaseFieldsOnly)) {
2758
            $fields = array_intersect_key($changed, array_flip($databaseFieldsOnly));
2759
        } elseif ($databaseFieldsOnly) {
2760
            $fieldsSpecs = static::getSchema()->fieldSpecs(static::class);
2761
            $fields = array_intersect_key($changed, $fieldsSpecs);
2762
        } else {
2763
            $fields = $changed;
2764
        }
2765
2766
        // Filter the list to those of a certain change level
2767
        if ($changeLevel > self::CHANGE_STRICT) {
2768
            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...
2769
                foreach ($fields as $name => $level) {
2770
                    if ($level < $changeLevel) {
2771
                        unset($fields[$name]);
2772
                    }
2773
                }
2774
            }
2775
        }
2776
2777
        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...
2778
            foreach ($fields as $name => $level) {
2779
                $changedFields[$name] = [
2780
                    'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
2781
                    'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
2782
                    'level' => $level
2783
                ];
2784
            }
2785
        }
2786
2787
        return $changedFields;
2788
    }
2789
2790
    /**
2791
     * Uses {@link getChangedFields()} to determine if fields have been changed
2792
     * since loading them from the database.
2793
     *
2794
     * @param string $fieldName Name of the database field to check, will check for any if not given
2795
     * @param int $changeLevel See {@link getChangedFields()}
2796
     * @return boolean
2797
     */
2798
    public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT)
2799
    {
2800
        $fields = $fieldName ? [$fieldName] : true;
2801
        $changed = $this->getChangedFields($fields, $changeLevel);
2802
        if (!isset($fieldName)) {
2803
            return !empty($changed);
2804
        } else {
2805
            return array_key_exists($fieldName, $changed);
2806
        }
2807
    }
2808
2809
    /**
2810
     * Set the value of the field
2811
     * Called by {@link __set()} and any setFieldName() methods you might create.
2812
     *
2813
     * @param string $fieldName Name of the field
2814
     * @param mixed $val New field value
2815
     * @return $this
2816
     */
2817
    public function setField($fieldName, $val)
2818
    {
2819
        $this->objCacheClear();
2820
        //if it's a has_one component, destroy the cache
2821
        if (substr($fieldName, -2) == 'ID') {
2822
            unset($this->components[substr($fieldName, 0, -2)]);
2823
        }
2824
2825
        // If we've just lazy-loaded the column, then we need to populate the $original array
2826
        if (isset($this->record[$fieldName . '_Lazy'])) {
2827
            $tableClass = $this->record[$fieldName . '_Lazy'];
2828
            $this->loadLazyFields($tableClass);
2829
        }
2830
2831
        // Support component assignent via field setter
2832
        $schema = static::getSchema();
2833
        if ($schema->unaryComponent(static::class, $fieldName)) {
2834
            unset($this->components[$fieldName]);
2835
            // Assign component directly
2836
            if (is_null($val) || $val instanceof DataObject) {
2837
                return $this->setComponent($fieldName, $val);
2838
            }
2839
            // Assign by ID instead of object
2840
            if (is_numeric($val)) {
2841
                $fieldName .= 'ID';
2842
            }
2843
        }
2844
2845
        // Situation 1: Passing an DBField
2846
        if ($val instanceof DBField) {
2847
            $val->setName($fieldName);
2848
            $val->saveInto($this);
2849
2850
            // Situation 1a: Composite fields should remain bound in case they are
2851
            // later referenced to update the parent dataobject
2852
            if ($val instanceof DBComposite) {
2853
                $val->bindTo($this);
2854
                $this->record[$fieldName] = $val;
2855
            }
2856
        // Situation 2: Passing a literal or non-DBField object
2857
        } else {
2858
            // If this is a proper database field, we shouldn't be getting non-DBField objects
2859
            if (is_object($val) && $schema->fieldSpec(static::class, $fieldName)) {
2860
                throw new InvalidArgumentException('DataObject::setField: passed an object that is not a DBField');
2861
            }
2862
2863
            if (!empty($val) && !is_scalar($val)) {
2864
                $dbField = $this->dbObject($fieldName);
2865
                if ($dbField && $dbField->scalarValueOnly()) {
2866
                    throw new InvalidArgumentException(
2867
                        sprintf(
2868
                            'DataObject::setField: %s only accepts scalars',
2869
                            $fieldName
2870
                        )
2871
                    );
2872
                }
2873
            }
2874
2875
            // if a field is not existing or has strictly changed
2876
            if (!array_key_exists($fieldName, $this->original) || $this->original[$fieldName] !== $val) {
2877
                // TODO Add check for php-level defaults which are not set in the db
2878
                // TODO Add check for hidden input-fields (readonly) which are not set in the db
2879
                // At the very least, the type has changed
2880
                $this->changed[$fieldName] = self::CHANGE_STRICT;
2881
2882
                if ((!array_key_exists($fieldName, $this->original) && $val)
2883
                    || (array_key_exists($fieldName, $this->original) && $this->original[$fieldName] != $val)
2884
                ) {
2885
                    // Value has changed as well, not just the type
2886
                    $this->changed[$fieldName] = self::CHANGE_VALUE;
2887
                }
2888
            // Value has been restored to its original, remove any record of the change
2889
            } elseif (isset($this->changed[$fieldName])) {
2890
                unset($this->changed[$fieldName]);
2891
            }
2892
2893
            // Value is saved regardless, since the change detection relates to the last write
2894
            $this->record[$fieldName] = $val;
2895
        }
2896
        return $this;
2897
    }
2898
2899
    /**
2900
     * Set the value of the field, using a casting object.
2901
     * This is useful when you aren't sure that a date is in SQL format, for example.
2902
     * setCastedField() can also be used, by forms, to set related data.  For example, uploaded images
2903
     * can be saved into the Image table.
2904
     *
2905
     * @param string $fieldName Name of the field
2906
     * @param mixed $value New field value
2907
     * @return $this
2908
     */
2909
    public function setCastedField($fieldName, $value)
2910
    {
2911
        if (!$fieldName) {
2912
            throw new InvalidArgumentException("DataObject::setCastedField: Called without a fieldName");
2913
        }
2914
        $fieldObj = $this->dbObject($fieldName);
2915
        if ($fieldObj) {
0 ignored issues
show
introduced by
$fieldObj is of type SilverStripe\ORM\FieldType\DBField, thus it always evaluated to true.
Loading history...
2916
            $fieldObj->setValue($value);
2917
            $fieldObj->saveInto($this);
2918
        } else {
2919
            $this->$fieldName = $value;
2920
        }
2921
        return $this;
2922
    }
2923
2924
    /**
2925
     * {@inheritdoc}
2926
     */
2927
    public function castingHelper($field)
2928
    {
2929
        $fieldSpec = static::getSchema()->fieldSpec(static::class, $field);
2930
        if ($fieldSpec) {
2931
            return $fieldSpec;
2932
        }
2933
2934
        // many_many_extraFields aren't presented by db(), so we check if the source query params
2935
        // provide us with meta-data for a many_many relation we can inspect for extra fields.
2936
        $queryParams = $this->getSourceQueryParams();
2937
        if (!empty($queryParams['Component.ExtraFields'])) {
2938
            $extraFields = $queryParams['Component.ExtraFields'];
2939
2940
            if (isset($extraFields[$field])) {
2941
                return $extraFields[$field];
2942
            }
2943
        }
2944
2945
        return parent::castingHelper($field);
2946
    }
2947
2948
    /**
2949
     * Returns true if the given field exists in a database column on any of
2950
     * the objects tables and optionally look up a dynamic getter with
2951
     * get<fieldName>().
2952
     *
2953
     * @param string $field Name of the field
2954
     * @return boolean True if the given field exists
2955
     */
2956
    public function hasField($field)
2957
    {
2958
        $schema = static::getSchema();
2959
        return (
2960
            array_key_exists($field, $this->record)
2961
            || array_key_exists($field, $this->components)
2962
            || $schema->fieldSpec(static::class, $field)
2963
            || $schema->unaryComponent(static::class, $field)
2964
            || $this->hasMethod("get{$field}")
2965
        );
2966
    }
2967
2968
    /**
2969
     * Returns true if the given field exists as a database column
2970
     *
2971
     * @param string $field Name of the field
2972
     *
2973
     * @return boolean
2974
     */
2975
    public function hasDatabaseField($field)
2976
    {
2977
        $spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY);
2978
        return !empty($spec);
2979
    }
2980
2981
    /**
2982
     * Returns true if the member is allowed to do the given action.
2983
     * See {@link extendedCan()} for a more versatile tri-state permission control.
2984
     *
2985
     * @param string $perm The permission to be checked, such as 'View'.
2986
     * @param Member $member The member whose permissions need checking.  Defaults to the currently logged
2987
     * in user.
2988
     * @param array $context Additional $context to pass to extendedCan()
2989
     *
2990
     * @return boolean True if the the member is allowed to do the given action
2991
     */
2992
    public function can($perm, $member = null, $context = [])
2993
    {
2994
        if (!$member) {
2995
            $member = Security::getCurrentUser();
2996
        }
2997
2998
        if ($member && Permission::checkMember($member, "ADMIN")) {
2999
            return true;
3000
        }
3001
3002
        if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
3003
            $method = 'can' . ucfirst($perm);
3004
            return $this->$method($member);
3005
        }
3006
3007
        $results = $this->extendedCan('can', $member);
3008
        if (isset($results)) {
3009
            return $results;
3010
        }
3011
3012
        return ($member && Permission::checkMember($member, $perm));
3013
    }
3014
3015
    /**
3016
     * Process tri-state responses from permission-alterting extensions.  The extensions are
3017
     * expected to return one of three values:
3018
     *
3019
     *  - false: Disallow this permission, regardless of what other extensions say
3020
     *  - true: Allow this permission, as long as no other extensions return false
3021
     *  - NULL: Don't affect the outcome
3022
     *
3023
     * This method itself returns a tri-state value, and is designed to be used like this:
3024
     *
3025
     * <code>
3026
     * $extended = $this->extendedCan('canDoSomething', $member);
3027
     * if($extended !== null) return $extended;
3028
     * else return $normalValue;
3029
     * </code>
3030
     *
3031
     * @param string $methodName Method on the same object, e.g. {@link canEdit()}
3032
     * @param Member|int $member
3033
     * @param array $context Optional context
3034
     * @return boolean|null
3035
     */
3036
    public function extendedCan($methodName, $member, $context = [])
3037
    {
3038
        $results = $this->extend($methodName, $member, $context);
3039
        if ($results && is_array($results)) {
3040
            // Remove NULLs
3041
            $results = array_filter($results, function ($v) {
3042
                return !is_null($v);
3043
            });
3044
            // If there are any non-NULL responses, then return the lowest one of them.
3045
            // If any explicitly deny the permission, then we don't get access
3046
            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...
3047
                return min($results);
3048
            }
3049
        }
3050
        return null;
3051
    }
3052
3053
    /**
3054
     * @param Member $member
3055
     * @return boolean
3056
     */
3057
    public function canView($member = null)
3058
    {
3059
        $extended = $this->extendedCan(__FUNCTION__, $member);
3060
        if ($extended !== null) {
3061
            return $extended;
3062
        }
3063
        return Permission::check('ADMIN', 'any', $member);
3064
    }
3065
3066
    /**
3067
     * @param Member $member
3068
     * @return boolean
3069
     */
3070
    public function canEdit($member = null)
3071
    {
3072
        $extended = $this->extendedCan(__FUNCTION__, $member);
3073
        if ($extended !== null) {
3074
            return $extended;
3075
        }
3076
        return Permission::check('ADMIN', 'any', $member);
3077
    }
3078
3079
    /**
3080
     * @param Member $member
3081
     * @return boolean
3082
     */
3083
    public function canDelete($member = null)
3084
    {
3085
        $extended = $this->extendedCan(__FUNCTION__, $member);
3086
        if ($extended !== null) {
3087
            return $extended;
3088
        }
3089
        return Permission::check('ADMIN', 'any', $member);
3090
    }
3091
3092
    /**
3093
     * @param Member $member
3094
     * @param array $context Additional context-specific data which might
3095
     * affect whether (or where) this object could be created.
3096
     * @return boolean
3097
     */
3098
    public function canCreate($member = null, $context = [])
3099
    {
3100
        $extended = $this->extendedCan(__FUNCTION__, $member, $context);
3101
        if ($extended !== null) {
3102
            return $extended;
3103
        }
3104
        return Permission::check('ADMIN', 'any', $member);
3105
    }
3106
3107
    /**
3108
     * Debugging used by Debug::show()
3109
     *
3110
     * @return string HTML data representing this object
3111
     */
3112
    public function debug()
3113
    {
3114
        $class = static::class;
3115
        $val = "<h3>Database record: {$class}</h3>\n<ul>\n";
3116
        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...
3117
            foreach ($this->record as $fieldName => $fieldVal) {
3118
                $val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
3119
            }
3120
        }
3121
        $val .= "</ul>\n";
3122
        return $val;
3123
    }
3124
3125
    /**
3126
     * Return the DBField object that represents the given field.
3127
     * This works similarly to obj() with 2 key differences:
3128
     *   - it still returns an object even when the field has no value.
3129
     *   - it only matches fields and not methods
3130
     *   - it matches foreign keys generated by has_one relationships, eg, "ParentID"
3131
     *
3132
     * @param string $fieldName Name of the field
3133
     * @return DBField The field as a DBField object
3134
     */
3135
    public function dbObject($fieldName)
3136
    {
3137
        // Check for field in DB
3138
        $schema = static::getSchema();
3139
        $helper = $schema->fieldSpec(static::class, $fieldName, DataObjectSchema::INCLUDE_CLASS);
3140
        if (!$helper) {
3141
            return null;
3142
        }
3143
3144
        if (!isset($this->record[$fieldName]) && isset($this->record[$fieldName . '_Lazy'])) {
3145
            $tableClass = $this->record[$fieldName . '_Lazy'];
3146
            $this->loadLazyFields($tableClass);
3147
        }
3148
3149
        $value = isset($this->record[$fieldName])
3150
            ? $this->record[$fieldName]
3151
            : null;
3152
3153
        // If we have a DBField object in $this->record, then return that
3154
        if ($value instanceof DBField) {
3155
            return $value;
3156
        }
3157
3158
        list($class, $spec) = explode('.', $helper);
3159
        /** @var DBField $obj */
3160
        $table = $schema->tableName($class);
3161
        $obj = Injector::inst()->create($spec, $fieldName);
3162
        $obj->setTable($table);
3163
        $obj->setValue($value, $this, false);
3164
        return $obj;
3165
    }
3166
3167
    /**
3168
     * Traverses to a DBField referenced by relationships between data objects.
3169
     *
3170
     * The path to the related field is specified with dot separated syntax
3171
     * (eg: Parent.Child.Child.FieldName).
3172
     *
3173
     * If a relation is blank, this will return null instead.
3174
     * If a relation name is invalid (e.g. non-relation on a parent) this
3175
     * can throw a LogicException.
3176
     *
3177
     * @param string $fieldPath List of paths on this object. All items in this path
3178
     * must be ViewableData implementors
3179
     *
3180
     * @return mixed DBField of the field on the object or a DataList instance.
3181
     * @throws LogicException If accessing invalid relations
3182
     */
3183
    public function relObject($fieldPath)
3184
    {
3185
        $object = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $object is dead and can be removed.
Loading history...
3186
        $component = $this;
3187
3188
        // Parse all relations
3189
        foreach (explode('.', $fieldPath) as $relation) {
3190
            if (!$component) {
3191
                return null;
3192
            }
3193
3194
            // Inspect relation type
3195
            if (ClassInfo::hasMethod($component, $relation)) {
3196
                $component = $component->$relation();
3197
            } elseif ($component instanceof Relation || $component instanceof DataList) {
3198
                // $relation could either be a field (aggregate), or another relation
3199
                $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

3199
                $singleton = DataObject::singleton($component->/** @scrutinizer ignore-call */ dataClass());
Loading history...
3200
                $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

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

3324
        if ($limit && strpos(/** @scrutinizer ignore-type */ $limit, ',') !== false) {
Loading history...
3325
            $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

3325
            $limitArguments = explode(',', /** @scrutinizer ignore-type */ $limit);
Loading history...
3326
            $result = $result->limit($limitArguments[1], $limitArguments[0]);
3327
        } elseif ($limit) {
3328
            $result = $result->limit($limit);
3329
        }
3330
3331
        return $result;
3332
    }
3333
3334
3335
    /**
3336
     * Return the first item matching the given query.
3337
     *
3338
     * The object returned is cached, unlike DataObject::get()->first() {@link DataList::first()}
3339
     * and DataObject::get()->last() {@link DataList::last()}
3340
     *
3341
     * The filter argument supports parameterised queries (see SQLSelect::addWhere() for syntax examples). Because
3342
     * of that (and differently from e.g. DataList::filter()) you need to manually escape the field names:
3343
     * <code>
3344
     * $member = DataObject::get_one('Member', [ '"FirstName"' => 'John' ]);
3345
     * </code>
3346
     *
3347
     * @param string $callerClass The class of objects to be returned
3348
     * @param string|array $filter A filter to be inserted into the WHERE clause.
3349
     * @param boolean $cache Use caching
3350
     * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
3351
     *
3352
     * @return DataObject|null The first item matching the query
3353
     */
3354
    public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "")
3355
    {
3356
        /** @var DataObject $singleton */
3357
        $singleton = singleton($callerClass);
3358
3359
        $cacheComponents = [$filter, $orderby, $singleton->getUniqueKeyComponents()];
3360
        $cacheKey = md5(serialize($cacheComponents));
3361
3362
        $item = null;
3363
        if (!$cache || !isset(self::$_cache_get_one[$callerClass][$cacheKey])) {
3364
            $dl = DataObject::get($callerClass)->where($filter)->sort($orderby);
3365
            $item = $dl->first();
3366
3367
            if ($cache) {
3368
                self::$_cache_get_one[$callerClass][$cacheKey] = $item;
3369
                if (!self::$_cache_get_one[$callerClass][$cacheKey]) {
3370
                    self::$_cache_get_one[$callerClass][$cacheKey] = false;
3371
                }
3372
            }
3373
        }
3374
3375
        if ($cache) {
3376
            return self::$_cache_get_one[$callerClass][$cacheKey] ?: null;
3377
        }
3378
3379
        return $item;
3380
    }
3381
3382
    /**
3383
     * Flush the cached results for all relations (has_one, has_many, many_many)
3384
     * Also clears any cached aggregate data.
3385
     *
3386
     * @param boolean $persistent When true will also clear persistent data stored in the Cache system.
3387
     *                            When false will just clear session-local cached data
3388
     * @return DataObject $this
3389
     */
3390
    public function flushCache($persistent = true)
3391
    {
3392
        if (static::class == self::class) {
0 ignored issues
show
introduced by
The condition static::class == self::class is always true.
Loading history...
3393
            self::$_cache_get_one = [];
3394
            return $this;
3395
        }
3396
3397
        $classes = ClassInfo::ancestry(static::class);
3398
        foreach ($classes as $class) {
3399
            if (isset(self::$_cache_get_one[$class])) {
3400
                unset(self::$_cache_get_one[$class]);
3401
            }
3402
        }
3403
3404
        $this->extend('flushCache');
3405
3406
        $this->components = [];
3407
        return $this;
3408
    }
3409
3410
    /**
3411
     * Flush the get_one global cache and destroy associated objects.
3412
     */
3413
    public static function flush_and_destroy_cache()
3414
    {
3415
        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...
3416
            foreach (self::$_cache_get_one as $class => $items) {
3417
                if (is_array($items)) {
3418
                    foreach ($items as $item) {
3419
                        if ($item) {
3420
                            $item->destroy();
3421
                        }
3422
                    }
3423
                }
3424
            }
3425
        }
3426
        self::$_cache_get_one = [];
3427
    }
3428
3429
    /**
3430
     * Reset all global caches associated with DataObject.
3431
     */
3432
    public static function reset()
3433
    {
3434
        // @todo Decouple these
3435
        DBEnum::flushCache();
3436
        ClassInfo::reset_db_cache();
3437
        static::getSchema()->reset();
3438
        self::$_cache_get_one = [];
3439
        self::$_cache_field_labels = [];
3440
    }
3441
3442
    /**
3443
     * Return the given element, searching by ID.
3444
     *
3445
     * This can be called either via `DataObject::get_by_id(MyClass::class, $id)`
3446
     * or `MyClass::get_by_id($id)`
3447
     *
3448
     * The object returned is cached, unlike DataObject::get()->byID() {@link DataList::byID()}
3449
     *
3450
     * @param string|int $classOrID The class of the object to be returned, or id if called on target class
3451
     * @param int|bool $idOrCache The id of the element, or cache if called on target class
3452
     * @param boolean $cache See {@link get_one()}
3453
     *
3454
     * @return static The element
3455
     */
3456
    public static function get_by_id($classOrID, $idOrCache = null, $cache = true)
3457
    {
3458
        // Shift arguments if passing id in first or second argument
3459
        list ($class, $id, $cached) = is_numeric($classOrID)
3460
            ? [get_called_class(), $classOrID, isset($idOrCache) ? $idOrCache : $cache]
3461
            : [$classOrID, $idOrCache, $cache];
3462
3463
        // Validate class
3464
        if ($class === self::class) {
3465
            throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly');
3466
        }
3467
3468
        // Pass to get_one
3469
        $column = static::getSchema()->sqlColumnForField($class, 'ID');
3470
        return DataObject::get_one($class, [$column => $id], $cached);
3471
    }
3472
3473
    /**
3474
     * Get the name of the base table for this object
3475
     *
3476
     * @return string
3477
     */
3478
    public function baseTable()
3479
    {
3480
        return static::getSchema()->baseDataTable($this);
3481
    }
3482
3483
    /**
3484
     * Get the base class for this object
3485
     *
3486
     * @return string
3487
     */
3488
    public function baseClass()
3489
    {
3490
        return static::getSchema()->baseDataClass($this);
3491
    }
3492
3493
    /**
3494
     * @var array Parameters used in the query that built this object.
3495
     * This can be used by decorators (e.g. lazy loading) to
3496
     * run additional queries using the same context.
3497
     */
3498
    protected $sourceQueryParams;
3499
3500
    /**
3501
     * @see $sourceQueryParams
3502
     * @return array
3503
     */
3504
    public function getSourceQueryParams()
3505
    {
3506
        return $this->sourceQueryParams;
3507
    }
3508
3509
    /**
3510
     * Get list of parameters that should be inherited to relations on this object
3511
     *
3512
     * @return array
3513
     */
3514
    public function getInheritableQueryParams()
3515
    {
3516
        $params = $this->getSourceQueryParams();
3517
        $this->extend('updateInheritableQueryParams', $params);
3518
        return $params;
3519
    }
3520
3521
    /**
3522
     * @see $sourceQueryParams
3523
     * @param array $array
3524
     */
3525
    public function setSourceQueryParams($array)
3526
    {
3527
        $this->sourceQueryParams = $array;
3528
    }
3529
3530
    /**
3531
     * @see $sourceQueryParams
3532
     * @param string $key
3533
     * @param string $value
3534
     */
3535
    public function setSourceQueryParam($key, $value)
3536
    {
3537
        $this->sourceQueryParams[$key] = $value;
3538
    }
3539
3540
    /**
3541
     * @see $sourceQueryParams
3542
     * @param string $key
3543
     * @return string
3544
     */
3545
    public function getSourceQueryParam($key)
3546
    {
3547
        if (isset($this->sourceQueryParams[$key])) {
3548
            return $this->sourceQueryParams[$key];
3549
        }
3550
        return null;
3551
    }
3552
3553
    //-------------------------------------------------------------------------------------------//
3554
3555
    /**
3556
     * Check the database schema and update it as necessary.
3557
     *
3558
     * @uses DataExtension::augmentDatabase()
3559
     */
3560
    public function requireTable()
3561
    {
3562
        // Only build the table if we've actually got fields
3563
        $schema = static::getSchema();
3564
        $table = $schema->tableName(static::class);
3565
        $fields = $schema->databaseFields(static::class, false);
3566
        $indexes = $schema->databaseIndexes(static::class, false);
3567
        $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

3567
        /** @scrutinizer ignore-call */ 
3568
        $extensions = self::database_extensions(static::class);
Loading history...
3568
3569
        if (empty($table)) {
3570
            throw new LogicException(
3571
                "Class " . static::class . " not loaded by manifest, or no database table configured"
3572
            );
3573
        }
3574
3575
        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...
3576
            $hasAutoIncPK = get_parent_class($this) === self::class;
3577
            DB::require_table(
3578
                $table,
3579
                $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

3579
                /** @scrutinizer ignore-type */ $fields,
Loading history...
3580
                $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

3580
                /** @scrutinizer ignore-type */ $indexes,
Loading history...
3581
                $hasAutoIncPK,
3582
                $this->config()->get('create_table_options'),
3583
                $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

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

3626
                DB::require_table($tableOrClass, /** @scrutinizer ignore-type */ $manymanyFields, $manymanyIndexes, true, null, $extensions);
Loading history...
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

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