Passed
Pull Request — 4.2 (#8831)
by Damian
06:58
created

DataObject::prepareManipulationTable()   C

Complexity

Conditions 12
Paths 80

Size

Total Lines 51
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 27
nc 80
nop 5
dl 0
loc 51
rs 6.9666
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\i18n\i18n;
19
use SilverStripe\i18n\i18nEntityProvider;
20
use SilverStripe\ORM\Connect\MySQLSchemaManager;
21
use SilverStripe\ORM\FieldType\DBClassName;
22
use SilverStripe\ORM\FieldType\DBComposite;
23
use SilverStripe\ORM\FieldType\DBDatetime;
24
use SilverStripe\ORM\FieldType\DBField;
25
use SilverStripe\ORM\Filters\SearchFilter;
26
use SilverStripe\ORM\Queries\SQLDelete;
27
use SilverStripe\ORM\Queries\SQLInsert;
28
use SilverStripe\ORM\Search\SearchContext;
29
use SilverStripe\Security\Member;
30
use SilverStripe\Security\Permission;
31
use SilverStripe\Security\Security;
32
use SilverStripe\View\SSViewer;
33
use SilverStripe\View\ViewableData;
34
use stdClass;
35
36
/**
37
 * A single database record & abstract class for the data-access-model.
38
 *
39
 * <h2>Extensions</h2>
40
 *
41
 * See {@link Extension} and {@link DataExtension}.
42
 *
43
 * <h2>Permission Control</h2>
44
 *
45
 * Object-level access control by {@link Permission}. Permission codes are arbitrary
46
 * strings which can be selected on a group-by-group basis.
47
 *
48
 * <code>
49
 * class Article extends DataObject implements PermissionProvider {
50
 *  static $api_access = true;
51
 *
52
 *  function canView($member = false) {
53
 *    return Permission::check('ARTICLE_VIEW');
54
 *  }
55
 *  function canEdit($member = false) {
56
 *    return Permission::check('ARTICLE_EDIT');
57
 *  }
58
 *  function canDelete() {
59
 *    return Permission::check('ARTICLE_DELETE');
60
 *  }
61
 *  function canCreate() {
62
 *    return Permission::check('ARTICLE_CREATE');
63
 *  }
64
 *  function providePermissions() {
65
 *    return array(
66
 *      'ARTICLE_VIEW' => 'Read an article object',
67
 *      'ARTICLE_EDIT' => 'Edit an article object',
68
 *      'ARTICLE_DELETE' => 'Delete an article object',
69
 *      'ARTICLE_CREATE' => 'Create an article object',
70
 *    );
71
 *  }
72
 * }
73
 * </code>
74
 *
75
 * Object-level access control by {@link Group} membership:
76
 * <code>
77
 * class Article extends DataObject {
78
 *   static $api_access = true;
79
 *
80
 *   function canView($member = false) {
81
 *     if(!$member) $member = Security::getCurrentUser();
82
 *     return $member->inGroup('Subscribers');
83
 *   }
84
 *   function canEdit($member = false) {
85
 *     if(!$member) $member = Security::getCurrentUser();
86
 *     return $member->inGroup('Editors');
87
 *   }
88
 *
89
 *   // ...
90
 * }
91
 * </code>
92
 *
93
 * If any public method on this class is prefixed with an underscore,
94
 * the results are cached in memory through {@link cachedCall()}.
95
 *
96
 *
97
 * @todo Add instance specific removeExtension() which undos loadExtraStatics()
98
 *  and defineMethods()
99
 *
100
 * @property int $ID ID of the DataObject, 0 if the DataObject doesn't exist in database.
101
 * @property int $OldID ID of object, if deleted
102
 * @property string $Title
103
 * @property string $ClassName Class name of the DataObject
104
 * @property string $LastEdited Date and time of DataObject's last modification.
105
 * @property string $Created Date and time of DataObject creation.
106
 * @property string $ObsoleteClassName If ClassName no longer exists this will be set to the legacy value
107
 */
108
class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider, Resettable
109
{
110
111
    /**
112
     * Human-readable singular name.
113
     * @var string
114
     * @config
115
     */
116
    private static $singular_name = null;
117
118
    /**
119
     * Human-readable plural name
120
     * @var string
121
     * @config
122
     */
123
    private static $plural_name = null;
124
125
    /**
126
     * Allow API access to this object?
127
     * @todo Define the options that can be set here
128
     * @config
129
     */
130
    private static $api_access = false;
131
132
    /**
133
     * Allows specification of a default value for the ClassName field.
134
     * Configure this value only in subclasses of DataObject.
135
     *
136
     * @config
137
     * @var string
138
     */
139
    private static $default_classname = null;
140
141
    /**
142
     * @deprecated 4.0..5.0
143
     * @var bool
144
     */
145
    public $destroyed = false;
146
147
    /**
148
     * Data stored in this objects database record. An array indexed by fieldname.
149
     *
150
     * Use {@link toMap()} if you want an array representation
151
     * of this object, as the $record array might contain lazy loaded field aliases.
152
     *
153
     * @var array
154
     */
155
    protected $record;
156
157
    /**
158
     * If selected through a many_many through relation, this is the instance of the through record
159
     *
160
     * @var DataObject
161
     */
162
    protected $joinRecord;
163
164
    /**
165
     * Represents a field that hasn't changed (before === after, thus before == after)
166
     */
167
    const CHANGE_NONE = 0;
168
169
    /**
170
     * Represents a field that has changed type, although not the loosely defined value.
171
     * (before !== after && before == after)
172
     * E.g. change 1 to true or "true" to true, but not true to 0.
173
     * Value changes are by nature also considered strict changes.
174
     */
175
    const CHANGE_STRICT = 1;
176
177
    /**
178
     * Represents a field that has changed the loosely defined value
179
     * (before != after, thus, before !== after))
180
     * E.g. change false to true, but not false to 0
181
     */
182
    const CHANGE_VALUE = 2;
183
184
    /**
185
     * An array indexed by fieldname, true if the field has been changed.
186
     * Use {@link getChangedFields()} and {@link isChanged()} to inspect
187
     * the changed state.
188
     *
189
     * @var array
190
     */
191
    private $changed;
192
193
    /**
194
     * The database record (in the same format as $record), before
195
     * any changes.
196
     * @var array
197
     */
198
    protected $original;
199
200
    /**
201
     * Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete()
202
     * @var boolean
203
     */
204
    protected $brokenOnDelete = false;
205
206
    /**
207
     * Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite()
208
     * @var boolean
209
     */
210
    protected $brokenOnWrite = false;
211
212
    /**
213
     * @config
214
     * @var boolean Should dataobjects be validated before they are written?
215
     * Caution: Validation can contain safeguards against invalid/malicious data,
216
     * and check permission levels (e.g. on {@link Group}). Therefore it is recommended
217
     * to only disable validation for very specific use cases.
218
     */
219
    private static $validation_enabled = true;
220
221
    /**
222
     * Static caches used by relevant functions.
223
     *
224
     * @var array
225
     */
226
    protected static $_cache_get_one;
227
228
    /**
229
     * Cache of field labels
230
     *
231
     * @var array
232
     */
233
    protected static $_cache_field_labels = array();
234
235
    /**
236
     * Base fields which are not defined in static $db
237
     *
238
     * @config
239
     * @var array
240
     */
241
    private static $fixed_fields = array(
242
        'ID' => 'PrimaryKey',
243
        'ClassName' => 'DBClassName',
244
        'LastEdited' => 'DBDatetime',
245
        'Created' => 'DBDatetime',
246
    );
247
248
    /**
249
     * Override table name for this class. If ignored will default to FQN of class.
250
     * This option is not inheritable, and must be set on each class.
251
     * If left blank naming will default to the legacy (3.x) behaviour.
252
     *
253
     * @var string
254
     */
255
    private static $table_name = null;
256
257
    /**
258
     * Non-static relationship cache, indexed by component name.
259
     *
260
     * @var DataObject[]
261
     */
262
    protected $components = [];
263
264
    /**
265
     * Non-static cache of has_many and many_many relations that can't be written until this object is saved.
266
     *
267
     * @var UnsavedRelationList[]
268
     */
269
    protected $unsavedRelations;
270
271
    /**
272
     * List of relations that should be cascade deleted, similar to `owns`
273
     * Note: This will trigger delete on many_many objects, not only the mapping table.
274
     * For many_many through you can specify the components you want to delete separately
275
     * (many_many or has_many sub-component)
276
     *
277
     * @config
278
     * @var array
279
     */
280
    private static $cascade_deletes = [];
281
282
    /**
283
     * List of relations that should be cascade duplicate.
284
     * many_many duplications are shallow only.
285
     *
286
     * Note: If duplicating a many_many through you should refer to the
287
     * has_many intermediary relation instead, otherwise extra fields
288
     * will be omitted from the duplicated relation.
289
     *
290
     * @var array
291
     */
292
    private static $cascade_duplicates = [];
293
294
    /**
295
     * Get schema object
296
     *
297
     * @return DataObjectSchema
298
     */
299
    public static function getSchema()
300
    {
301
        return Injector::inst()->get(DataObjectSchema::class);
302
    }
303
304
    /**
305
     * Construct a new DataObject.
306
     *
307
     * @param array|null $record Used internally for rehydrating an object from database content.
308
     *                           Bypasses setters on this class, and hence should not be used
309
     *                           for populating data on new records.
310
     * @param boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods.
311
     *                             Singletons don't have their defaults set.
312
     * @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects.
313
     */
314
    public function __construct($record = null, $isSingleton = false, $queryParams = array())
315
    {
316
        parent::__construct();
317
318
        // Set query params on the DataObject to tell the lazy loading mechanism the context the object creation context
319
        $this->setSourceQueryParams($queryParams);
320
321
        // Set the fields data.
322
        if (!$record) {
323
            $record = array(
324
                'ID' => 0,
325
                'ClassName' => static::class,
326
                'RecordClassName' => static::class
327
            );
328
        }
329
330
        if ($record instanceof stdClass) {
0 ignored issues
show
introduced by
$record is never a sub-type of stdClass.
Loading history...
331
            $record = (array)$record;
332
        }
333
334
        if (!is_array($record)) {
0 ignored issues
show
introduced by
The condition is_array($record) is always true.
Loading history...
335
            if (is_object($record)) {
336
                $passed = "an object of type '" . get_class($record) . "'";
337
            } else {
338
                $passed = "The value '$record'";
339
            }
340
341
            user_error(
342
                "DataObject::__construct passed $passed.  It's supposed to be passed an array,"
343
                . " taken straight from the database.  Perhaps you should use DataList::create()->First(); instead?",
344
                E_USER_WARNING
345
            );
346
            $record = null;
347
        }
348
349
        // Set $this->record to $record, but ignore NULLs
350
        $this->record = array();
351
        foreach ($record as $k => $v) {
352
            // Ensure that ID is stored as a number and not a string
353
            // To do: this kind of clean-up should be done on all numeric fields, in some relatively
354
            // performant manner
355
            if ($v !== null) {
356
                if ($k == 'ID' && is_numeric($v)) {
357
                    $this->record[$k] = (int)$v;
358
                } else {
359
                    $this->record[$k] = $v;
360
                }
361
            }
362
        }
363
364
        // Identify fields that should be lazy loaded, but only on existing records
365
        if (!empty($record['ID'])) {
366
            // Get all field specs scoped to class for later lazy loading
367
            $fields = static::getSchema()->fieldSpecs(
368
                static::class,
369
                DataObjectSchema::INCLUDE_CLASS | DataObjectSchema::DB_ONLY
370
            );
371
            foreach ($fields as $field => $fieldSpec) {
372
                $fieldClass = strtok($fieldSpec, ".");
373
                if (!array_key_exists($field, $record)) {
374
                    $this->record[$field . '_Lazy'] = $fieldClass;
375
                }
376
            }
377
        }
378
379
        $this->original = $this->record;
380
381
        // Must be called after parent constructor
382
        if (!$isSingleton && (!isset($this->record['ID']) || !$this->record['ID'])) {
383
            $this->populateDefaults();
384
        }
385
386
        // prevent populateDefaults() and setField() from marking overwritten defaults as changed
387
        $this->changed = array();
388
    }
389
390
    /**
391
     * Destroy all of this objects dependant objects and local caches.
392
     * You'll need to call this to get the memory of an object that has components or extensions freed.
393
     */
394
    public function destroy()
395
    {
396
        $this->flushCache(false);
397
    }
398
399
    /**
400
     * Create a duplicate of this node. Can duplicate many_many relations
401
     *
402
     * @param bool $doWrite Perform a write() operation before returning the object.
403
     * If this is true, it will create the duplicate in the database.
404
     * @param array|null|false $relations List of relations to duplicate.
405
     * Will default to `cascade_duplicates` if null.
406
     * Set to 'false' to force none.
407
     * Set to specific array of names to duplicate to override these.
408
     * Note: If using versioned, this will additionally failover to `owns` config.
409
     * @return static A duplicate of this node. The exact type will be the type of this node.
410
     */
411
    public function duplicate($doWrite = true, $relations = null)
412
    {
413
        // Handle legacy behaviour
414
        if (is_string($relations) || $relations === true) {
0 ignored issues
show
introduced by
The condition $relations === true is always false.
Loading history...
415
            if ($relations === true) {
416
                $relations = 'many_many';
417
            }
418
            Deprecation::notice('5.0', 'Use cascade_duplicates config instead of providing a string to duplicate()');
419
            $relations = array_keys($this->config()->get($relations)) ?: [];
420
        }
421
422
        // Get duplicates
423
        if ($relations === null) {
424
            $relations = $this->config()->get('cascade_duplicates');
425
            // Remove any duplicate entries before duplicating them
426
            if (is_array($relations)) {
427
                $relations = array_unique($relations);
428
            }
429
        }
430
431
        // Create unsaved raw duplicate
432
        $map = $this->toMap();
433
        unset($map['Created']);
434
        /** @var static $clone */
435
        $clone = Injector::inst()->create(static::class, $map, false, $this->getSourceQueryParams());
436
        $clone->ID = 0;
437
438
        // Note: Extensions such as versioned may update $relations here
439
        $clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite, $relations);
440
        if ($relations) {
441
            $this->duplicateRelations($this, $clone, $relations);
442
        }
443
        if ($doWrite) {
444
            $clone->write();
445
        }
446
        $clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite, $relations);
447
448
        return $clone;
449
    }
450
451
    /**
452
     * Copies the given relations from this object to the destination
453
     *
454
     * @param DataObject $sourceObject the source object to duplicate from
455
     * @param DataObject $destinationObject the destination object to populate with the duplicated relations
456
     * @param array $relations List of relations
457
     */
458
    protected function duplicateRelations($sourceObject, $destinationObject, $relations)
459
    {
460
        // Get list of duplicable relation types
461
        $manyMany = $sourceObject->manyMany();
462
        $hasMany = $sourceObject->hasMany();
463
        $hasOne = $sourceObject->hasOne();
464
        $belongsTo = $sourceObject->belongsTo();
465
466
        // Duplicate each relation based on type
467
        foreach ($relations as $relation) {
468
            switch (true) {
469
                case array_key_exists($relation, $manyMany): {
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
470
                    $this->duplicateManyManyRelation($sourceObject, $destinationObject, $relation);
471
                    break;
472
                }
473
                case array_key_exists($relation, $hasMany): {
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
474
                    $this->duplicateHasManyRelation($sourceObject, $destinationObject, $relation);
475
                    break;
476
                }
477
                case array_key_exists($relation, $hasOne): {
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
478
                    $this->duplicateHasOneRelation($sourceObject, $destinationObject, $relation);
479
                    break;
480
                }
481
                case array_key_exists($relation, $belongsTo): {
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
482
                    $this->duplicateBelongsToRelation($sourceObject, $destinationObject, $relation);
483
                    break;
484
                }
485
                default: {
0 ignored issues
show
Coding Style introduced by
DEFAULT statements must be defined using a colon

As per the PSR-2 coding standard, default statements should not be wrapped in curly braces.

switch ($expr) {
    default: { //wrong
        doSomething();
        break;
    }
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
486
                    $sourceType = get_class($sourceObject);
487
                    throw new InvalidArgumentException(
488
                        "Cannot duplicate unknown relation {$relation} on parent type {$sourceType}"
489
                    );
490
                }
491
            }
492
        }
493
    }
494
495
    /**
496
     * Copies the many_many and belongs_many_many relations from one object to another instance of the name of object.
497
     *
498
     * @deprecated 4.1...5.0 Use duplicateRelations() instead
499
     * @param DataObject $sourceObject the source object to duplicate from
500
     * @param DataObject $destinationObject the destination object to populate with the duplicated relations
501
     * @param bool|string $filter
502
     */
503
    protected function duplicateManyManyRelations($sourceObject, $destinationObject, $filter)
504
    {
505
        Deprecation::notice('5.0', 'Use duplicateRelations() instead');
506
507
        // Get list of relations to duplicate
508
        if ($filter === 'many_many' || $filter === 'belongs_many_many') {
509
            $relations = $sourceObject->config()->get($filter);
510
        } elseif ($filter === true) {
511
            $relations = $sourceObject->manyMany();
512
        } else {
513
            throw new InvalidArgumentException("Invalid many_many duplication filter");
514
        }
515
        foreach ($relations as $manyManyName => $type) {
516
            $this->duplicateManyManyRelation($sourceObject, $destinationObject, $manyManyName);
517
        }
518
    }
519
520
    /**
521
     * Duplicates a single many_many relation from one object to another.
522
     *
523
     * @param DataObject $sourceObject
524
     * @param DataObject $destinationObject
525
     * @param string $relation
526
     */
527
    protected function duplicateManyManyRelation($sourceObject, $destinationObject, $relation)
528
    {
529
        // Copy all components from source to destination
530
        $source = $sourceObject->getManyManyComponents($relation);
531
        $dest = $destinationObject->getManyManyComponents($relation);
532
533
        if ($source instanceof ManyManyList) {
534
            $extraFieldNames = $source->getExtraFields();
535
        } else {
536
            $extraFieldNames = [];
537
        }
538
539
        foreach ($source as $item) {
540
            // Merge extra fields
541
            $extraFields = [];
542
            foreach ($extraFieldNames as $fieldName => $fieldType) {
543
                $extraFields[$fieldName] = $item->getField($fieldName);
544
            }
545
            $dest->add($item, $extraFields);
546
        }
547
    }
548
549
    /**
550
     * Duplicates a single many_many relation from one object to another.
551
     *
552
     * @param DataObject $sourceObject
553
     * @param DataObject $destinationObject
554
     * @param string $relation
555
     */
556
    protected function duplicateHasManyRelation($sourceObject, $destinationObject, $relation)
557
    {
558
        // Copy all components from source to destination
559
        $source = $sourceObject->getComponents($relation);
560
        $dest = $destinationObject->getComponents($relation);
561
562
        /** @var DataObject $item */
563
        foreach ($source as $item) {
564
            // Don't write on duplicate; Wait until ParentID is available later.
565
            // writeRelations() will eventually write these records when converting
566
            // from UnsavedRelationList
567
            $clonedItem = $item->duplicate(false);
568
            $dest->add($clonedItem);
569
        }
570
    }
571
572
    /**
573
     * Duplicates a single has_one relation from one object to another.
574
     * Note: Child object will be force written.
575
     *
576
     * @param DataObject $sourceObject
577
     * @param DataObject $destinationObject
578
     * @param string $relation
579
     */
580
    protected function duplicateHasOneRelation($sourceObject, $destinationObject, $relation)
581
    {
582
        // Check if original object exists
583
        $item = $sourceObject->getComponent($relation);
584
        if (!$item->isInDB()) {
585
            return;
586
        }
587
588
        $clonedItem = $item->duplicate(false);
589
        $destinationObject->setComponent($relation, $clonedItem);
590
    }
591
592
    /**
593
     * Duplicates a single belongs_to relation from one object to another.
594
     * Note: This will force a write on both parent / child objects.
595
     *
596
     * @param DataObject $sourceObject
597
     * @param DataObject $destinationObject
598
     * @param string $relation
599
     */
600
    protected function duplicateBelongsToRelation($sourceObject, $destinationObject, $relation)
601
    {
602
        // Check if original object exists
603
        $item = $sourceObject->getComponent($relation);
604
        if (!$item->isInDB()) {
605
            return;
606
        }
607
608
        $clonedItem = $item->duplicate(false);
609
        $destinationObject->setComponent($relation, $clonedItem);
610
        // After $clonedItem is assigned the appropriate FieldID / FieldClass, force write
611
        // @todo Write this component in onAfterWrite instead, assigning the FieldID then
612
        // https://github.com/silverstripe/silverstripe-framework/issues/7818
613
        $clonedItem->write();
614
    }
615
616
    /**
617
     * Return obsolete class name, if this is no longer a valid class
618
     *
619
     * @return string
620
     */
621
    public function getObsoleteClassName()
622
    {
623
        $className = $this->getField("ClassName");
624
        if (!ClassInfo::exists($className)) {
625
            return $className;
626
        }
627
        return null;
628
    }
629
630
    /**
631
     * Gets name of this class
632
     *
633
     * @return string
634
     */
635
    public function getClassName()
636
    {
637
        $className = $this->getField("ClassName");
638
        if (!ClassInfo::exists($className)) {
639
            return static::class;
640
        }
641
        return $className;
642
    }
643
644
    /**
645
     * Set the ClassName attribute. {@link $class} is also updated.
646
     * Warning: This will produce an inconsistent record, as the object
647
     * instance will not automatically switch to the new subclass.
648
     * Please use {@link newClassInstance()} for this purpose,
649
     * or destroy and reinstanciate the record.
650
     *
651
     * @param string $className The new ClassName attribute (a subclass of {@link DataObject})
652
     * @return $this
653
     */
654
    public function setClassName($className)
655
    {
656
        $className = trim($className);
657
        if (!$className || !is_subclass_of($className, self::class)) {
658
            return $this;
659
        }
660
661
        $this->setField("ClassName", $className);
662
        $this->setField('RecordClassName', $className);
663
        return $this;
664
    }
665
666
    /**
667
     * Create a new instance of a different class from this object's record.
668
     * This is useful when dynamically changing the type of an instance. Specifically,
669
     * it ensures that the instance of the class is a match for the className of the
670
     * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName}
671
     * property manually before calling this method, as it will confuse change detection.
672
     *
673
     * If the new class is different to the original class, defaults are populated again
674
     * because this will only occur automatically on instantiation of a DataObject if
675
     * there is no record, or the record has no ID. In this case, we do have an ID but
676
     * we still need to repopulate the defaults.
677
     *
678
     * @param string $newClassName The name of the new class
679
     *
680
     * @return DataObject The new instance of the new class, The exact type will be of the class name provided.
681
     */
682
    public function newClassInstance($newClassName)
683
    {
684
        if (!is_subclass_of($newClassName, self::class)) {
685
            throw new InvalidArgumentException("$newClassName is not a valid subclass of DataObject");
686
        }
687
688
        $originalClass = $this->ClassName;
689
690
        /** @var DataObject $newInstance */
691
        $newInstance = Injector::inst()->create($newClassName, $this->record, false);
692
693
        // Modify ClassName
694
        if ($newClassName != $originalClass) {
695
            $newInstance->setClassName($newClassName);
696
            $newInstance->populateDefaults();
697
            $newInstance->forceChange();
698
        }
699
700
        return $newInstance;
701
    }
702
703
    /**
704
     * Adds methods from the extensions.
705
     * Called by Object::__construct() once per class.
706
     */
707
    public function defineMethods()
708
    {
709
        parent::defineMethods();
710
711
        if (static::class === self::class) {
0 ignored issues
show
introduced by
The condition static::class === self::class is always true.
Loading history...
712
            return;
713
        }
714
715
        // Set up accessors for joined items
716
        if ($manyMany = $this->manyMany()) {
717
            foreach ($manyMany as $relationship => $class) {
718
                $this->addWrapperMethod($relationship, 'getManyManyComponents');
719
            }
720
        }
721
        if ($hasMany = $this->hasMany()) {
722
            foreach ($hasMany as $relationship => $class) {
723
                $this->addWrapperMethod($relationship, 'getComponents');
724
            }
725
        }
726
        if ($hasOne = $this->hasOne()) {
727
            foreach ($hasOne as $relationship => $class) {
728
                $this->addWrapperMethod($relationship, 'getComponent');
729
            }
730
        }
731
        if ($belongsTo = $this->belongsTo()) {
732
            foreach (array_keys($belongsTo) as $relationship) {
733
                $this->addWrapperMethod($relationship, 'getComponent');
734
            }
735
        }
736
    }
737
738
    /**
739
     * Returns true if this object "exists", i.e., has a sensible value.
740
     * The default behaviour for a DataObject is to return true if
741
     * the object exists in the database, you can override this in subclasses.
742
     *
743
     * @return boolean true if this object exists
744
     */
745
    public function exists()
746
    {
747
        return (isset($this->record['ID']) && $this->record['ID'] > 0);
748
    }
749
750
    /**
751
     * Returns TRUE if all values (other than "ID") are
752
     * considered empty (by weak boolean comparison).
753
     *
754
     * @return boolean
755
     */
756
    public function isEmpty()
757
    {
758
        $fixed = DataObject::config()->uninherited('fixed_fields');
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
759
        foreach ($this->toMap() as $field => $value) {
760
            // only look at custom fields
761
            if (isset($fixed[$field])) {
762
                continue;
763
            }
764
765
            $dbObject = $this->dbObject($field);
766
            if (!$dbObject) {
767
                continue;
768
            }
769
            if ($dbObject->exists()) {
770
                return false;
771
            }
772
        }
773
        return true;
774
    }
775
776
    /**
777
     * Pluralise this item given a specific count.
778
     *
779
     * E.g. "0 Pages", "1 File", "3 Images"
780
     *
781
     * @param string $count
782
     * @return string
783
     */
784
    public function i18n_pluralise($count)
785
    {
786
        $default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name();
787
        return i18n::_t(
788
            static::class . '.PLURALS',
789
            $default,
790
            ['count' => $count]
791
        );
792
    }
793
794
    /**
795
     * Get the user friendly singular name of this DataObject.
796
     * If the name is not defined (by redefining $singular_name in the subclass),
797
     * this returns the class name.
798
     *
799
     * @return string User friendly singular name of this DataObject
800
     */
801
    public function singular_name()
802
    {
803
        $name = $this->config()->get('singular_name');
804
        if ($name) {
805
            return $name;
806
        }
807
        return ucwords(trim(strtolower(preg_replace(
808
            '/_?([A-Z])/',
809
            ' $1',
810
            ClassInfo::shortName($this)
811
        ))));
812
    }
813
814
    /**
815
     * Get the translated user friendly singular name of this DataObject
816
     * same as singular_name() but runs it through the translating function
817
     *
818
     * Translating string is in the form:
819
     *     $this->class.SINGULARNAME
820
     * Example:
821
     *     Page.SINGULARNAME
822
     *
823
     * @return string User friendly translated singular name of this DataObject
824
     */
825
    public function i18n_singular_name()
826
    {
827
        return _t(static::class . '.SINGULARNAME', $this->singular_name());
828
    }
829
830
    /**
831
     * Get the user friendly plural name of this DataObject
832
     * If the name is not defined (by renaming $plural_name in the subclass),
833
     * this returns a pluralised version of the class name.
834
     *
835
     * @return string User friendly plural name of this DataObject
836
     */
837
    public function plural_name()
838
    {
839
        if ($name = $this->config()->get('plural_name')) {
840
            return $name;
841
        }
842
        $name = $this->singular_name();
843
        //if the penultimate character is not a vowel, replace "y" with "ies"
844
        if (preg_match('/[^aeiou]y$/i', $name)) {
845
            $name = substr($name, 0, -1) . 'ie';
846
        }
847
        return ucfirst($name . 's');
848
    }
849
850
    /**
851
     * Get the translated user friendly plural name of this DataObject
852
     * Same as plural_name but runs it through the translation function
853
     * Translation string is in the form:
854
     *      $this->class.PLURALNAME
855
     * Example:
856
     *      Page.PLURALNAME
857
     *
858
     * @return string User friendly translated plural name of this DataObject
859
     */
860
    public function i18n_plural_name()
861
    {
862
        return _t(static::class . '.PLURALNAME', $this->plural_name());
863
    }
864
865
    /**
866
     * Standard implementation of a title/label for a specific
867
     * record. Tries to find properties 'Title' or 'Name',
868
     * and falls back to the 'ID'. Useful to provide
869
     * user-friendly identification of a record, e.g. in errormessages
870
     * or UI-selections.
871
     *
872
     * Overload this method to have a more specialized implementation,
873
     * e.g. for an Address record this could be:
874
     * <code>
875
     * function getTitle() {
876
     *   return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
877
     * }
878
     * </code>
879
     *
880
     * @return string
881
     */
882
    public function getTitle()
883
    {
884
        $schema = static::getSchema();
885
        if ($schema->fieldSpec($this, 'Title')) {
886
            return $this->getField('Title');
887
        }
888
        if ($schema->fieldSpec($this, 'Name')) {
889
            return $this->getField('Name');
890
        }
891
892
        return "#{$this->ID}";
893
    }
894
895
    /**
896
     * Returns the associated database record - in this case, the object itself.
897
     * This is included so that you can call $dataOrController->data() and get a DataObject all the time.
898
     *
899
     * @return DataObject Associated database record
900
     */
901
    public function data()
902
    {
903
        return $this;
904
    }
905
906
    /**
907
     * Convert this object to a map.
908
     *
909
     * @return array The data as a map.
910
     */
911
    public function toMap()
912
    {
913
        $this->loadLazyFields();
914
        return $this->record;
915
    }
916
917
    /**
918
     * Return all currently fetched database fields.
919
     *
920
     * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
921
     * Obviously, this makes it a lot faster.
922
     *
923
     * @return array The data as a map.
924
     */
925
    public function getQueriedDatabaseFields()
926
    {
927
        return $this->record;
928
    }
929
930
    /**
931
     * Update a number of fields on this object, given a map of the desired changes.
932
     *
933
     * The field names can be simple names, or you can use a dot syntax to access $has_one relations.
934
     * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
935
     *
936
     * update() doesn't write the main object, but if you use the dot syntax, it will write()
937
     * the related objects that it alters.
938
     *
939
     * @param array $data A map of field name to data values to update.
940
     * @return DataObject $this
941
     */
942
    public function update($data)
943
    {
944
        foreach ($data as $key => $value) {
945
            // Implement dot syntax for updates
946
            if (strpos($key, '.') !== false) {
947
                $relations = explode('.', $key);
948
                $fieldName = array_pop($relations);
949
                /** @var static $relObj */
950
                $relObj = $this;
951
                $relation = null;
952
                foreach ($relations as $i => $relation) {
953
                    // no support for has_many or many_many relationships,
954
                    // as the updater wouldn't know which object to write to (or create)
955
                    if ($relObj->$relation() instanceof DataObject) {
956
                        $parentObj = $relObj;
957
                        $relObj = $relObj->$relation();
958
                        // If the intermediate relationship objects haven't been created, then write them
959
                        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...
960
                            $relObj->write();
961
                            $relatedFieldName = $relation . "ID";
962
                            $parentObj->$relatedFieldName = $relObj->ID;
963
                            $parentObj->write();
964
                        }
965
                    } else {
966
                        user_error(
967
                            "DataObject::update(): Can't traverse relationship '$relation'," .
968
                            "it has to be a has_one relationship or return a single DataObject",
969
                            E_USER_NOTICE
970
                        );
971
                        // unset relation object so we don't write properties to the wrong object
972
                        $relObj = null;
973
                        break;
974
                    }
975
                }
976
977
                if ($relObj) {
978
                    $relObj->$fieldName = $value;
979
                    $relObj->write();
980
                    $relatedFieldName = $relation . "ID";
981
                    $this->$relatedFieldName = $relObj->ID;
982
                    $relObj->flushCache();
983
                } else {
984
                    $class = static::class;
985
                    user_error("Couldn't follow dot syntax '{$key}' on '{$class}' object", E_USER_WARNING);
986
                }
987
            } else {
988
                $this->$key = $value;
989
            }
990
        }
991
        return $this;
992
    }
993
994
    /**
995
     * Pass changes as a map, and try to
996
     * get automatic casting for these fields.
997
     * Doesn't write to the database. To write the data,
998
     * use the write() method.
999
     *
1000
     * @param array $data A map of field name to data values to update.
1001
     * @return DataObject $this
1002
     */
1003
    public function castedUpdate($data)
1004
    {
1005
        foreach ($data as $k => $v) {
1006
            $this->setCastedField($k, $v);
1007
        }
1008
        return $this;
1009
    }
1010
1011
    /**
1012
     * Merges data and relations from another object of same class,
1013
     * without conflict resolution. Allows to specify which
1014
     * dataset takes priority in case its not empty.
1015
     * has_one-relations are just transferred with priority 'right'.
1016
     * has_many and many_many-relations are added regardless of priority.
1017
     *
1018
     * Caution: has_many/many_many relations are moved rather than duplicated,
1019
     * meaning they are not connected to the merged object any longer.
1020
     * Caution: Just saves updated has_many/many_many relations to the database,
1021
     * doesn't write the updated object itself (just writes the object-properties).
1022
     * Caution: Does not delete the merged object.
1023
     * Caution: Does now overwrite Created date on the original object.
1024
     *
1025
     * @param DataObject $rightObj
1026
     * @param string $priority left|right Determines who wins in case of a conflict (optional)
1027
     * @param bool $includeRelations Merge any existing relations (optional)
1028
     * @param bool $overwriteWithEmpty Overwrite existing left values with empty right values.
1029
     *                            Only applicable with $priority='right'. (optional)
1030
     * @return Boolean
1031
     */
1032
    public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false)
1033
    {
1034
        $leftObj = $this;
1035
1036
        if ($leftObj->ClassName != $rightObj->ClassName) {
1037
            // we can't merge similiar subclasses because they might have additional relations
1038
            user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
1039
			(expected '{$leftObj->ClassName}').", E_USER_WARNING);
1040
            return false;
1041
        }
1042
1043
        if (!$rightObj->ID) {
1044
            user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
1045
				to make sure all relations are transferred properly.').", E_USER_WARNING);
1046
            return false;
1047
        }
1048
1049
        // makes sure we don't merge data like ID or ClassName
1050
        $rightData = DataObject::getSchema()->fieldSpecs(get_class($rightObj));
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1051
        foreach ($rightData as $key => $rightSpec) {
1052
            // Don't merge ID
1053
            if ($key === 'ID') {
1054
                continue;
1055
            }
1056
1057
            // Only merge relations if allowed
1058
            if ($rightSpec === 'ForeignKey' && !$includeRelations) {
1059
                continue;
1060
            }
1061
1062
            // don't merge conflicting values if priority is 'left'
1063
            if ($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) {
1064
                continue;
1065
            }
1066
1067
            // don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
1068
            if ($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) {
1069
                continue;
1070
            }
1071
1072
            // TODO remove redundant merge of has_one fields
1073
            $leftObj->{$key} = $rightObj->{$key};
1074
        }
1075
1076
        // merge relations
1077
        if ($includeRelations) {
1078
            if ($manyMany = $this->manyMany()) {
1079
                foreach ($manyMany as $relationship => $class) {
1080
                    /** @var DataObject $leftComponents */
1081
                    $leftComponents = $leftObj->getManyManyComponents($relationship);
1082
                    $rightComponents = $rightObj->getManyManyComponents($relationship);
1083
                    if ($rightComponents && $rightComponents->exists()) {
1084
                        $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

1084
                        $leftComponents->/** @scrutinizer ignore-call */ 
1085
                                         addMany($rightComponents->column('ID'));
Loading history...
1085
                    }
1086
                    $leftComponents->write();
1087
                }
1088
            }
1089
1090
            if ($hasMany = $this->hasMany()) {
1091
                foreach ($hasMany as $relationship => $class) {
1092
                    $leftComponents = $leftObj->getComponents($relationship);
1093
                    $rightComponents = $rightObj->getComponents($relationship);
1094
                    if ($rightComponents && $rightComponents->exists()) {
1095
                        $leftComponents->addMany($rightComponents->column('ID'));
1096
                    }
1097
                    $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

1097
                    $leftComponents->/** @scrutinizer ignore-call */ 
1098
                                     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

1097
                    $leftComponents->/** @scrutinizer ignore-call */ 
1098
                                     write();
Loading history...
1098
                }
1099
            }
1100
        }
1101
1102
        return true;
1103
    }
1104
1105
    /**
1106
     * Forces the record to think that all its data has changed.
1107
     * Doesn't write to the database. Only sets fields as changed
1108
     * if they are not already marked as changed.
1109
     *
1110
     * @return $this
1111
     */
1112
    public function forceChange()
1113
    {
1114
        // Ensure lazy fields loaded
1115
        $this->loadLazyFields();
1116
        $fields = static::getSchema()->fieldSpecs(static::class);
1117
1118
        // $this->record might not contain the blank values so we loop on $this->inheritedDatabaseFields() as well
1119
        $fieldNames = array_unique(array_merge(
1120
            array_keys($this->record),
1121
            array_keys($fields)
1122
        ));
1123
1124
        foreach ($fieldNames as $fieldName) {
1125
            if (!isset($this->changed[$fieldName])) {
1126
                $this->changed[$fieldName] = self::CHANGE_STRICT;
1127
            }
1128
            // Populate the null values in record so that they actually get written
1129
            if (!isset($this->record[$fieldName])) {
1130
                $this->record[$fieldName] = null;
1131
            }
1132
        }
1133
1134
        // @todo Find better way to allow versioned to write a new version after forceChange
1135
        if ($this->isChanged('Version')) {
1136
            unset($this->changed['Version']);
1137
        }
1138
        return $this;
1139
    }
1140
1141
    /**
1142
     * Validate the current object.
1143
     *
1144
     * By default, there is no validation - objects are always valid!  However, you can overload this method in your
1145
     * DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
1146
     *
1147
     * Invalid objects won't be able to be written - a warning will be thrown and no write will occur.  onBeforeWrite()
1148
     * and onAfterWrite() won't get called either.
1149
     *
1150
     * It is expected that you call validate() in your own application to test that an object is valid before
1151
     * attempting a write, and respond appropriately if it isn't.
1152
     *
1153
     * @see {@link ValidationResult}
1154
     * @return ValidationResult
1155
     */
1156
    public function validate()
1157
    {
1158
        $result = ValidationResult::create();
1159
        $this->extend('validate', $result);
1160
        return $result;
1161
    }
1162
1163
    /**
1164
     * Public accessor for {@see DataObject::validate()}
1165
     *
1166
     * @return ValidationResult
1167
     */
1168
    public function doValidate()
1169
    {
1170
        Deprecation::notice('5.0', 'Use validate');
1171
        return $this->validate();
1172
    }
1173
1174
    /**
1175
     * Event handler called before writing to the database.
1176
     * You can overload this to clean up or otherwise process data before writing it to the
1177
     * database.  Don't forget to call parent::onBeforeWrite(), though!
1178
     *
1179
     * This called after {@link $this->validate()}, so you can be sure that your data is valid.
1180
     *
1181
     * @uses DataExtension->onBeforeWrite()
1182
     */
1183
    protected function onBeforeWrite()
1184
    {
1185
        $this->brokenOnWrite = false;
1186
1187
        $dummy = null;
1188
        $this->extend('onBeforeWrite', $dummy);
1189
    }
1190
1191
    /**
1192
     * Event handler called after writing to the database.
1193
     * You can overload this to act upon changes made to the data after it is written.
1194
     * $this->changed will have a record
1195
     * database.  Don't forget to call parent::onAfterWrite(), though!
1196
     *
1197
     * @uses DataExtension->onAfterWrite()
1198
     */
1199
    protected function onAfterWrite()
1200
    {
1201
        $dummy = null;
1202
        $this->extend('onAfterWrite', $dummy);
1203
    }
1204
1205
    /**
1206
     * Find all objects that will be cascade deleted if this object is deleted
1207
     *
1208
     * Notes:
1209
     *   - If this object is versioned, objects will only be searched in the same stage as the given record.
1210
     *   - This will only be useful prior to deletion, as post-deletion this record will no longer exist.
1211
     *
1212
     * @param bool $recursive True if recursive
1213
     * @param ArrayList $list Optional list to add items to
1214
     * @return ArrayList list of objects
1215
     */
1216
    public function findCascadeDeletes($recursive = true, $list = null)
1217
    {
1218
        // Find objects in these relationships
1219
        return $this->findRelatedObjects('cascade_deletes', $recursive, $list);
1220
    }
1221
1222
    /**
1223
     * Event handler called before deleting from the database.
1224
     * You can overload this to clean up or otherwise process data before delete this
1225
     * record.  Don't forget to call parent::onBeforeDelete(), though!
1226
     *
1227
     * @uses DataExtension->onBeforeDelete()
1228
     */
1229
    protected function onBeforeDelete()
1230
    {
1231
        $this->brokenOnDelete = false;
1232
1233
        $dummy = null;
1234
        $this->extend('onBeforeDelete', $dummy);
1235
1236
        // Cascade deletes
1237
        $deletes = $this->findCascadeDeletes(false);
1238
        foreach ($deletes as $delete) {
1239
            $delete->delete();
1240
        }
1241
    }
1242
1243
    protected function onAfterDelete()
1244
    {
1245
        $this->extend('onAfterDelete');
1246
    }
1247
1248
    /**
1249
     * Load the default values in from the self::$defaults array.
1250
     * Will traverse the defaults of the current class and all its parent classes.
1251
     * Called by the constructor when creating new records.
1252
     *
1253
     * @uses DataExtension->populateDefaults()
1254
     * @return DataObject $this
1255
     */
1256
    public function populateDefaults()
1257
    {
1258
        $classes = array_reverse(ClassInfo::ancestry($this));
1259
1260
        foreach ($classes as $class) {
1261
            $defaults = Config::inst()->get($class, 'defaults', Config::UNINHERITED);
1262
1263
            if ($defaults && !is_array($defaults)) {
1264
                user_error(
1265
                    "Bad '" . static::class . "' defaults given: " . var_export($defaults, true),
1266
                    E_USER_WARNING
1267
                );
1268
                $defaults = null;
1269
            }
1270
1271
            if ($defaults) {
1272
                foreach ($defaults as $fieldName => $fieldValue) {
1273
                    // SRM 2007-03-06: Stricter check
1274
                    if (!isset($this->$fieldName) || $this->$fieldName === null) {
1275
                        $this->$fieldName = $fieldValue;
1276
                    }
1277
                    // Set many-many defaults with an array of ids
1278
                    if (is_array($fieldValue) && $this->getSchema()->manyManyComponent(static::class, $fieldName)) {
1279
                        /** @var ManyManyList $manyManyJoin */
1280
                        $manyManyJoin = $this->$fieldName();
1281
                        $manyManyJoin->setByIDList($fieldValue);
1282
                    }
1283
                }
1284
            }
1285
            if ($class == self::class) {
1286
                break;
1287
            }
1288
        }
1289
1290
        $this->extend('populateDefaults');
1291
        return $this;
1292
    }
1293
1294
    /**
1295
     * Determine validation of this object prior to write
1296
     *
1297
     * @return ValidationException Exception generated by this write, or null if valid
1298
     */
1299
    protected function validateWrite()
1300
    {
1301
        if ($this->ObsoleteClassName) {
1302
            return new ValidationException(
1303
                "Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " .
1304
                "you need to change the ClassName before you can write it"
1305
            );
1306
        }
1307
1308
        // Note: Validation can only be disabled at the global level, not per-model
1309
        if (DataObject::config()->uninherited('validation_enabled')) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1310
            $result = $this->validate();
1311
            if (!$result->isValid()) {
1312
                return new ValidationException($result);
1313
            }
1314
        }
1315
        return null;
1316
    }
1317
1318
    /**
1319
     * Prepare an object prior to write
1320
     *
1321
     * @throws ValidationException
1322
     */
1323
    protected function preWrite()
1324
    {
1325
        // Validate this object
1326
        if ($writeException = $this->validateWrite()) {
1327
            // Used by DODs to clean up after themselves, eg, Versioned
1328
            $this->invokeWithExtensions('onAfterSkippedWrite');
1329
            throw $writeException;
1330
        }
1331
1332
        // Check onBeforeWrite
1333
        $this->brokenOnWrite = true;
1334
        $this->onBeforeWrite();
1335
        if ($this->brokenOnWrite) {
1336
            user_error(static::class . " has a broken onBeforeWrite() function."
1337
                . " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
1338
        }
1339
    }
1340
1341
    /**
1342
     * Detects and updates all changes made to this object
1343
     *
1344
     * @param bool $forceChanges If set to true, force all fields to be treated as changed
1345
     * @return bool True if any changes are detected
1346
     */
1347
    protected function updateChanges($forceChanges = false)
1348
    {
1349
        if ($forceChanges) {
1350
            // Force changes, but only for loaded fields
1351
            foreach ($this->record as $field => $value) {
1352
                $this->changed[$field] = static::CHANGE_VALUE;
1353
            }
1354
            return true;
1355
        }
1356
        return $this->isChanged();
1357
    }
1358
1359
    /**
1360
     * Writes a subset of changes for a specific table to the given manipulation
1361
     *
1362
     * @param string $baseTable Base table
1363
     * @param string $now Timestamp to use for the current time
1364
     * @param bool $isNewRecord Whether this should be treated as a new record write
1365
     * @param array $manipulation Manipulation to write to
1366
     * @param string $class Class of table to manipulate
1367
     */
1368
    protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class)
1369
    {
1370
        $schema = $this->getSchema();
1371
        $table = $schema->tableName($class);
1372
        $manipulation[$table] = array();
1373
1374
        // Extract records for this table
1375
        foreach ($this->record as $fieldName => $fieldValue) {
1376
            // we're not attempting to reset the BaseTable->ID
1377
            // Ignore unchanged fields or attempts to reset the BaseTable->ID
1378
            if (empty($this->changed[$fieldName]) || ($table === $baseTable && $fieldName === 'ID')) {
1379
                continue;
1380
            }
1381
1382
            // Ensure this field pertains to this table
1383
            $specification = $schema->fieldSpec(
1384
                $class,
1385
                $fieldName,
1386
                DataObjectSchema::DB_ONLY | DataObjectSchema::UNINHERITED
1387
            );
1388
            if (!$specification) {
1389
                continue;
1390
            }
1391
1392
            // if database column doesn't correlate to a DBField instance...
1393
            $fieldObj = $this->dbObject($fieldName);
1394
            if (!$fieldObj) {
1395
                $fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
1396
            }
1397
1398
            // Write to manipulation
1399
            $fieldObj->writeToManipulation($manipulation[$table]);
1400
        }
1401
1402
        // Ensure update of Created and LastEdited columns
1403
        if ($baseTable === $table) {
1404
            $manipulation[$table]['fields']['LastEdited'] = $now;
1405
            if ($isNewRecord) {
1406
                $manipulation[$table]['fields']['Created'] = empty($this->record['Created'])
1407
                    ? $now
1408
                    : $this->record['Created'];
1409
                $manipulation[$table]['fields']['ClassName'] = static::class;
1410
            }
1411
        }
1412
1413
        // Inserts done one the base table are performed in another step, so the manipulation should instead
1414
        // attempt an update, as though it were a normal update.
1415
        $manipulation[$table]['command'] = $isNewRecord ? 'insert' : 'update';
1416
        $manipulation[$table]['class'] = $class;
1417
        if ($this->isInDB()) {
1418
            $manipulation[$table]['id'] = $this->record['ID'];
1419
        }
1420
    }
1421
1422
    /**
1423
     * Ensures that a blank base record exists with the basic fixed fields for this dataobject
1424
     *
1425
     * Does nothing if an ID is already assigned for this record
1426
     *
1427
     * @param string $baseTable Base table
1428
     * @param string $now Timestamp to use for the current time
1429
     */
1430
    protected function writeBaseRecord($baseTable, $now)
1431
    {
1432
        // Generate new ID if not specified
1433
        if ($this->isInDB()) {
1434
            return;
1435
        }
1436
1437
        // Perform an insert on the base table
1438
        $manipulation = [];
1439
        $this->prepareManipulationTable($baseTable, $now, true, $manipulation, $this->baseClass());
1440
        DB::manipulate($manipulation);
1441
1442
        $this->changed['ID'] = self::CHANGE_VALUE;
1443
        $this->record['ID'] = DB::get_generated_id($baseTable);
1444
    }
1445
1446
    /**
1447
     * Generate and write the database manipulation for all changed fields
1448
     *
1449
     * @param string $baseTable Base table
1450
     * @param string $now Timestamp to use for the current time
1451
     * @param bool $isNewRecord If this is a new record
1452
     * @throws InvalidArgumentException
1453
     */
1454
    protected function writeManipulation($baseTable, $now, $isNewRecord)
1455
    {
1456
        // Generate database manipulations for each class
1457
        $manipulation = array();
1458
        foreach (ClassInfo::ancestry(static::class, true) as $class) {
1459
            $this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
1460
        }
1461
1462
        // Allow extensions to extend this manipulation
1463
        $this->extend('augmentWrite', $manipulation);
1464
1465
        // New records have their insert into the base data table done first, so that they can pass the
1466
        // generated ID on to the rest of the manipulation
1467
        if ($isNewRecord) {
1468
            $manipulation[$baseTable]['command'] = 'update';
1469
        }
1470
1471
        // Make sure none of our field assignment are arrays
1472
        foreach ($manipulation as $tableManipulation) {
1473
            if (!isset($tableManipulation['fields'])) {
1474
                continue;
1475
            }
1476
            foreach ($tableManipulation['fields'] as $fieldName => $fieldValue) {
1477
                if (is_array($fieldValue)) {
1478
                    $dbObject = $this->dbObject($fieldName);
1479
                    // If the field allows non-scalar values we'll let it do dynamic assignments
1480
                    if ($dbObject && $dbObject->scalarValueOnly()) {
1481
                        throw new InvalidArgumentException(
1482
                            'DataObject::writeManipulation: parameterised field assignments are disallowed'
1483
                        );
1484
                    }
1485
                }
1486
            }
1487
        }
1488
1489
        // Perform the manipulation
1490
        DB::manipulate($manipulation);
1491
    }
1492
1493
    /**
1494
     * Writes all changes to this object to the database.
1495
     *  - It will insert a record whenever ID isn't set, otherwise update.
1496
     *  - All relevant tables will be updated.
1497
     *  - $this->onBeforeWrite() gets called beforehand.
1498
     *  - Extensions such as Versioned will ammend the database-write to ensure that a version is saved.
1499
     *
1500
     * @uses DataExtension->augmentWrite()
1501
     *
1502
     * @param boolean $showDebug Show debugging information
1503
     * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
1504
     * @param boolean $forceWrite Write to database even if there are no changes
1505
     * @param boolean $writeComponents Call write() on all associated component instances which were previously
1506
     *                                 retrieved through {@link getComponent()}, {@link getComponents()} or
1507
     *                                 {@link getManyManyComponents()} (Default: false)
1508
     * @return int The ID of the record
1509
     * @throws ValidationException Exception that can be caught and handled by the calling function
1510
     */
1511
    public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false)
1512
    {
1513
        $now = DBDatetime::now()->Rfc2822();
1514
1515
        // Execute pre-write tasks
1516
        $this->preWrite();
1517
1518
        // Check if we are doing an update or an insert
1519
        $isNewRecord = !$this->isInDB() || $forceInsert;
1520
1521
        // Check changes exist, abort if there are none
1522
        $hasChanges = $this->updateChanges($isNewRecord);
1523
        if ($hasChanges || $forceWrite || $isNewRecord) {
1524
            // Ensure Created and LastEdited are populated
1525
            if (!isset($this->record['Created'])) {
1526
                $this->record['Created'] = $now;
1527
            }
1528
            $this->record['LastEdited'] = $now;
1529
1530
            // New records have their insert into the base data table done first, so that they can pass the
1531
            // generated primary key on to the rest of the manipulation
1532
            $baseTable = $this->baseTable();
1533
            $this->writeBaseRecord($baseTable, $now);
1534
1535
            // Write the DB manipulation for all changed fields
1536
            $this->writeManipulation($baseTable, $now, $isNewRecord);
1537
1538
            // If there's any relations that couldn't be saved before, save them now (we have an ID here)
1539
            $this->writeRelations();
1540
            $this->onAfterWrite();
1541
            $this->changed = array();
1542
        } else {
1543
            if ($showDebug) {
1544
                Debug::message("no changes for DataObject");
1545
            }
1546
1547
            // Used by DODs to clean up after themselves, eg, Versioned
1548
            $this->invokeWithExtensions('onAfterSkippedWrite');
1549
        }
1550
1551
        // Write relations as necessary
1552
        if ($writeComponents) {
1553
            $this->writeComponents(true);
1554
        }
1555
1556
        // Clears the cache for this object so get_one returns the correct object.
1557
        $this->flushCache();
1558
1559
        return $this->record['ID'];
1560
    }
1561
1562
    /**
1563
     * Writes cached relation lists to the database, if possible
1564
     */
1565
    public function writeRelations()
1566
    {
1567
        if (!$this->isInDB()) {
1568
            return;
1569
        }
1570
1571
        // If there's any relations that couldn't be saved before, save them now (we have an ID here)
1572
        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...
1573
            foreach ($this->unsavedRelations as $name => $list) {
1574
                $list->changeToList($this->$name());
1575
            }
1576
            $this->unsavedRelations = array();
1577
        }
1578
    }
1579
1580
    /**
1581
     * Write the cached components to the database. Cached components could refer to two different instances of the
1582
     * same record.
1583
     *
1584
     * @param bool $recursive Recursively write components
1585
     * @return DataObject $this
1586
     */
1587
    public function writeComponents($recursive = false)
1588
    {
1589
        foreach ($this->components as $component) {
1590
            $component->write(false, false, false, $recursive);
1591
        }
1592
1593
        if ($join = $this->getJoin()) {
1594
            $join->write(false, false, false, $recursive);
1595
        }
1596
1597
        return $this;
1598
    }
1599
1600
    /**
1601
     * Delete this data object.
1602
     * $this->onBeforeDelete() gets called.
1603
     * Note that in Versioned objects, both Stage and Live will be deleted.
1604
     * @uses DataExtension->augmentSQL()
1605
     */
1606
    public function delete()
1607
    {
1608
        $this->brokenOnDelete = true;
1609
        $this->onBeforeDelete();
1610
        if ($this->brokenOnDelete) {
1611
            user_error(static::class . " has a broken onBeforeDelete() function."
1612
                . " Make sure that you call parent::onBeforeDelete().", E_USER_ERROR);
1613
        }
1614
1615
        // Deleting a record without an ID shouldn't do anything
1616
        if (!$this->ID) {
1617
            throw new LogicException("DataObject::delete() called on a DataObject without an ID");
1618
        }
1619
1620
        // TODO: This is quite ugly.  To improve:
1621
        //  - move the details of the delete code in the DataQuery system
1622
        //  - update the code to just delete the base table, and rely on cascading deletes in the DB to do the rest
1623
        //    obviously, that means getting requireTable() to configure cascading deletes ;-)
1624
        $srcQuery = DataList::create(static::class)
1625
            ->filter('ID', $this->ID)
1626
            ->dataQuery()
1627
            ->query();
1628
        $queriedTables = $srcQuery->queriedTables();
1629
        $this->extend('updateDeleteTables', $queriedTables, $srcQuery);
1630
        foreach ($queriedTables as $table) {
1631
            $delete = SQLDelete::create("\"$table\"", array('"ID"' => $this->ID));
1632
            $this->extend('updateDeleteTable', $delete, $table, $queriedTables, $srcQuery);
1633
            $delete->execute();
1634
        }
1635
        // Remove this item out of any caches
1636
        $this->flushCache();
1637
1638
        $this->onAfterDelete();
1639
1640
        $this->OldID = $this->ID;
1641
        $this->ID = 0;
1642
    }
1643
1644
    /**
1645
     * Delete the record with the given ID.
1646
     *
1647
     * @param string $className The class name of the record to be deleted
1648
     * @param int $id ID of record to be deleted
1649
     */
1650
    public static function delete_by_id($className, $id)
1651
    {
1652
        $obj = DataObject::get_by_id($className, $id);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1653
        if ($obj) {
0 ignored issues
show
introduced by
$obj is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
1654
            $obj->delete();
1655
        } else {
1656
            user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
1657
        }
1658
    }
1659
1660
    /**
1661
     * Get the class ancestry, including the current class name.
1662
     * The ancestry will be returned as an array of class names, where the 0th element
1663
     * will be the class that inherits directly from DataObject, and the last element
1664
     * will be the current class.
1665
     *
1666
     * @return array Class ancestry
1667
     */
1668
    public function getClassAncestry()
1669
    {
1670
        return ClassInfo::ancestry(static::class);
1671
    }
1672
1673
    /**
1674
     * Return a unary component object from a one to one relationship, as a DataObject.
1675
     * If no component is available, an 'empty component' will be returned for
1676
     * non-polymorphic relations, or for polymorphic relations with a class set.
1677
     *
1678
     * @param string $componentName Name of the component
1679
     * @return DataObject The component object. It's exact type will be that of the component.
1680
     * @throws Exception
1681
     */
1682
    public function getComponent($componentName)
1683
    {
1684
        if (isset($this->components[$componentName])) {
1685
            return $this->components[$componentName];
1686
        }
1687
1688
        $schema = static::getSchema();
1689
        if ($class = $schema->hasOneComponent(static::class, $componentName)) {
1690
            $joinField = $componentName . 'ID';
1691
            $joinID = $this->getField($joinField);
1692
1693
            // Extract class name for polymorphic relations
1694
            if ($class === self::class) {
1695
                $class = $this->getField($componentName . 'Class');
1696
                if (empty($class)) {
1697
                    return null;
1698
                }
1699
            }
1700
1701
            if ($joinID) {
1702
                // Ensure that the selected object originates from the same stage, subsite, etc
1703
                $component = DataObject::get($class)
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1704
                    ->filter('ID', $joinID)
1705
                    ->setDataQueryParam($this->getInheritableQueryParams())
1706
                    ->first();
1707
            }
1708
1709
            if (empty($component)) {
1710
                $component = Injector::inst()->create($class);
1711
            }
1712
        } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
1713
            $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
1714
            $joinID = $this->ID;
1715
1716
            if ($joinID) {
1717
                // Prepare filter for appropriate join type
1718
                if ($polymorphic) {
1719
                    $filter = array(
1720
                        "{$joinField}ID" => $joinID,
1721
                        "{$joinField}Class" => static::class,
1722
                    );
1723
                } else {
1724
                    $filter = array(
1725
                        $joinField => $joinID
1726
                    );
1727
                }
1728
1729
                // Ensure that the selected object originates from the same stage, subsite, etc
1730
                $component = DataObject::get($class)
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1731
                    ->filter($filter)
1732
                    ->setDataQueryParam($this->getInheritableQueryParams())
1733
                    ->first();
1734
            }
1735
1736
            if (empty($component)) {
1737
                $component = Injector::inst()->create($class);
1738
                if ($polymorphic) {
1739
                    $component->{$joinField . 'ID'} = $this->ID;
1740
                    $component->{$joinField . 'Class'} = static::class;
1741
                } else {
1742
                    $component->$joinField = $this->ID;
1743
                }
1744
            }
1745
        } else {
1746
            throw new InvalidArgumentException(
1747
                "DataObject->getComponent(): Could not find component '$componentName'."
1748
            );
1749
        }
1750
1751
        $this->components[$componentName] = $component;
1752
        return $component;
1753
    }
1754
1755
    /**
1756
     * Assign an item to the given component
1757
     *
1758
     * @param string $componentName
1759
     * @param DataObject|null $item
1760
     * @return $this
1761
     */
1762
    public function setComponent($componentName, $item)
1763
    {
1764
        // Validate component
1765
        $schema = static::getSchema();
1766
        if ($class = $schema->hasOneComponent(static::class, $componentName)) {
1767
            // Force item to be written if not by this point
1768
            // @todo This could be lazy-written in a beforeWrite hook, but force write here for simplicity
1769
            // https://github.com/silverstripe/silverstripe-framework/issues/7818
1770
            if ($item && !$item->isInDB()) {
1771
                $item->write();
1772
            }
1773
1774
            // Update local ID
1775
            $joinField = $componentName . 'ID';
1776
            $this->setField($joinField, $item ? $item->ID : null);
1777
            // Update Class (Polymorphic has_one)
1778
            // Extract class name for polymorphic relations
1779
            if ($class === self::class) {
1780
                $this->setField($componentName . 'Class', $item ? get_class($item) : null);
1781
            }
1782
        } 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...
1783
            if ($item) {
1784
                // For belongs_to, add to has_one on other component
1785
                $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
1786
                if (!$polymorphic) {
1787
                    $joinField = substr($joinField, 0, -2);
1788
                }
1789
                $item->setComponent($joinField, $this);
1790
            }
1791
        } else {
1792
            throw new InvalidArgumentException(
1793
                "DataObject->setComponent(): Could not find component '$componentName'."
1794
            );
1795
        }
1796
1797
        $this->components[$componentName] = $item;
1798
        return $this;
1799
    }
1800
1801
    /**
1802
     * Returns a one-to-many relation as a HasManyList
1803
     *
1804
     * @param string $componentName Name of the component
1805
     * @param int|array $id Optional ID(s) for parent of this relation, if not the current record
1806
     * @return HasManyList|UnsavedRelationList The components of the one-to-many relationship.
1807
     */
1808
    public function getComponents($componentName, $id = null)
1809
    {
1810
        if (!isset($id)) {
1811
            $id = $this->ID;
1812
        }
1813
        $result = null;
1814
1815
        $schema = $this->getSchema();
1816
        $componentClass = $schema->hasManyComponent(static::class, $componentName);
1817
        if (!$componentClass) {
1818
            throw new InvalidArgumentException(sprintf(
1819
                "DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
1820
                $componentName,
1821
                static::class
1822
            ));
1823
        }
1824
1825
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
1826
        if (!$id) {
1827
            if (!isset($this->unsavedRelations[$componentName])) {
1828
                $this->unsavedRelations[$componentName] =
1829
                    new UnsavedRelationList(static::class, $componentName, $componentClass);
1830
            }
1831
            return $this->unsavedRelations[$componentName];
1832
        }
1833
1834
        // Determine type and nature of foreign relation
1835
        $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'has_many', $polymorphic);
1836
        /** @var HasManyList $result */
1837
        if ($polymorphic) {
1838
            $result = PolymorphicHasManyList::create($componentClass, $joinField, static::class);
1839
        } else {
1840
            $result = HasManyList::create($componentClass, $joinField);
1841
        }
1842
1843
        return $result
1844
            ->setDataQueryParam($this->getInheritableQueryParams())
1845
            ->forForeignID($id);
1846
    }
1847
1848
    /**
1849
     * Find the foreign class of a relation on this DataObject, regardless of the relation type.
1850
     *
1851
     * @param string $relationName Relation name.
1852
     * @return string Class name, or null if not found.
1853
     */
1854
    public function getRelationClass($relationName)
1855
    {
1856
        // Parse many_many
1857
        $manyManyComponent = $this->getSchema()->manyManyComponent(static::class, $relationName);
1858
        if ($manyManyComponent) {
1859
            return $manyManyComponent['childClass'];
1860
        }
1861
1862
        // Go through all relationship configuration fields.
1863
        $config = $this->config();
1864
        $candidates = array_merge(
1865
            ($relations = $config->get('has_one')) ? $relations : array(),
1866
            ($relations = $config->get('has_many')) ? $relations : array(),
1867
            ($relations = $config->get('belongs_to')) ? $relations : array()
1868
        );
1869
1870
        if (isset($candidates[$relationName])) {
1871
            $remoteClass = $candidates[$relationName];
1872
1873
            // If dot notation is present, extract just the first part that contains the class.
1874
            if (($fieldPos = strpos($remoteClass, '.')) !== false) {
1875
                return substr($remoteClass, 0, $fieldPos);
1876
            }
1877
1878
            // Otherwise just return the class
1879
            return $remoteClass;
1880
        }
1881
1882
        return null;
1883
    }
1884
1885
    /**
1886
     * Given a relation name, determine the relation type
1887
     *
1888
     * @param string $component Name of component
1889
     * @return string has_one, has_many, many_many, belongs_many_many or belongs_to
1890
     */
1891
    public function getRelationType($component)
1892
    {
1893
        $types = array('has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to');
1894
        $config = $this->config();
1895
        foreach ($types as $type) {
1896
            $relations = $config->get($type);
1897
            if ($relations && isset($relations[$component])) {
1898
                return $type;
1899
            }
1900
        }
1901
        return null;
1902
    }
1903
1904
    /**
1905
     * Given a relation declared on a remote class, generate a substitute component for the opposite
1906
     * side of the relation.
1907
     *
1908
     * Notes on behaviour:
1909
     *  - This can still be used on components that are defined on both sides, but do not need to be.
1910
     *  - All has_ones on remote class will be treated as local has_many, even if they are belongs_to
1911
     *  - Polymorphic relationships do not have two natural endpoints (only on one side)
1912
     *   and thus attempting to infer them will return nothing.
1913
     *  - Cannot be used on unsaved objects.
1914
     *
1915
     * @param string $remoteClass
1916
     * @param string $remoteRelation
1917
     * @return DataList|DataObject The component, either as a list or single object
1918
     * @throws BadMethodCallException
1919
     * @throws InvalidArgumentException
1920
     */
1921
    public function inferReciprocalComponent($remoteClass, $remoteRelation)
1922
    {
1923
        $remote = DataObject::singleton($remoteClass);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1924
        $class = $remote->getRelationClass($remoteRelation);
1925
        $schema = static::getSchema();
1926
1927
        // Validate arguments
1928
        if (!$this->isInDB()) {
1929
            throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects");
1930
        }
1931
        if (empty($class)) {
1932
            throw new InvalidArgumentException(sprintf(
1933
                "%s invoked with invalid relation %s.%s",
1934
                __METHOD__,
1935
                $remoteClass,
1936
                $remoteRelation
1937
            ));
1938
        }
1939
        // If relation is polymorphic, do not infer recriprocal relationship
1940
        if ($class === self::class) {
1941
            return null;
1942
        }
1943
        if (!is_a($this, $class, true)) {
1944
            throw new InvalidArgumentException(sprintf(
1945
                "Relation %s on %s does not refer to objects of type %s",
1946
                $remoteRelation,
1947
                $remoteClass,
1948
                static::class
1949
            ));
1950
        }
1951
1952
        // Check the relation type to mock
1953
        $relationType = $remote->getRelationType($remoteRelation);
1954
        switch ($relationType) {
1955
            case 'has_one': {
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
1956
                // Mock has_many
1957
                $joinField = "{$remoteRelation}ID";
1958
                $componentClass = $schema->classForField($remoteClass, $joinField);
1959
                $result = HasManyList::create($componentClass, $joinField);
1960
                return $result
1961
                    ->setDataQueryParam($this->getInheritableQueryParams())
1962
                    ->forForeignID($this->ID);
1963
            }
1964
            case 'belongs_to':
1965
            case 'has_many': {
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
1966
                // These relations must have a has_one on the other end, so find it
1967
                $joinField = $schema->getRemoteJoinField(
1968
                    $remoteClass,
1969
                    $remoteRelation,
1970
                    $relationType,
1971
                    $polymorphic
1972
                );
1973
                // If relation is polymorphic, do not infer recriprocal relationship automatically
1974
                if ($polymorphic) {
1975
                    return null;
1976
                }
1977
                $joinID = $this->getField($joinField);
1978
                if (empty($joinID)) {
1979
                    return null;
1980
                }
1981
                // Get object by joined ID
1982
                return DataObject::get($remoteClass)
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
1983
                    ->filter('ID', $joinID)
1984
                    ->setDataQueryParam($this->getInheritableQueryParams())
1985
                    ->first();
1986
            }
1987
            case 'many_many':
1988
            case 'belongs_many_many': {
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
1989
                // Get components and extra fields from parent
1990
                $manyMany = $remote->getSchema()->manyManyComponent($remoteClass, $remoteRelation);
1991
                $extraFields = $schema->manyManyExtraFieldsForComponent($remoteClass, $remoteRelation) ?: array();
1992
1993
                // Reverse parent and component fields and create an inverse ManyManyList
1994
                /** @var RelationList $result */
1995
                $result = Injector::inst()->create(
1996
                    $manyMany['relationClass'],
1997
                    $manyMany['parentClass'], // Substitute parent class for dataClass
1998
                    $manyMany['join'],
1999
                    $manyMany['parentField'], // Reversed parent / child field
2000
                    $manyMany['childField'], // Reversed parent / child field
2001
                    $extraFields,
2002
                    $manyMany['childClass'], // substitute child class for parentClass
2003
                    $remoteClass // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
2004
                );
2005
                $this->extend('updateManyManyComponents', $result);
2006
2007
                // If this is called on a singleton, then we return an 'orphaned relation' that can have the
2008
                // foreignID set elsewhere.
2009
                return $result
2010
                    ->setDataQueryParam($this->getInheritableQueryParams())
2011
                    ->forForeignID($this->ID);
2012
            }
2013
            default: {
0 ignored issues
show
Coding Style introduced by
DEFAULT statements must be defined using a colon

As per the PSR-2 coding standard, default statements should not be wrapped in curly braces.

switch ($expr) {
    default: { //wrong
        doSomething();
        break;
    }
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2014
                return null;
2015
            }
2016
        }
2017
    }
2018
2019
    /**
2020
     * Returns a many-to-many component, as a ManyManyList.
2021
     * @param string $componentName Name of the many-many component
2022
     * @param int|array $id Optional ID for parent of this relation, if not the current record
2023
     * @return ManyManyList|UnsavedRelationList The set of components
2024
     */
2025
    public function getManyManyComponents($componentName, $id = null)
2026
    {
2027
        if (!isset($id)) {
2028
            $id = $this->ID;
2029
        }
2030
        $schema = static::getSchema();
2031
        $manyManyComponent = $schema->manyManyComponent(static::class, $componentName);
2032
        if (!$manyManyComponent) {
2033
            throw new InvalidArgumentException(sprintf(
2034
                "DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'",
2035
                $componentName,
2036
                static::class
2037
            ));
2038
        }
2039
2040
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
2041
        if (!$id) {
2042
            if (!isset($this->unsavedRelations[$componentName])) {
2043
                $this->unsavedRelations[$componentName] =
2044
                    new UnsavedRelationList(
2045
                        $manyManyComponent['parentClass'],
2046
                        $componentName,
2047
                        $manyManyComponent['childClass']
2048
                    );
2049
            }
2050
            return $this->unsavedRelations[$componentName];
2051
        }
2052
2053
        $extraFields = $schema->manyManyExtraFieldsForComponent(static::class, $componentName) ?: array();
2054
        /** @var RelationList $result */
2055
        $result = Injector::inst()->create(
2056
            $manyManyComponent['relationClass'],
2057
            $manyManyComponent['childClass'],
2058
            $manyManyComponent['join'],
2059
            $manyManyComponent['childField'],
2060
            $manyManyComponent['parentField'],
2061
            $extraFields,
2062
            $manyManyComponent['parentClass'],
2063
            static::class // In case ManyManyThroughList needs to use PolymorphicHasManyList internally
2064
        );
2065
2066
        // Store component data in query meta-data
2067
        $result = $result->alterDataQuery(function ($query) use ($extraFields) {
2068
            /** @var DataQuery $query */
2069
            $query->setQueryParam('Component.ExtraFields', $extraFields);
2070
        });
2071
2072
        $this->extend('updateManyManyComponents', $result);
2073
2074
        // If this is called on a singleton, then we return an 'orphaned relation' that can have the
2075
        // foreignID set elsewhere.
2076
        return $result
2077
            ->setDataQueryParam($this->getInheritableQueryParams())
2078
            ->forForeignID($id);
2079
    }
2080
2081
    /**
2082
     * Return the class of a one-to-one component.  If $component is null, return all of the one-to-one components and
2083
     * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.
2084
     *
2085
     * @return string|array The class of the one-to-one component, or an array of all one-to-one components and
2086
     *                          their classes.
2087
     */
2088
    public function hasOne()
2089
    {
2090
        return (array)$this->config()->get('has_one');
2091
    }
2092
2093
    /**
2094
     * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
2095
     * their class name will be returned.
2096
     *
2097
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2098
     *        the field data stripped off. It defaults to TRUE.
2099
     * @return string|array
2100
     */
2101
    public function belongsTo($classOnly = true)
2102
    {
2103
        $belongsTo = (array)$this->config()->get('belongs_to');
2104
        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...
2105
            return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
2106
        } else {
2107
            return $belongsTo ? $belongsTo : array();
2108
        }
2109
    }
2110
2111
    /**
2112
     * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
2113
     * relationships and their classes will be returned.
2114
     *
2115
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2116
     *        the field data stripped off. It defaults to TRUE.
2117
     * @return string|array|false
2118
     */
2119
    public function hasMany($classOnly = true)
2120
    {
2121
        $hasMany = (array)$this->config()->get('has_many');
2122
        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...
2123
            return preg_replace('/(.+)?\..+/', '$1', $hasMany);
2124
        } else {
2125
            return $hasMany ? $hasMany : array();
2126
        }
2127
    }
2128
2129
    /**
2130
     * Return the many-to-many extra fields specification.
2131
     *
2132
     * If you don't specify a component name, it returns all
2133
     * extra fields for all components available.
2134
     *
2135
     * @return array|null
2136
     */
2137
    public function manyManyExtraFields()
2138
    {
2139
        return $this->config()->get('many_many_extraFields');
2140
    }
2141
2142
    /**
2143
     * Return information about a many-to-many component.
2144
     * The return value is an array of (parentclass, childclass).  If $component is null, then all many-many
2145
     * components are returned.
2146
     *
2147
     * @see DataObjectSchema::manyManyComponent()
2148
     * @return array|null An array of (parentclass, childclass), or an array of all many-many components
2149
     */
2150
    public function manyMany()
2151
    {
2152
        $config = $this->config();
2153
        $manyManys = (array)$config->get('many_many');
2154
        $belongsManyManys = (array)$config->get('belongs_many_many');
2155
        $items = array_merge($manyManys, $belongsManyManys);
2156
        return $items;
2157
    }
2158
2159
    /**
2160
     * This returns an array (if it exists) describing the database extensions that are required, or false if none
2161
     *
2162
     * This is experimental, and is currently only a Postgres-specific enhancement.
2163
     *
2164
     * @param string $class
2165
     * @return array|false
2166
     */
2167
    public function database_extensions($class)
2168
    {
2169
        $extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
2170
        if ($extensions) {
2171
            return $extensions;
2172
        } else {
2173
            return false;
2174
        }
2175
    }
2176
2177
    /**
2178
     * Generates a SearchContext to be used for building and processing
2179
     * a generic search form for properties on this object.
2180
     *
2181
     * @return SearchContext
2182
     */
2183
    public function getDefaultSearchContext()
2184
    {
2185
        return new SearchContext(
2186
            static::class,
2187
            $this->scaffoldSearchFields(),
2188
            $this->defaultSearchFilters()
2189
        );
2190
    }
2191
2192
    /**
2193
     * Determine which properties on the DataObject are
2194
     * searchable, and map them to their default {@link FormField}
2195
     * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
2196
     *
2197
     * Some additional logic is included for switching field labels, based on
2198
     * how generic or specific the field type is.
2199
     *
2200
     * Used by {@link SearchContext}.
2201
     *
2202
     * @param array $_params
2203
     *   'fieldClasses': Associative array of field names as keys and FormField classes as values
2204
     *   'restrictFields': Numeric array of a field name whitelist
2205
     * @return FieldList
2206
     */
2207
    public function scaffoldSearchFields($_params = null)
2208
    {
2209
        $params = array_merge(
2210
            array(
2211
                'fieldClasses' => false,
2212
                'restrictFields' => false
2213
            ),
2214
            (array)$_params
2215
        );
2216
        $fields = new FieldList();
2217
        foreach ($this->searchableFields() as $fieldName => $spec) {
2218
            if ($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) {
2219
                continue;
2220
            }
2221
2222
            // If a custom fieldclass is provided as a string, use it
2223
            $field = null;
2224
            if ($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
2225
                $fieldClass = $params['fieldClasses'][$fieldName];
2226
                $field = new $fieldClass($fieldName);
2227
            // If we explicitly set a field, then construct that
2228
            } elseif (isset($spec['field'])) {
2229
                // If it's a string, use it as a class name and construct
2230
                if (is_string($spec['field'])) {
2231
                    $fieldClass = $spec['field'];
2232
                    $field = new $fieldClass($fieldName);
2233
2234
                // If it's a FormField object, then just use that object directly.
2235
                } elseif ($spec['field'] instanceof FormField) {
2236
                    $field = $spec['field'];
2237
2238
                // Otherwise we have a bug
2239
                } else {
2240
                    user_error("Bad value for searchable_fields, 'field' value: "
2241
                        . var_export($spec['field'], true), E_USER_WARNING);
2242
                }
2243
2244
            // Otherwise, use the database field's scaffolder
2245
            } elseif ($object = $this->relObject($fieldName)) {
2246
                $field = $object->scaffoldSearchField();
2247
            }
2248
2249
            // Allow fields to opt out of search
2250
            if (!$field) {
2251
                continue;
2252
            }
2253
2254
            if (strstr($fieldName, '.')) {
2255
                $field->setName(str_replace('.', '__', $fieldName));
2256
            }
2257
            $field->setTitle($spec['title']);
2258
2259
            $fields->push($field);
2260
        }
2261
        return $fields;
2262
    }
2263
2264
    /**
2265
     * Scaffold a simple edit form for all properties on this dataobject,
2266
     * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
2267
     * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
2268
     *
2269
     * @uses FormScaffolder
2270
     *
2271
     * @param array $_params Associative array passing through properties to {@link FormScaffolder}.
2272
     * @return FieldList
2273
     */
2274
    public function scaffoldFormFields($_params = null)
2275
    {
2276
        $params = array_merge(
2277
            array(
2278
                'tabbed' => false,
2279
                'includeRelations' => false,
2280
                'restrictFields' => false,
2281
                'fieldClasses' => false,
2282
                'ajaxSafe' => false
2283
            ),
2284
            (array)$_params
2285
        );
2286
2287
        $fs = FormScaffolder::create($this);
2288
        $fs->tabbed = $params['tabbed'];
2289
        $fs->includeRelations = $params['includeRelations'];
2290
        $fs->restrictFields = $params['restrictFields'];
2291
        $fs->fieldClasses = $params['fieldClasses'];
2292
        $fs->ajaxSafe = $params['ajaxSafe'];
2293
2294
        return $fs->getFieldList();
2295
    }
2296
2297
    /**
2298
     * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
2299
     * being called on extensions
2300
     *
2301
     * @param callable $callback The callback to execute
2302
     */
2303
    protected function beforeUpdateCMSFields($callback)
2304
    {
2305
        $this->beforeExtending('updateCMSFields', $callback);
2306
    }
2307
2308
    /**
2309
     * Centerpiece of every data administration interface in Silverstripe,
2310
     * which returns a {@link FieldList} suitable for a {@link Form} object.
2311
     * If not overloaded, we're using {@link scaffoldFormFields()} to automatically
2312
     * generate this set. To customize, overload this method in a subclass
2313
     * or extended onto it by using {@link DataExtension->updateCMSFields()}.
2314
     *
2315
     * <code>
2316
     * class MyCustomClass extends DataObject {
2317
     *  static $db = array('CustomProperty'=>'Boolean');
2318
     *
2319
     *  function getCMSFields() {
2320
     *    $fields = parent::getCMSFields();
2321
     *    $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
2322
     *    return $fields;
2323
     *  }
2324
     * }
2325
     * </code>
2326
     *
2327
     * @see Good example of complex FormField building: SiteTree::getCMSFields()
2328
     *
2329
     * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.
2330
     */
2331
    public function getCMSFields()
2332
    {
2333
        $tabbedFields = $this->scaffoldFormFields(array(
2334
            // Don't allow has_many/many_many relationship editing before the record is first saved
2335
            'includeRelations' => ($this->ID > 0),
2336
            'tabbed' => true,
2337
            'ajaxSafe' => true
2338
        ));
2339
2340
        $this->extend('updateCMSFields', $tabbedFields);
2341
2342
        return $tabbedFields;
2343
    }
2344
2345
    /**
2346
     * need to be overload by solid dataobject, so that the customised actions of that dataobject,
2347
     * including that dataobject's extensions customised actions could be added to the EditForm.
2348
     *
2349
     * @return FieldList an Empty FieldList(); need to be overload by solid subclass
2350
     */
2351
    public function getCMSActions()
2352
    {
2353
        $actions = new FieldList();
2354
        $this->extend('updateCMSActions', $actions);
2355
        return $actions;
2356
    }
2357
2358
2359
    /**
2360
     * Used for simple frontend forms without relation editing
2361
     * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()}
2362
     * by default. To customize, either overload this method in your
2363
     * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.
2364
     *
2365
     * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API
2366
     *
2367
     * @param array $params See {@link scaffoldFormFields()}
2368
     * @return FieldList Always returns a simple field collection without TabSet.
2369
     */
2370
    public function getFrontEndFields($params = null)
2371
    {
2372
        $untabbedFields = $this->scaffoldFormFields($params);
2373
        $this->extend('updateFrontEndFields', $untabbedFields);
2374
2375
        return $untabbedFields;
2376
    }
2377
2378
    public function getViewerTemplates($suffix = '')
2379
    {
2380
        return SSViewer::get_templates_by_class(static::class, $suffix, $this->baseClass());
2381
    }
2382
2383
    /**
2384
     * Gets the value of a field.
2385
     * Called by {@link __get()} and any getFieldName() methods you might create.
2386
     *
2387
     * @param string $field The name of the field
2388
     * @return mixed The field value
2389
     */
2390
    public function getField($field)
2391
    {
2392
        // If we already have a value in $this->record, then we should just return that
2393
        if (isset($this->record[$field])) {
2394
            return $this->record[$field];
2395
        }
2396
2397
        // Do we have a field that needs to be lazy loaded?
2398
        if (isset($this->record[$field . '_Lazy'])) {
2399
            $tableClass = $this->record[$field . '_Lazy'];
2400
            $this->loadLazyFields($tableClass);
2401
        }
2402
        $schema = static::getSchema();
2403
2404
        // Support unary relations as fields
2405
        if ($schema->unaryComponent(static::class, $field)) {
2406
            return $this->getComponent($field);
2407
        }
2408
2409
        // In case of complex fields, return the DBField object
2410
        if ($schema->compositeField(static::class, $field)) {
2411
            $this->record[$field] = $this->dbObject($field);
2412
        }
2413
2414
        return isset($this->record[$field]) ? $this->record[$field] : null;
2415
    }
2416
2417
    /**
2418
     * Loads all the stub fields that an initial lazy load didn't load fully.
2419
     *
2420
     * @param string $class Class to load the values from. Others are joined as required.
2421
     * Not specifying a tableClass will load all lazy fields from all tables.
2422
     * @return bool Flag if lazy loading succeeded
2423
     */
2424
    protected function loadLazyFields($class = null)
2425
    {
2426
        if (!$this->isInDB() || !is_numeric($this->ID)) {
2427
            return false;
2428
        }
2429
2430
        if (!$class) {
2431
            $loaded = array();
2432
2433
            foreach ($this->record as $key => $value) {
2434
                if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
2435
                    $this->loadLazyFields($value);
2436
                    $loaded[$value] = $value;
2437
                }
2438
            }
2439
2440
            return false;
2441
        }
2442
2443
        $dataQuery = new DataQuery($class);
2444
2445
        // Reset query parameter context to that of this DataObject
2446
        if ($params = $this->getSourceQueryParams()) {
2447
            foreach ($params as $key => $value) {
2448
                $dataQuery->setQueryParam($key, $value);
2449
            }
2450
        }
2451
2452
        // Limit query to the current record, unless it has the Versioned extension,
2453
        // in which case it requires special handling through augmentLoadLazyFields()
2454
        $schema = static::getSchema();
2455
        $baseIDColumn = $schema->sqlColumnForField($this, 'ID');
2456
        $dataQuery->where([
2457
            $baseIDColumn => $this->record['ID']
2458
        ])->limit(1);
2459
2460
        $columns = array();
2461
2462
        // Add SQL for fields, both simple & multi-value
2463
        // TODO: This is copy & pasted from buildSQL(), it could be moved into a method
2464
        $databaseFields = $schema->databaseFields($class, false);
2465
        foreach ($databaseFields as $k => $v) {
2466
            if (!isset($this->record[$k]) || $this->record[$k] === null) {
2467
                $columns[] = $k;
2468
            }
2469
        }
2470
2471
        if ($columns) {
2472
            $query = $dataQuery->query();
2473
            $this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
2474
            $this->extend('augmentSQL', $query, $dataQuery);
2475
2476
            $dataQuery->setQueriedColumns($columns);
2477
            $newData = $dataQuery->execute()->record();
2478
2479
            // Load the data into record
2480
            if ($newData) {
2481
                foreach ($newData as $k => $v) {
2482
                    if (in_array($k, $columns)) {
2483
                        $this->record[$k] = $v;
2484
                        $this->original[$k] = $v;
2485
                        unset($this->record[$k . '_Lazy']);
2486
                    }
2487
                }
2488
2489
            // No data means that the query returned nothing; assign 'null' to all the requested fields
2490
            } else {
2491
                foreach ($columns as $k) {
2492
                    $this->record[$k] = null;
2493
                    $this->original[$k] = null;
2494
                    unset($this->record[$k . '_Lazy']);
2495
                }
2496
            }
2497
        }
2498
        return true;
2499
    }
2500
2501
    /**
2502
     * Return the fields that have changed.
2503
     *
2504
     * The change level affects what the functions defines as "changed":
2505
     * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
2506
     * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
2507
     *   for example a change from 0 to null would not be included.
2508
     *
2509
     * Example return:
2510
     * <code>
2511
     * array(
2512
     *   'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
2513
     * )
2514
     * </code>
2515
     *
2516
     * @param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true
2517
     * to return all database fields, or an array for an explicit filter. false returns all fields.
2518
     * @param int $changeLevel The strictness of what is defined as change. Defaults to strict
2519
     * @return array
2520
     */
2521
    public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT)
2522
    {
2523
        $changedFields = array();
2524
2525
        // Update the changed array with references to changed obj-fields
2526
        foreach ($this->record as $k => $v) {
2527
            // Prevents DBComposite infinite looping on isChanged
2528
            if (is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
2529
                continue;
2530
            }
2531
            if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
2532
                $this->changed[$k] = self::CHANGE_VALUE;
2533
            }
2534
        }
2535
2536
        if (is_array($databaseFieldsOnly)) {
2537
            $fields = array_intersect_key((array)$this->changed, array_flip($databaseFieldsOnly));
2538
        } elseif ($databaseFieldsOnly) {
2539
            $fieldsSpecs = static::getSchema()->fieldSpecs(static::class);
2540
            $fields = array_intersect_key((array)$this->changed, $fieldsSpecs);
2541
        } else {
2542
            $fields = $this->changed;
2543
        }
2544
2545
        // Filter the list to those of a certain change level
2546
        if ($changeLevel > self::CHANGE_STRICT) {
2547
            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...
2548
                foreach ($fields as $name => $level) {
2549
                    if ($level < $changeLevel) {
2550
                        unset($fields[$name]);
2551
                    }
2552
                }
2553
            }
2554
        }
2555
2556
        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...
2557
            foreach ($fields as $name => $level) {
2558
                $changedFields[$name] = array(
2559
                    'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
2560
                    'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
2561
                    'level' => $level
2562
                );
2563
            }
2564
        }
2565
2566
        return $changedFields;
2567
    }
2568
2569
    /**
2570
     * Uses {@link getChangedFields()} to determine if fields have been changed
2571
     * since loading them from the database.
2572
     *
2573
     * @param string $fieldName Name of the database field to check, will check for any if not given
2574
     * @param int $changeLevel See {@link getChangedFields()}
2575
     * @return boolean
2576
     */
2577
    public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT)
2578
    {
2579
        $fields = $fieldName ? array($fieldName) : true;
2580
        $changed = $this->getChangedFields($fields, $changeLevel);
2581
        if (!isset($fieldName)) {
2582
            return !empty($changed);
2583
        } else {
2584
            return array_key_exists($fieldName, $changed);
2585
        }
2586
    }
2587
2588
    /**
2589
     * Set the value of the field
2590
     * Called by {@link __set()} and any setFieldName() methods you might create.
2591
     *
2592
     * @param string $fieldName Name of the field
2593
     * @param mixed $val New field value
2594
     * @return $this
2595
     */
2596
    public function setField($fieldName, $val)
2597
    {
2598
        $this->objCacheClear();
2599
        //if it's a has_one component, destroy the cache
2600
        if (substr($fieldName, -2) == 'ID') {
2601
            unset($this->components[substr($fieldName, 0, -2)]);
2602
        }
2603
2604
        // If we've just lazy-loaded the column, then we need to populate the $original array
2605
        if (isset($this->record[$fieldName . '_Lazy'])) {
2606
            $tableClass = $this->record[$fieldName . '_Lazy'];
2607
            $this->loadLazyFields($tableClass);
2608
        }
2609
2610
        // Support component assignent via field setter
2611
        $schema = static::getSchema();
2612
        if ($schema->unaryComponent(static::class, $fieldName)) {
2613
            unset($this->components[$fieldName]);
2614
            // Assign component directly
2615
            if (is_null($val) || $val instanceof DataObject) {
2616
                return $this->setComponent($fieldName, $val);
2617
            }
2618
            // Assign by ID instead of object
2619
            if (is_numeric($val)) {
2620
                $fieldName .= 'ID';
2621
            }
2622
        }
2623
2624
        // Situation 1: Passing an DBField
2625
        if ($val instanceof DBField) {
2626
            $val->setName($fieldName);
2627
            $val->saveInto($this);
2628
2629
            // Situation 1a: Composite fields should remain bound in case they are
2630
            // later referenced to update the parent dataobject
2631
            if ($val instanceof DBComposite) {
2632
                $val->bindTo($this);
2633
                $this->record[$fieldName] = $val;
2634
            }
2635
        // Situation 2: Passing a literal or non-DBField object
2636
        } else {
2637
            // If this is a proper database field, we shouldn't be getting non-DBField objects
2638
            if (is_object($val) && $schema->fieldSpec(static::class, $fieldName)) {
2639
                throw new InvalidArgumentException('DataObject::setField: passed an object that is not a DBField');
2640
            }
2641
2642
            if (!empty($val) && !is_scalar($val)) {
2643
                $dbField = $this->dbObject($fieldName);
2644
                if ($dbField && $dbField->scalarValueOnly()) {
2645
                    throw new InvalidArgumentException(
2646
                        sprintf(
2647
                            'DataObject::setField: %s only accepts scalars',
2648
                            $fieldName
2649
                        )
2650
                    );
2651
                }
2652
            }
2653
2654
            // if a field is not existing or has strictly changed
2655
            if (!isset($this->record[$fieldName]) || $this->record[$fieldName] !== $val) {
2656
                // TODO Add check for php-level defaults which are not set in the db
2657
                // TODO Add check for hidden input-fields (readonly) which are not set in the db
2658
                // At the very least, the type has changed
2659
                $this->changed[$fieldName] = self::CHANGE_STRICT;
2660
2661
                if ((!isset($this->record[$fieldName]) && $val)
2662
                    || (isset($this->record[$fieldName]) && $this->record[$fieldName] != $val)
2663
                ) {
2664
                    // Value has changed as well, not just the type
2665
                    $this->changed[$fieldName] = self::CHANGE_VALUE;
2666
                }
2667
2668
                // Value is always saved back when strict check succeeds.
2669
                $this->record[$fieldName] = $val;
2670
            }
2671
        }
2672
        return $this;
2673
    }
2674
2675
    /**
2676
     * Set the value of the field, using a casting object.
2677
     * This is useful when you aren't sure that a date is in SQL format, for example.
2678
     * setCastedField() can also be used, by forms, to set related data.  For example, uploaded images
2679
     * can be saved into the Image table.
2680
     *
2681
     * @param string $fieldName Name of the field
2682
     * @param mixed $value New field value
2683
     * @return $this
2684
     */
2685
    public function setCastedField($fieldName, $value)
2686
    {
2687
        if (!$fieldName) {
2688
            user_error("DataObject::setCastedField: Called without a fieldName", E_USER_ERROR);
2689
        }
2690
        $fieldObj = $this->dbObject($fieldName);
2691
        if ($fieldObj) {
0 ignored issues
show
introduced by
$fieldObj is of type SilverStripe\ORM\FieldType\DBField, thus it always evaluated to true.
Loading history...
2692
            $fieldObj->setValue($value);
2693
            $fieldObj->saveInto($this);
2694
        } else {
2695
            $this->$fieldName = $value;
2696
        }
2697
        return $this;
2698
    }
2699
2700
    /**
2701
     * {@inheritdoc}
2702
     */
2703
    public function castingHelper($field)
2704
    {
2705
        $fieldSpec = static::getSchema()->fieldSpec(static::class, $field);
2706
        if ($fieldSpec) {
2707
            return $fieldSpec;
2708
        }
2709
2710
        // many_many_extraFields aren't presented by db(), so we check if the source query params
2711
        // provide us with meta-data for a many_many relation we can inspect for extra fields.
2712
        $queryParams = $this->getSourceQueryParams();
2713
        if (!empty($queryParams['Component.ExtraFields'])) {
2714
            $extraFields = $queryParams['Component.ExtraFields'];
2715
2716
            if (isset($extraFields[$field])) {
2717
                return $extraFields[$field];
2718
            }
2719
        }
2720
2721
        return parent::castingHelper($field);
2722
    }
2723
2724
    /**
2725
     * Returns true if the given field exists in a database column on any of
2726
     * the objects tables and optionally look up a dynamic getter with
2727
     * get<fieldName>().
2728
     *
2729
     * @param string $field Name of the field
2730
     * @return boolean True if the given field exists
2731
     */
2732
    public function hasField($field)
2733
    {
2734
        $schema = static::getSchema();
2735
        return (
2736
            array_key_exists($field, $this->record)
2737
            || array_key_exists($field, $this->components)
2738
            || $schema->fieldSpec(static::class, $field)
2739
            || $schema->unaryComponent(static::class, $field)
2740
            || $this->hasMethod("get{$field}")
2741
        );
2742
    }
2743
2744
    /**
2745
     * Returns true if the given field exists as a database column
2746
     *
2747
     * @param string $field Name of the field
2748
     *
2749
     * @return boolean
2750
     */
2751
    public function hasDatabaseField($field)
2752
    {
2753
        $spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY);
2754
        return !empty($spec);
2755
    }
2756
2757
    /**
2758
     * Returns true if the member is allowed to do the given action.
2759
     * See {@link extendedCan()} for a more versatile tri-state permission control.
2760
     *
2761
     * @param string $perm The permission to be checked, such as 'View'.
2762
     * @param Member $member The member whose permissions need checking.  Defaults to the currently logged
2763
     * in user.
2764
     * @param array $context Additional $context to pass to extendedCan()
2765
     *
2766
     * @return boolean True if the the member is allowed to do the given action
2767
     */
2768
    public function can($perm, $member = null, $context = array())
2769
    {
2770
        if (!$member) {
2771
            $member = Security::getCurrentUser();
2772
        }
2773
2774
        if ($member && Permission::checkMember($member, "ADMIN")) {
2775
            return true;
2776
        }
2777
2778
        if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
2779
            $method = 'can' . ucfirst($perm);
2780
            return $this->$method($member);
2781
        }
2782
2783
        $results = $this->extendedCan('can', $member);
2784
        if (isset($results)) {
2785
            return $results;
2786
        }
2787
2788
        return ($member && Permission::checkMember($member, $perm));
2789
    }
2790
2791
    /**
2792
     * Process tri-state responses from permission-alterting extensions.  The extensions are
2793
     * expected to return one of three values:
2794
     *
2795
     *  - false: Disallow this permission, regardless of what other extensions say
2796
     *  - true: Allow this permission, as long as no other extensions return false
2797
     *  - NULL: Don't affect the outcome
2798
     *
2799
     * This method itself returns a tri-state value, and is designed to be used like this:
2800
     *
2801
     * <code>
2802
     * $extended = $this->extendedCan('canDoSomething', $member);
2803
     * if($extended !== null) return $extended;
2804
     * else return $normalValue;
2805
     * </code>
2806
     *
2807
     * @param string $methodName Method on the same object, e.g. {@link canEdit()}
2808
     * @param Member|int $member
2809
     * @param array $context Optional context
2810
     * @return boolean|null
2811
     */
2812
    public function extendedCan($methodName, $member, $context = array())
2813
    {
2814
        $results = $this->extend($methodName, $member, $context);
2815
        if ($results && is_array($results)) {
2816
            // Remove NULLs
2817
            $results = array_filter($results, function ($v) {
2818
                return !is_null($v);
2819
            });
2820
            // If there are any non-NULL responses, then return the lowest one of them.
2821
            // If any explicitly deny the permission, then we don't get access
2822
            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...
2823
                return min($results);
2824
            }
2825
        }
2826
        return null;
2827
    }
2828
2829
    /**
2830
     * @param Member $member
2831
     * @return boolean
2832
     */
2833
    public function canView($member = null)
2834
    {
2835
        $extended = $this->extendedCan(__FUNCTION__, $member);
2836
        if ($extended !== null) {
2837
            return $extended;
2838
        }
2839
        return Permission::check('ADMIN', 'any', $member);
2840
    }
2841
2842
    /**
2843
     * @param Member $member
2844
     * @return boolean
2845
     */
2846
    public function canEdit($member = null)
2847
    {
2848
        $extended = $this->extendedCan(__FUNCTION__, $member);
2849
        if ($extended !== null) {
2850
            return $extended;
2851
        }
2852
        return Permission::check('ADMIN', 'any', $member);
2853
    }
2854
2855
    /**
2856
     * @param Member $member
2857
     * @return boolean
2858
     */
2859
    public function canDelete($member = null)
2860
    {
2861
        $extended = $this->extendedCan(__FUNCTION__, $member);
2862
        if ($extended !== null) {
2863
            return $extended;
2864
        }
2865
        return Permission::check('ADMIN', 'any', $member);
2866
    }
2867
2868
    /**
2869
     * @param Member $member
2870
     * @param array $context Additional context-specific data which might
2871
     * affect whether (or where) this object could be created.
2872
     * @return boolean
2873
     */
2874
    public function canCreate($member = null, $context = array())
2875
    {
2876
        $extended = $this->extendedCan(__FUNCTION__, $member, $context);
2877
        if ($extended !== null) {
2878
            return $extended;
2879
        }
2880
        return Permission::check('ADMIN', 'any', $member);
2881
    }
2882
2883
    /**
2884
     * Debugging used by Debug::show()
2885
     *
2886
     * @return string HTML data representing this object
2887
     */
2888
    public function debug()
2889
    {
2890
        $class = static::class;
2891
        $val = "<h3>Database record: {$class}</h3>\n<ul>\n";
2892
        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...
2893
            foreach ($this->record as $fieldName => $fieldVal) {
2894
                $val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
2895
            }
2896
        }
2897
        $val .= "</ul>\n";
2898
        return $val;
2899
    }
2900
2901
    /**
2902
     * Return the DBField object that represents the given field.
2903
     * This works similarly to obj() with 2 key differences:
2904
     *   - it still returns an object even when the field has no value.
2905
     *   - it only matches fields and not methods
2906
     *   - it matches foreign keys generated by has_one relationships, eg, "ParentID"
2907
     *
2908
     * @param string $fieldName Name of the field
2909
     * @return DBField The field as a DBField object
2910
     */
2911
    public function dbObject($fieldName)
2912
    {
2913
        // Check for field in DB
2914
        $schema = static::getSchema();
2915
        $helper = $schema->fieldSpec(static::class, $fieldName, DataObjectSchema::INCLUDE_CLASS);
2916
        if (!$helper) {
2917
            return null;
2918
        }
2919
2920
        if (!isset($this->record[$fieldName]) && isset($this->record[$fieldName . '_Lazy'])) {
2921
            $tableClass = $this->record[$fieldName . '_Lazy'];
2922
            $this->loadLazyFields($tableClass);
2923
        }
2924
2925
        $value = isset($this->record[$fieldName])
2926
            ? $this->record[$fieldName]
2927
            : null;
2928
2929
        // If we have a DBField object in $this->record, then return that
2930
        if ($value instanceof DBField) {
2931
            return $value;
2932
        }
2933
2934
        list($class, $spec) = explode('.', $helper);
2935
        /** @var DBField $obj */
2936
        $table = $schema->tableName($class);
2937
        $obj = Injector::inst()->create($spec, $fieldName);
2938
        $obj->setTable($table);
2939
        $obj->setValue($value, $this, false);
2940
        return $obj;
2941
    }
2942
2943
    /**
2944
     * Traverses to a DBField referenced by relationships between data objects.
2945
     *
2946
     * The path to the related field is specified with dot separated syntax
2947
     * (eg: Parent.Child.Child.FieldName).
2948
     *
2949
     * If a relation is blank, this will return null instead.
2950
     * If a relation name is invalid (e.g. non-relation on a parent) this
2951
     * can throw a LogicException.
2952
     *
2953
     * @param string $fieldPath List of paths on this object. All items in this path
2954
     * must be ViewableData implementors
2955
     *
2956
     * @return mixed DBField of the field on the object or a DataList instance.
2957
     * @throws LogicException If accessing invalid relations
2958
     */
2959
    public function relObject($fieldPath)
2960
    {
2961
        $object = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $object is dead and can be removed.
Loading history...
2962
        $component = $this;
2963
2964
        // Parse all relations
2965
        foreach (explode('.', $fieldPath) as $relation) {
2966
            if (!$component) {
2967
                return null;
2968
            }
2969
2970
            // Inspect relation type
2971
            if (ClassInfo::hasMethod($component, $relation)) {
2972
                $component = $component->$relation();
2973
            } elseif ($component instanceof Relation || $component instanceof DataList) {
2974
                // $relation could either be a field (aggregate), or another relation
2975
                $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

2975
                $singleton = DataObject::singleton($component->/** @scrutinizer ignore-call */ dataClass());
Loading history...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2976
                $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

2976
                $component = $singleton->dbObject($relation) ?: $component->/** @scrutinizer ignore-call */ relation($relation);
Loading history...
2977
            } elseif ($component instanceof DataObject && ($dbObject = $component->dbObject($relation))) {
2978
                $component = $dbObject;
2979
            } elseif ($component instanceof ViewableData && $component->hasField($relation)) {
2980
                $component = $component->obj($relation);
2981
            } else {
2982
                throw new LogicException(
2983
                    "$relation is not a relation/field on " . get_class($component)
2984
                );
2985
            }
2986
        }
2987
        return $component;
2988
    }
2989
2990
    /**
2991
     * Traverses to a field referenced by relationships between data objects, returning the value
2992
     * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)
2993
     *
2994
     * @param string $fieldName string
2995
     * @return mixed Will return null on a missing value
2996
     */
2997
    public function relField($fieldName)
2998
    {
2999
        // Navigate to relative parent using relObject() if needed
3000
        $component = $this;
3001
        if (($pos = strrpos($fieldName, '.')) !== false) {
3002
            $relation = substr($fieldName, 0, $pos);
3003
            $fieldName = substr($fieldName, $pos + 1);
3004
            $component = $this->relObject($relation);
3005
        }
3006
3007
        // Bail if the component is null
3008
        if (!$component) {
3009
            return null;
3010
        }
3011
        if (ClassInfo::hasMethod($component, $fieldName)) {
3012
            return $component->$fieldName();
3013
        }
3014
        return $component->$fieldName;
3015
    }
3016
3017
    /**
3018
     * Temporary hack to return an association name, based on class, to get around the mangle
3019
     * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
3020
     *
3021
     * @param string $className
3022
     * @return string
3023
     */
3024
    public function getReverseAssociation($className)
3025
    {
3026
        if (is_array($this->manyMany())) {
0 ignored issues
show
introduced by
The condition is_array($this->manyMany()) is always true.
Loading history...
3027
            $many_many = array_flip($this->manyMany());
3028
            if (array_key_exists($className, $many_many)) {
3029
                return $many_many[$className];
3030
            }
3031
        }
3032
        if (is_array($this->hasMany())) {
0 ignored issues
show
introduced by
The condition is_array($this->hasMany()) is always true.
Loading history...
3033
            $has_many = array_flip($this->hasMany());
3034
            if (array_key_exists($className, $has_many)) {
3035
                return $has_many[$className];
3036
            }
3037
        }
3038
        if (is_array($this->hasOne())) {
0 ignored issues
show
introduced by
The condition is_array($this->hasOne()) is always true.
Loading history...
3039
            $has_one = array_flip($this->hasOne());
3040
            if (array_key_exists($className, $has_one)) {
3041
                return $has_one[$className];
3042
            }
3043
        }
3044
3045
        return false;
3046
    }
3047
3048
    /**
3049
     * Return all objects matching the filter
3050
     * sub-classes are automatically selected and included
3051
     *
3052
     * @param string $callerClass The class of objects to be returned
3053
     * @param string|array $filter A filter to be inserted into the WHERE clause.
3054
     * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
3055
     * @param string|array $sort A sort expression to be inserted into the ORDER
3056
     * BY clause.  If omitted, self::$default_sort will be used.
3057
     * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
3058
     * @param string|array $limit A limit expression to be inserted into the LIMIT clause.
3059
     * @param string $containerClass The container class to return the results in.
3060
     *
3061
     * @todo $containerClass is Ignored, why?
3062
     *
3063
     * @return DataList The objects matching the filter, in the class specified by $containerClass
3064
     */
3065
    public static function get(
3066
        $callerClass = null,
3067
        $filter = "",
3068
        $sort = "",
3069
        $join = "",
3070
        $limit = null,
3071
        $containerClass = DataList::class
3072
    ) {
3073
        // Validate arguments
3074
        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...
3075
            $callerClass = get_called_class();
3076
            if ($callerClass === self::class) {
3077
                throw new InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
3078
            }
3079
            if ($filter || $sort || $join || $limit || ($containerClass !== DataList::class)) {
3080
                throw new InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
3081
                    . ' arguments');
3082
            }
3083
        } elseif ($callerClass === self::class) {
3084
            throw new InvalidArgumentException('DataObject::get() cannot query non-subclass DataObject directly');
3085
        }
3086
        if ($join) {
3087
            throw new InvalidArgumentException(
3088
                'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
3089
            );
3090
        }
3091
3092
        // Build and decorate with args
3093
        $result = DataList::create($callerClass);
3094
        if ($filter) {
3095
            $result = $result->where($filter);
3096
        }
3097
        if ($sort) {
3098
            $result = $result->sort($sort);
3099
        }
3100
        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

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

3101
            $limitArguments = explode(',', /** @scrutinizer ignore-type */ $limit);
Loading history...
3102
            $result = $result->limit($limitArguments[1], $limitArguments[0]);
3103
        } elseif ($limit) {
3104
            $result = $result->limit($limit);
3105
        }
3106
3107
        return $result;
3108
    }
3109
3110
3111
    /**
3112
     * Return the first item matching the given query.
3113
     * All calls to get_one() are cached.
3114
     *
3115
     * @param string $callerClass The class of objects to be returned
3116
     * @param string|array $filter A filter to be inserted into the WHERE clause.
3117
     * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
3118
     * @param boolean $cache Use caching
3119
     * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
3120
     *
3121
     * @return DataObject|null The first item matching the query
3122
     */
3123
    public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "")
3124
    {
3125
        $SNG = singleton($callerClass);
3126
3127
        $cacheComponents = array($filter, $orderby, $SNG->extend('cacheKeyComponent'));
3128
        $cacheKey = md5(serialize($cacheComponents));
3129
3130
        $item = null;
3131
        if (!$cache || !isset(self::$_cache_get_one[$callerClass][$cacheKey])) {
3132
            $dl = DataObject::get($callerClass)->where($filter)->sort($orderby);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
3133
            $item = $dl->first();
3134
3135
            if ($cache) {
3136
                self::$_cache_get_one[$callerClass][$cacheKey] = $item;
3137
                if (!self::$_cache_get_one[$callerClass][$cacheKey]) {
3138
                    self::$_cache_get_one[$callerClass][$cacheKey] = false;
3139
                }
3140
            }
3141
        }
3142
3143
        if ($cache) {
3144
            return self::$_cache_get_one[$callerClass][$cacheKey] ?: null;
3145
        } else {
3146
            return $item;
3147
        }
3148
    }
3149
3150
    /**
3151
     * Flush the cached results for all relations (has_one, has_many, many_many)
3152
     * Also clears any cached aggregate data.
3153
     *
3154
     * @param boolean $persistent When true will also clear persistent data stored in the Cache system.
3155
     *                            When false will just clear session-local cached data
3156
     * @return DataObject $this
3157
     */
3158
    public function flushCache($persistent = true)
3159
    {
3160
        if (static::class == self::class) {
0 ignored issues
show
introduced by
The condition static::class == self::class is always true.
Loading history...
3161
            self::$_cache_get_one = array();
3162
            return $this;
3163
        }
3164
3165
        $classes = ClassInfo::ancestry(static::class);
3166
        foreach ($classes as $class) {
3167
            if (isset(self::$_cache_get_one[$class])) {
3168
                unset(self::$_cache_get_one[$class]);
3169
            }
3170
        }
3171
3172
        $this->extend('flushCache');
3173
3174
        $this->components = array();
3175
        return $this;
3176
    }
3177
3178
    /**
3179
     * Flush the get_one global cache and destroy associated objects.
3180
     */
3181
    public static function flush_and_destroy_cache()
3182
    {
3183
        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...
3184
            foreach (self::$_cache_get_one as $class => $items) {
3185
                if (is_array($items)) {
3186
                    foreach ($items as $item) {
3187
                        if ($item) {
3188
                            $item->destroy();
3189
                        }
3190
                    }
3191
                }
3192
            }
3193
        }
3194
        self::$_cache_get_one = array();
3195
    }
3196
3197
    /**
3198
     * Reset all global caches associated with DataObject.
3199
     */
3200
    public static function reset()
3201
    {
3202
        // @todo Decouple these
3203
        DBClassName::clear_classname_cache();
3204
        ClassInfo::reset_db_cache();
3205
        static::getSchema()->reset();
3206
        self::$_cache_get_one = array();
3207
        self::$_cache_field_labels = array();
3208
    }
3209
3210
    /**
3211
     * Return the given element, searching by ID.
3212
     *
3213
     * This can be called either via `DataObject::get_by_id(MyClass::class, $id)`
3214
     * or `MyClass::get_by_id($id)`
3215
     *
3216
     * @param string|int $classOrID The class of the object to be returned, or id if called on target class
3217
     * @param int|bool $idOrCache The id of the element, or cache if called on target class
3218
     * @param boolean $cache See {@link get_one()}
3219
     *
3220
     * @return static The element
3221
     */
3222
    public static function get_by_id($classOrID, $idOrCache = null, $cache = true)
3223
    {
3224
        // Shift arguments if passing id in first or second argument
3225
        list ($class, $id, $cached) = is_numeric($classOrID)
3226
            ? [get_called_class(), $classOrID, isset($idOrCache) ? $idOrCache : $cache]
3227
            : [$classOrID, $idOrCache, $cache];
3228
3229
        // Validate class
3230
        if ($class === self::class) {
3231
            throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly');
3232
        }
3233
3234
        // Pass to get_one
3235
        $column = static::getSchema()->sqlColumnForField($class, 'ID');
3236
        return DataObject::get_one($class, [$column => $id], $cached);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
3237
    }
3238
3239
    /**
3240
     * Get the name of the base table for this object
3241
     *
3242
     * @return string
3243
     */
3244
    public function baseTable()
3245
    {
3246
        return static::getSchema()->baseDataTable($this);
3247
    }
3248
3249
    /**
3250
     * Get the base class for this object
3251
     *
3252
     * @return string
3253
     */
3254
    public function baseClass()
3255
    {
3256
        return static::getSchema()->baseDataClass($this);
3257
    }
3258
3259
    /**
3260
     * @var array Parameters used in the query that built this object.
3261
     * This can be used by decorators (e.g. lazy loading) to
3262
     * run additional queries using the same context.
3263
     */
3264
    protected $sourceQueryParams;
3265
3266
    /**
3267
     * @see $sourceQueryParams
3268
     * @return array
3269
     */
3270
    public function getSourceQueryParams()
3271
    {
3272
        return $this->sourceQueryParams;
3273
    }
3274
3275
    /**
3276
     * Get list of parameters that should be inherited to relations on this object
3277
     *
3278
     * @return array
3279
     */
3280
    public function getInheritableQueryParams()
3281
    {
3282
        $params = $this->getSourceQueryParams();
3283
        $this->extend('updateInheritableQueryParams', $params);
3284
        return $params;
3285
    }
3286
3287
    /**
3288
     * @see $sourceQueryParams
3289
     * @param array
3290
     */
3291
    public function setSourceQueryParams($array)
3292
    {
3293
        $this->sourceQueryParams = $array;
3294
    }
3295
3296
    /**
3297
     * @see $sourceQueryParams
3298
     * @param string $key
3299
     * @param string $value
3300
     */
3301
    public function setSourceQueryParam($key, $value)
3302
    {
3303
        $this->sourceQueryParams[$key] = $value;
3304
    }
3305
3306
    /**
3307
     * @see $sourceQueryParams
3308
     * @param string $key
3309
     * @return string
3310
     */
3311
    public function getSourceQueryParam($key)
3312
    {
3313
        if (isset($this->sourceQueryParams[$key])) {
3314
            return $this->sourceQueryParams[$key];
3315
        }
3316
        return null;
3317
    }
3318
3319
    //-------------------------------------------------------------------------------------------//
3320
3321
    /**
3322
     * Check the database schema and update it as necessary.
3323
     *
3324
     * @uses DataExtension->augmentDatabase()
3325
     */
3326
    public function requireTable()
3327
    {
3328
        // Only build the table if we've actually got fields
3329
        $schema = static::getSchema();
3330
        $table = $schema->tableName(static::class);
3331
        $fields = $schema->databaseFields(static::class, false);
3332
        $indexes = $schema->databaseIndexes(static::class, false);
3333
        $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

3333
        /** @scrutinizer ignore-call */ 
3334
        $extensions = self::database_extensions(static::class);
Loading history...
3334
3335
        if (empty($table)) {
3336
            throw new LogicException(
3337
                "Class " . static::class . " not loaded by manifest, or no database table configured"
3338
            );
3339
        }
3340
3341
        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...
3342
            $hasAutoIncPK = get_parent_class($this) === self::class;
3343
            DB::require_table(
3344
                $table,
3345
                $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

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

3346
                /** @scrutinizer ignore-type */ $indexes,
Loading history...
3347
                $hasAutoIncPK,
3348
                $this->config()->get('create_table_options'),
3349
                $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

3349
                /** @scrutinizer ignore-type */ $extensions
Loading history...
3350
            );
3351
        } else {
3352
            DB::dont_require_table($table);
3353
        }
3354
3355
        // Build any child tables for many_many items
3356
        if ($manyMany = $this->uninherited('many_many')) {
3357
            $extras = $this->uninherited('many_many_extraFields');
3358
            foreach ($manyMany as $component => $spec) {
3359
                // Get many_many spec
3360
                $manyManyComponent = $schema->manyManyComponent(static::class, $component);
3361
                $parentField = $manyManyComponent['parentField'];
3362
                $childField = $manyManyComponent['childField'];
3363
                $tableOrClass = $manyManyComponent['join'];
3364
3365
                // Skip if backed by actual class
3366
                if (class_exists($tableOrClass)) {
3367
                    continue;
3368
                }
3369
3370
                // Build fields
3371
                $manymanyFields = array(
3372
                    $parentField => "Int",
3373
                    $childField => "Int",
3374
                );
3375
                if (isset($extras[$component])) {
3376
                    $manymanyFields = array_merge($manymanyFields, $extras[$component]);
3377
                }
3378
3379
                // Build index list
3380
                $manymanyIndexes = [
3381
                    $parentField => [
3382
                        'type' => 'index',
3383
                        'name' => $parentField,
3384
                        'columns' => [$parentField],
3385
                    ],
3386
                    $childField => [
3387
                        'type' => 'index',
3388
                        'name' => $childField,
3389
                        'columns' => [$childField],
3390
                    ],
3391
                ];
3392
                DB::require_table($tableOrClass, $manymanyFields, $manymanyIndexes, true, null, $extensions);
0 ignored issues
show
Bug introduced by
$manymanyIndexes of type array<mixed,array<string,array|mixed|string>> is incompatible with the type string expected by parameter $indexSchema of SilverStripe\ORM\DB::require_table(). ( Ignorable by Annotation )

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

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

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

3392
                DB::require_table($tableOrClass, /** @scrutinizer ignore-type */ $manymanyFields, $manymanyIndexes, true, null, $extensions);
Loading history...
3393
            }
3394
        }
3395
3396
        // Let any extentions make their own database fields
3397
        $this->extend('augmentDatabase', $dummy);
3398
    }
3399
3400
    /**
3401
     * Add default records to database. This function is called whenever the
3402
     * database is built, after the database tables have all been created. Overload
3403
     * this to add default records when the database is built, but make sure you
3404
     * call parent::requireDefaultRecords().
3405
     *
3406
     * @uses DataExtension->requireDefaultRecords()
3407
     */
3408
    public function requireDefaultRecords()
3409
    {
3410
        $defaultRecords = $this->config()->uninherited('default_records');
3411
3412
        if (!empty($defaultRecords)) {
3413
            $hasData = DataObject::get_one(static::class);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
3414
            if (!$hasData) {
3415
                $className = static::class;
3416
                foreach ($defaultRecords as $record) {
3417
                    $obj = Injector::inst()->create($className, $record);
3418
                    $obj->write();
3419
                }
3420
                DB::alteration_message("Added default records to $className table", "created");
3421
            }
3422
        }
3423
3424
        // Let any extentions make their own database default data
3425
        $this->extend('requireDefaultRecords', $dummy);
3426
    }
3427
3428
    /**
3429
     * Get the default searchable fields for this object, as defined in the
3430
     * $searchable_fields list. If searchable fields are not defined on the
3431
     * data object, uses a default selection of summary fields.
3432
     *
3433
     * @return array
3434
     */
3435
    public function searchableFields()
3436
    {
3437
        // can have mixed format, need to make consistent in most verbose form
3438
        $fields = $this->config()->get('searchable_fields');
3439
        $labels = $this->fieldLabels();
3440
3441
        // fallback to summary fields (unless empty array is explicitly specified)
3442
        if (!$fields && !is_array($fields)) {
3443
            $summaryFields = array_keys($this->summaryFields());
3444
            $fields = array();
3445
3446
            // remove the custom getters as the search should not include them
3447
            $schema = static::getSchema();
3448
            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...
3449
                foreach ($summaryFields as $key => $name) {
3450
                    $spec = $name;
3451
3452
                    // Extract field name in case this is a method called on a field (e.g. "Date.Nice")
3453
                    if (($fieldPos = strpos($name, '.')) !== false) {
3454
                        $name = substr($name, 0, $fieldPos);
3455
                    }
3456
3457
                    if ($schema->fieldSpec($this, $name)) {
3458
                        $fields[] = $name;
3459
                    } elseif ($this->relObject($spec)) {
3460
                        $fields[] = $spec;
3461
                    }
3462
                }
3463
            }
3464
        }
3465
3466
        // we need to make sure the format is unified before
3467
        // augmenting fields, so extensions can apply consistent checks
3468
        // but also after augmenting fields, because the extension
3469
        // might use the shorthand notation as well
3470
3471
        // rewrite array, if it is using shorthand syntax
3472
        $rewrite = array();
3473
        foreach ($fields as $name => $specOrName) {
3474
            $identifer = (is_int($name)) ? $specOrName : $name;
3475
3476
            if (is_int($name)) {
3477
                // Format: array('MyFieldName')
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3478
                $rewrite[$identifer] = array();
3479
            } elseif (is_array($specOrName) && ($relObject = $this->relObject($identifer))) {
3480
                // Format: array('MyFieldName' => array(
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3481
                //   'filter => 'ExactMatchFilter',
3482
                //   'field' => 'NumericField', // optional
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3483
                //   'title' => 'My Title', // optional
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3484
                // ))
3485
                $rewrite[$identifer] = array_merge(
3486
                    array('filter' => $relObject->config()->get('default_search_filter_class')),
3487
                    (array)$specOrName
3488
                );
3489
            } else {
3490
                // Format: array('MyFieldName' => 'ExactMatchFilter')
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3491
                $rewrite[$identifer] = array(
3492
                    'filter' => $specOrName,
3493
                );
3494
            }
3495
            if (!isset($rewrite[$identifer]['title'])) {
3496
                $rewrite[$identifer]['title'] = (isset($labels[$identifer]))
3497
                    ? $labels[$identifer] : FormField::name_to_label($identifer);
3498
            }
3499
            if (!isset($rewrite[$identifer]['filter'])) {
3500
                /** @skipUpgrade */
3501
                $rewrite[$identifer]['filter'] = 'PartialMatchFilter';
3502
            }
3503
        }
3504
3505
        $fields = $rewrite;
3506
3507
        // apply DataExtensions if present
3508
        $this->extend('updateSearchableFields', $fields);
3509
3510
        return $fields;
3511
    }
3512
3513
    /**
3514
     * Get any user defined searchable fields labels that
3515
     * exist. Allows overriding of default field names in the form
3516
     * interface actually presented to the user.
3517
     *
3518
     * The reason for keeping this separate from searchable_fields,
3519
     * which would be a logical place for this functionality, is to
3520
     * avoid bloating and complicating the configuration array. Currently
3521
     * much of this system is based on sensible defaults, and this property
3522
     * would generally only be set in the case of more complex relationships
3523
     * between data object being required in the search interface.
3524
     *
3525
     * Generates labels based on name of the field itself, if no static property
3526
     * {@link self::field_labels} exists.
3527
     *
3528
     * @uses $field_labels
3529
     * @uses FormField::name_to_label()
3530
     *
3531
     * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
3532
     *
3533
     * @return array|string Array of all element labels if no argument given, otherwise the label of the field
3534
     */
3535
    public function fieldLabels($includerelations = true)
3536
    {
3537
        $cacheKey = static::class . '_' . $includerelations;
3538
3539
        if (!isset(self::$_cache_field_labels[$cacheKey])) {
3540
            $customLabels = $this->config()->get('field_labels');
3541
            $autoLabels = array();
3542
3543
            // get all translated static properties as defined in i18nCollectStatics()
3544
            $ancestry = ClassInfo::ancestry(static::class);
3545
            $ancestry = array_reverse($ancestry);
3546
            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...
3547
                foreach ($ancestry as $ancestorClass) {
3548
                    if ($ancestorClass === ViewableData::class) {
3549
                        break;
3550
                    }
3551
                    $types = [
3552
                        'db' => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
3553
                    ];
3554
                    if ($includerelations) {
3555
                        $types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
3556
                        $types['has_many'] = (array)Config::inst()->get(
3557
                            $ancestorClass,
3558
                            'has_many',
3559
                            Config::UNINHERITED
3560
                        );
3561
                        $types['many_many'] = (array)Config::inst()->get(
3562
                            $ancestorClass,
3563
                            'many_many',
3564
                            Config::UNINHERITED
3565
                        );
3566
                        $types['belongs_many_many'] = (array)Config::inst()->get(
3567
                            $ancestorClass,
3568
                            'belongs_many_many',
3569
                            Config::UNINHERITED
3570
                        );
3571
                    }
3572
                    foreach ($types as $type => $attrs) {
3573
                        foreach ($attrs as $name => $spec) {
3574
                            $autoLabels[$name] = _t(
3575
                                "{$ancestorClass}.{$type}_{$name}",
3576
                                FormField::name_to_label($name)
3577
                            );
3578
                        }
3579
                    }
3580
                }
3581
            }
3582
3583
            $labels = array_merge((array)$autoLabels, (array)$customLabels);
3584
            $this->extend('updateFieldLabels', $labels);
3585
            self::$_cache_field_labels[$cacheKey] = $labels;
3586
        }
3587
3588
        return self::$_cache_field_labels[$cacheKey];
3589
    }
3590
3591
    /**
3592
     * Get a human-readable label for a single field,
3593
     * see {@link fieldLabels()} for more details.
3594
     *
3595
     * @uses fieldLabels()
3596
     * @uses FormField::name_to_label()
3597
     *
3598
     * @param string $name Name of the field
3599
     * @return string Label of the field
3600
     */
3601
    public function fieldLabel($name)
3602
    {
3603
        $labels = $this->fieldLabels();
3604
        return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name);
3605
    }
3606
3607
    /**
3608
     * Get the default summary fields for this object.
3609
     *
3610
     * @todo use the translation apparatus to return a default field selection for the language
3611
     *
3612
     * @return array
3613
     */
3614
    public function summaryFields()
3615
    {
3616
        $rawFields = $this->config()->get('summary_fields');
3617
3618
        // Merge associative / numeric keys
3619
        $fields = [];
3620
        foreach ($rawFields as $key => $value) {
3621
            if (is_int($key)) {
3622
                $key = $value;
3623
            }
3624
            $fields[$key] = $value;
3625
        }
3626
3627
        if (!$fields) {
3628
            $fields = array();
3629
            // try to scaffold a couple of usual suspects
3630
            if ($this->hasField('Name')) {
3631
                $fields['Name'] = 'Name';
3632
            }
3633
            if (static::getSchema()->fieldSpec($this, 'Title')) {
3634
                $fields['Title'] = 'Title';
3635
            }
3636
            if ($this->hasField('Description')) {
3637
                $fields['Description'] = 'Description';
3638
            }
3639
            if ($this->hasField('FirstName')) {
3640
                $fields['FirstName'] = 'First Name';
3641
            }
3642
        }
3643
        $this->extend("updateSummaryFields", $fields);
3644
3645
        // Final fail-over, just list ID field
3646
        if (!$fields) {
3647
            $fields['ID'] = 'ID';
3648
        }
3649
3650
        // Localize fields (if possible)
3651
        foreach ($this->fieldLabels(false) as $name => $label) {
3652
            // only attempt to localize if the label definition is the same as the field name.
3653
            // this will preserve any custom labels set in the summary_fields configuration
3654
            if (isset($fields[$name]) && $name === $fields[$name]) {
3655
                $fields[$name] = $label;
3656
            }
3657
        }
3658
3659
        return $fields;
3660
    }
3661
3662
    /**
3663
     * Defines a default list of filters for the search context.
3664
     *
3665
     * If a filter class mapping is defined on the data object,
3666
     * it is constructed here. Otherwise, the default filter specified in
3667
     * {@link DBField} is used.
3668
     *
3669
     * @todo error handling/type checking for valid FormField and SearchFilter subclasses?
3670
     *
3671
     * @return array
3672
     */
3673
    public function defaultSearchFilters()
3674
    {
3675
        $filters = array();
3676
3677
        foreach ($this->searchableFields() as $name => $spec) {
3678
            if (empty($spec['filter'])) {
3679
                /** @skipUpgrade */
3680
                $filters[$name] = 'PartialMatchFilter';
3681
            } elseif ($spec['filter'] instanceof SearchFilter) {
3682
                $filters[$name] = $spec['filter'];
3683
            } else {
3684
                $filters[$name] = Injector::inst()->create($spec['filter'], $name);
3685
            }
3686
        }
3687
3688
        return $filters;
3689
    }
3690
3691
    /**
3692
     * @return boolean True if the object is in the database
3693
     */
3694
    public function isInDB()
3695
    {
3696
        return is_numeric($this->ID) && $this->ID > 0;
3697
    }
3698
3699
    /*
3700
     * @ignore
3701
     */
3702
    private static $subclass_access = true;
3703
3704
    /**
3705
     * Temporarily disable subclass access in data object qeur
3706
     */
3707
    public static function disable_subclass_access()
3708
    {
3709
        self::$subclass_access = false;
3710
    }
3711
3712
    public static function enable_subclass_access()
3713
    {
3714
        self::$subclass_access = true;
3715
    }
3716
3717
    //-------------------------------------------------------------------------------------------//
3718
3719
    /**
3720
     * Database field definitions.
3721
     * This is a map from field names to field type. The field
3722
     * type should be a class that extends .
3723
     * @var array
3724
     * @config
3725
     */
3726
    private static $db = [];
3727
3728
    /**
3729
     * Use a casting object for a field. This is a map from
3730
     * field name to class name of the casting object.
3731
     *
3732
     * @var array
3733
     */
3734
    private static $casting = array(
3735
        "Title" => 'Text',
3736
    );
3737
3738
    /**
3739
     * Specify custom options for a CREATE TABLE call.
3740
     * Can be used to specify a custom storage engine for specific database table.
3741
     * All options have to be keyed for a specific database implementation,
3742
     * identified by their class name (extending from {@link SS_Database}).
3743
     *
3744
     * <code>
3745
     * array(
3746
     *  'MySQLDatabase' => 'ENGINE=MyISAM'
3747
     * )
3748
     * </code>
3749
     *
3750
     * Caution: This API is experimental, and might not be
3751
     * included in the next major release. Please use with care.
3752
     *
3753
     * @var array
3754
     * @config
3755
     */
3756
    private static $create_table_options = array(
3757
        MySQLSchemaManager::ID => 'ENGINE=InnoDB'
3758
    );
3759
3760
    /**
3761
     * If a field is in this array, then create a database index
3762
     * on that field. This is a map from fieldname to index type.
3763
     * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
3764
     *
3765
     * @var array
3766
     * @config
3767
     */
3768
    private static $indexes = null;
3769
3770
    /**
3771
     * Inserts standard column-values when a DataObject
3772
     * is instanciated. Does not insert default records {@see $default_records}.
3773
     * This is a map from fieldname to default value.
3774
     *
3775
     *  - If you would like to change a default value in a sub-class, just specify it.
3776
     *  - If you would like to disable the default value given by a parent class, set the default value to 0,'',
3777
     *    or false in your subclass.  Setting it to null won't work.
3778
     *
3779
     * @var array
3780
     * @config
3781
     */
3782
    private static $defaults = [];
3783
3784
    /**
3785
     * Multidimensional array which inserts default data into the database
3786
     * on a db/build-call as long as the database-table is empty. Please use this only
3787
     * for simple constructs, not for SiteTree-Objects etc. which need special
3788
     * behaviour such as publishing and ParentNodes.
3789
     *
3790
     * Example:
3791
     * array(
3792
     *  array('Title' => "DefaultPage1", 'PageTitle' => 'page1'),
3793
     *  array('Title' => "DefaultPage2")
3794
     * ).
3795
     *
3796
     * @var array
3797
     * @config
3798
     */
3799
    private static $default_records = null;
3800
3801
    /**
3802
     * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a
3803
     * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class.
3804
     *
3805
     * Note that you cannot have a has_one and belongs_to relationship with the same name.
3806
     *
3807
     * @var array
3808
     * @config
3809
     */
3810
    private static $has_one = [];
3811
3812
    /**
3813
     * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.
3814
     *
3815
     * This does not actually create any data structures, but allows you to query the other object in a one-to-one
3816
     * relationship from the child object. If you have multiple belongs_to links to another object you can use the
3817
     * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use.
3818
     *
3819
     * Note that you cannot have a has_one and belongs_to relationship with the same name.
3820
     *
3821
     * @var array
3822
     * @config
3823
     */
3824
    private static $belongs_to = [];
3825
3826
    /**
3827
     * This defines a one-to-many relationship. It is a map of component name to the remote data class.
3828
     *
3829
     * This relationship type does not actually create a data structure itself - you need to define a matching $has_one
3830
     * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this
3831
     * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show
3832
     * which foreign key to use.
3833
     *
3834
     * @var array
3835
     * @config
3836
     */
3837
    private static $has_many = [];
3838
3839
    /**
3840
     * many-many relationship definitions.
3841
     * This is a map from component name to data type.
3842
     * @var array
3843
     * @config
3844
     */
3845
    private static $many_many = [];
3846
3847
    /**
3848
     * Extra fields to include on the connecting many-many table.
3849
     * This is a map from field name to field type.
3850
     *
3851
     * Example code:
3852
     * <code>
3853
     * public static $many_many_extraFields = array(
3854
     *  'Members' => array(
3855
     *          'Role' => 'Varchar(100)'
3856
     *      )
3857
     * );
3858
     * </code>
3859
     *
3860
     * @var array
3861
     * @config
3862
     */
3863
    private static $many_many_extraFields = [];
3864
3865
    /**
3866
     * The inverse side of a many-many relationship.
3867
     * This is a map from component name to data type.
3868
     * @var array
3869
     * @config
3870
     */
3871
    private static $belongs_many_many = [];
3872
3873
    /**
3874
     * The default sort expression. This will be inserted in the ORDER BY
3875
     * clause of a SQL query if no other sort expression is provided.
3876
     * @var string
3877
     * @config
3878
     */
3879
    private static $default_sort = null;
3880
3881
    /**
3882
     * Default list of fields that can be scaffolded by the ModelAdmin
3883
     * search interface.
3884
     *
3885
     * Overriding the default filter, with a custom defined filter:
3886
     * <code>
3887
     *  static $searchable_fields = array(
3888
     *     "Name" => "PartialMatchFilter"
3889
     *  );
3890
     * </code>
3891
     *
3892
     * Overriding the default form fields, with a custom defined field.
3893
     * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}.
3894
     * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}.
3895
     * <code>
3896
     *  static $searchable_fields = array(
3897
     *    "Name" => array(
3898
     *      "field" => "TextField"
3899
     *    )
3900
     *  );
3901
     * </code>
3902
     *
3903
     * Overriding the default form field, filter and title:
3904
     * <code>
3905
     *  static $searchable_fields = array(
3906
     *    "Organisation.ZipCode" => array(
3907
     *      "field" => "TextField",
3908
     *      "filter" => "PartialMatchFilter",
3909
     *      "title" => 'Organisation ZIP'
3910
     *    )
3911
     *  );
3912
     * </code>
3913
     * @config
3914
     */
3915
    private static $searchable_fields = null;
3916
3917
    /**
3918
     * User defined labels for searchable_fields, used to override
3919
     * default display in the search form.
3920
     * @config
3921
     */
3922
    private static $field_labels = [];
3923
3924
    /**
3925
     * Provides a default list of fields to be used by a 'summary'
3926
     * view of this object.
3927
     * @config
3928
     */
3929
    private static $summary_fields = [];
3930
3931
    public function provideI18nEntities()
3932
    {
3933
        // Note: see http://guides.rubyonrails.org/i18n.html#pluralization for rules
3934
        // Best guess for a/an rule. Better guesses require overriding in subclasses
3935
        $pluralName = $this->plural_name();
3936
        $singularName = $this->singular_name();
3937
        $conjunction = preg_match('/^[aeiou]/i', $singularName) ? 'An ' : 'A ';
3938
        return [
3939
            static::class . '.SINGULARNAME' => $this->singular_name(),
3940
            static::class . '.PLURALNAME' => $pluralName,
3941
            static::class . '.PLURALS' => [
3942
                'one' => $conjunction . $singularName,
3943
                'other' => '{count} ' . $pluralName
3944
            ]
3945
        ];
3946
    }
3947
3948
    /**
3949
     * Returns true if the given method/parameter has a value
3950
     * (Uses the DBField::hasValue if the parameter is a database field)
3951
     *
3952
     * @param string $field The field name
3953
     * @param array $arguments
3954
     * @param bool $cache
3955
     * @return boolean
3956
     */
3957
    public function hasValue($field, $arguments = null, $cache = true)
3958
    {
3959
        // has_one fields should not use dbObject to check if a value is given
3960
        $hasOne = static::getSchema()->hasOneComponent(static::class, $field);
3961
        if (!$hasOne && ($obj = $this->dbObject($field))) {
3962
            return $obj->exists();
3963
        } else {
3964
            return parent::hasValue($field, $arguments, $cache);
3965
        }
3966
    }
3967
3968
    /**
3969
     * If selected through a many_many through relation, this is the instance of the joined record
3970
     *
3971
     * @return DataObject
3972
     */
3973
    public function getJoin()
3974
    {
3975
        return $this->joinRecord;
3976
    }
3977
3978
    /**
3979
     * Set joining object
3980
     *
3981
     * @param DataObject $object
3982
     * @param string $alias Alias
3983
     * @return $this
3984
     */
3985
    public function setJoin(DataObject $object, $alias = null)
3986
    {
3987
        $this->joinRecord = $object;
3988
        if ($alias) {
3989
            if (static::getSchema()->fieldSpec(static::class, $alias)) {
3990
                throw new InvalidArgumentException(
3991
                    "Joined record $alias cannot also be a db field"
3992
                );
3993
            }
3994
            $this->record[$alias] = $object;
3995
        }
3996
        return $this;
3997
    }
3998
3999
    /**
4000
     * Find objects in the given relationships, merging them into the given list
4001
     *
4002
     * @param string $source Config property to extract relationships from
4003
     * @param bool $recursive True if recursive
4004
     * @param ArrayList $list If specified, items will be added to this list. If not, a new
4005
     * instance of ArrayList will be constructed and returned
4006
     * @return ArrayList The list of related objects
4007
     */
4008
    public function findRelatedObjects($source, $recursive = true, $list = null)
4009
    {
4010
        if (!$list) {
4011
            $list = new ArrayList();
4012
        }
4013
4014
        // Skip search for unsaved records
4015
        if (!$this->isInDB()) {
4016
            return $list;
4017
        }
4018
4019
        $relationships = $this->config()->get($source) ?: [];
4020
        foreach ($relationships as $relationship) {
4021
            // Warn if invalid config
4022
            if (!$this->hasMethod($relationship)) {
4023
                trigger_error(sprintf(
4024
                    "Invalid %s config value \"%s\" on object on class \"%s\"",
4025
                    $source,
4026
                    $relationship,
4027
                    get_class($this)
4028
                ), E_USER_WARNING);
4029
                continue;
4030
            }
4031
4032
            // Inspect value of this relationship
4033
            $items = $this->{$relationship}();
4034
4035
            // Merge any new item
4036
            $newItems = $this->mergeRelatedObjects($list, $items);
4037
4038
            // Recurse if necessary
4039
            if ($recursive) {
4040
                foreach ($newItems as $item) {
4041
                    /** @var DataObject $item */
4042
                    $item->findRelatedObjects($source, true, $list);
4043
                }
4044
            }
4045
        }
4046
        return $list;
4047
    }
4048
4049
    /**
4050
     * Helper method to merge owned/owning items into a list.
4051
     * Items already present in the list will be skipped.
4052
     *
4053
     * @param ArrayList $list Items to merge into
4054
     * @param mixed $items List of new items to merge
4055
     * @return ArrayList List of all newly added items that did not already exist in $list
4056
     */
4057
    public function mergeRelatedObjects($list, $items)
4058
    {
4059
        $added = new ArrayList();
4060
        if (!$items) {
4061
            return $added;
4062
        }
4063
        if ($items instanceof DataObject) {
4064
            $items = [$items];
4065
        }
4066
4067
        /** @var DataObject $item */
4068
        foreach ($items as $item) {
4069
            $this->mergeRelatedObject($list, $added, $item);
4070
        }
4071
        return $added;
4072
    }
4073
4074
    /**
4075
     * Merge single object into a list, but ensures that existing objects are not
4076
     * re-added.
4077
     *
4078
     * @param ArrayList $list Global list
4079
     * @param ArrayList $added Additional list to insert into
4080
     * @param DataObject $item Item to add
4081
     */
4082
    protected function mergeRelatedObject($list, $added, $item)
4083
    {
4084
        // Identify item
4085
        $itemKey = get_class($item) . '/' . $item->ID;
4086
4087
        // Write if saved, versioned, and not already added
4088
        if ($item->isInDB() && !isset($list[$itemKey])) {
4089
            $list[$itemKey] = $item;
4090
            $added[$itemKey] = $item;
4091
        }
4092
4093
        // Add joined record (from many_many through) automatically
4094
        $joined = $item->getJoin();
4095
        if ($joined) {
0 ignored issues
show
introduced by
$joined is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
4096
            $this->mergeRelatedObject($list, $added, $joined);
4097
        }
4098
    }
4099
}
4100