Completed
Push — 4.0 ( b59aea...80f83b )
by Loz
52s queued 21s
created

DataObject::setComponent()   B

Complexity

Conditions 10
Paths 8

Size

Total Lines 37
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 19
nc 8
nop 2
dl 0
loc 37
rs 7.6666
c 0
b 0
f 0

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

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

475
            $dest->/** @scrutinizer ignore-call */ 
476
                   add($item, $extraFields);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
476
        }
477
    }
478
479
    /**
480
     * Return obsolete class name, if this is no longer a valid class
481
     *
482
     * @return string
483
     */
484
    public function getObsoleteClassName()
485
    {
486
        $className = $this->getField("ClassName");
487
        if (!ClassInfo::exists($className)) {
488
            return $className;
489
        }
490
        return null;
491
    }
492
493
    /**
494
     * Gets name of this class
495
     *
496
     * @return string
497
     */
498
    public function getClassName()
499
    {
500
        $className = $this->getField("ClassName");
501
        if (!ClassInfo::exists($className)) {
502
            return static::class;
503
        }
504
        return $className;
505
    }
506
507
    /**
508
     * Set the ClassName attribute. {@link $class} is also updated.
509
     * Warning: This will produce an inconsistent record, as the object
510
     * instance will not automatically switch to the new subclass.
511
     * Please use {@link newClassInstance()} for this purpose,
512
     * or destroy and reinstanciate the record.
513
     *
514
     * @param string $className The new ClassName attribute (a subclass of {@link DataObject})
515
     * @return $this
516
     */
517
    public function setClassName($className)
518
    {
519
        $className = trim($className);
520
        if (!$className || !is_subclass_of($className, self::class)) {
521
            return $this;
522
        }
523
524
        $this->setField("ClassName", $className);
525
        $this->setField('RecordClassName', $className);
526
        return $this;
527
    }
528
529
    /**
530
     * Create a new instance of a different class from this object's record.
531
     * This is useful when dynamically changing the type of an instance. Specifically,
532
     * it ensures that the instance of the class is a match for the className of the
533
     * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName}
534
     * property manually before calling this method, as it will confuse change detection.
535
     *
536
     * If the new class is different to the original class, defaults are populated again
537
     * because this will only occur automatically on instantiation of a DataObject if
538
     * there is no record, or the record has no ID. In this case, we do have an ID but
539
     * we still need to repopulate the defaults.
540
     *
541
     * @param string $newClassName The name of the new class
542
     *
543
     * @return DataObject The new instance of the new class, The exact type will be of the class name provided.
544
     */
545
    public function newClassInstance($newClassName)
546
    {
547
        if (!is_subclass_of($newClassName, self::class)) {
548
            throw new InvalidArgumentException("$newClassName is not a valid subclass of DataObject");
549
        }
550
551
        $originalClass = $this->ClassName;
552
553
        /** @var DataObject $newInstance */
554
        $newInstance = Injector::inst()->create($newClassName, $this->record, false);
555
556
        // Modify ClassName
557
        if ($newClassName != $originalClass) {
558
            $newInstance->setClassName($newClassName);
559
            $newInstance->populateDefaults();
560
            $newInstance->forceChange();
561
        }
562
563
        return $newInstance;
564
    }
565
566
    /**
567
     * Adds methods from the extensions.
568
     * Called by Object::__construct() once per class.
569
     */
570
    public function defineMethods()
571
    {
572
        parent::defineMethods();
573
574
        if (static::class === self::class) {
0 ignored issues
show
introduced by
The condition static::class === self::class is always true.
Loading history...
575
             return;
576
        }
577
578
        // Set up accessors for joined items
579
        if ($manyMany = $this->manyMany()) {
580
            foreach ($manyMany as $relationship => $class) {
581
                $this->addWrapperMethod($relationship, 'getManyManyComponents');
582
            }
583
        }
584
        if ($hasMany = $this->hasMany()) {
585
            foreach ($hasMany as $relationship => $class) {
586
                $this->addWrapperMethod($relationship, 'getComponents');
587
            }
588
        }
589
        if ($hasOne = $this->hasOne()) {
590
            foreach ($hasOne as $relationship => $class) {
591
                $this->addWrapperMethod($relationship, 'getComponent');
592
            }
593
        }
594
        if ($belongsTo = $this->belongsTo()) {
595
            foreach (array_keys($belongsTo) as $relationship) {
596
                $this->addWrapperMethod($relationship, 'getComponent');
597
            }
598
        }
599
    }
600
601
    /**
602
     * Returns true if this object "exists", i.e., has a sensible value.
603
     * The default behaviour for a DataObject is to return true if
604
     * the object exists in the database, you can override this in subclasses.
605
     *
606
     * @return boolean true if this object exists
607
     */
608
    public function exists()
609
    {
610
        return (isset($this->record['ID']) && $this->record['ID'] > 0);
611
    }
612
613
    /**
614
     * Returns TRUE if all values (other than "ID") are
615
     * considered empty (by weak boolean comparison).
616
     *
617
     * @return boolean
618
     */
619
    public function isEmpty()
620
    {
621
        $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...
622
        foreach ($this->toMap() as $field => $value) {
623
            // only look at custom fields
624
            if (isset($fixed[$field])) {
625
                continue;
626
            }
627
628
            $dbObject = $this->dbObject($field);
629
            if (!$dbObject) {
630
                continue;
631
            }
632
            if ($dbObject->exists()) {
633
                return false;
634
            }
635
        }
636
        return true;
637
    }
638
639
    /**
640
     * Pluralise this item given a specific count.
641
     *
642
     * E.g. "0 Pages", "1 File", "3 Images"
643
     *
644
     * @param string $count
645
     * @return string
646
     */
647
    public function i18n_pluralise($count)
648
    {
649
        $default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name();
650
        return i18n::_t(
651
            static::class . '.PLURALS',
652
            $default,
653
            [ 'count' => $count ]
654
        );
655
    }
656
657
    /**
658
     * Get the user friendly singular name of this DataObject.
659
     * If the name is not defined (by redefining $singular_name in the subclass),
660
     * this returns the class name.
661
     *
662
     * @return string User friendly singular name of this DataObject
663
     */
664
    public function singular_name()
665
    {
666
        $name = $this->config()->get('singular_name');
667
        if ($name) {
668
            return $name;
669
        }
670
        return ucwords(trim(strtolower(preg_replace(
671
            '/_?([A-Z])/',
672
            ' $1',
673
            ClassInfo::shortName($this)
674
        ))));
675
    }
676
677
    /**
678
     * Get the translated user friendly singular name of this DataObject
679
     * same as singular_name() but runs it through the translating function
680
     *
681
     * Translating string is in the form:
682
     *     $this->class.SINGULARNAME
683
     * Example:
684
     *     Page.SINGULARNAME
685
     *
686
     * @return string User friendly translated singular name of this DataObject
687
     */
688
    public function i18n_singular_name()
689
    {
690
        return _t(static::class . '.SINGULARNAME', $this->singular_name());
691
    }
692
693
    /**
694
     * Get the user friendly plural name of this DataObject
695
     * If the name is not defined (by renaming $plural_name in the subclass),
696
     * this returns a pluralised version of the class name.
697
     *
698
     * @return string User friendly plural name of this DataObject
699
     */
700
    public function plural_name()
701
    {
702
        if ($name = $this->config()->get('plural_name')) {
703
            return $name;
704
        }
705
        $name = $this->singular_name();
706
        //if the penultimate character is not a vowel, replace "y" with "ies"
707
        if (preg_match('/[^aeiou]y$/i', $name)) {
708
            $name = substr($name, 0, -1) . 'ie';
709
        }
710
        return ucfirst($name . 's');
711
    }
712
713
    /**
714
     * Get the translated user friendly plural name of this DataObject
715
     * Same as plural_name but runs it through the translation function
716
     * Translation string is in the form:
717
     *      $this->class.PLURALNAME
718
     * Example:
719
     *      Page.PLURALNAME
720
     *
721
     * @return string User friendly translated plural name of this DataObject
722
     */
723
    public function i18n_plural_name()
724
    {
725
        return _t(static::class . '.PLURALNAME', $this->plural_name());
726
    }
727
728
    /**
729
     * Standard implementation of a title/label for a specific
730
     * record. Tries to find properties 'Title' or 'Name',
731
     * and falls back to the 'ID'. Useful to provide
732
     * user-friendly identification of a record, e.g. in errormessages
733
     * or UI-selections.
734
     *
735
     * Overload this method to have a more specialized implementation,
736
     * e.g. for an Address record this could be:
737
     * <code>
738
     * function getTitle() {
739
     *   return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
740
     * }
741
     * </code>
742
     *
743
     * @return string
744
     */
745
    public function getTitle()
746
    {
747
        $schema = static::getSchema();
748
        if ($schema->fieldSpec($this, 'Title')) {
749
            return $this->getField('Title');
750
        }
751
        if ($schema->fieldSpec($this, 'Name')) {
752
            return $this->getField('Name');
753
        }
754
755
        return "#{$this->ID}";
756
    }
757
758
    /**
759
     * Returns the associated database record - in this case, the object itself.
760
     * This is included so that you can call $dataOrController->data() and get a DataObject all the time.
761
     *
762
     * @return DataObject Associated database record
763
     */
764
    public function data()
765
    {
766
        return $this;
767
    }
768
769
    /**
770
     * Convert this object to a map.
771
     *
772
     * @return array The data as a map.
773
     */
774
    public function toMap()
775
    {
776
        $this->loadLazyFields();
777
        return $this->record;
778
    }
779
780
    /**
781
     * Return all currently fetched database fields.
782
     *
783
     * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
784
     * Obviously, this makes it a lot faster.
785
     *
786
     * @return array The data as a map.
787
     */
788
    public function getQueriedDatabaseFields()
789
    {
790
        return $this->record;
791
    }
792
793
    /**
794
     * Update a number of fields on this object, given a map of the desired changes.
795
     *
796
     * The field names can be simple names, or you can use a dot syntax to access $has_one relations.
797
     * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
798
     *
799
     * update() doesn't write the main object, but if you use the dot syntax, it will write()
800
     * the related objects that it alters.
801
     *
802
     * @param array $data A map of field name to data values to update.
803
     * @return DataObject $this
804
     */
805
    public function update($data)
806
    {
807
        foreach ($data as $key => $value) {
808
            // Implement dot syntax for updates
809
            if (strpos($key, '.') !== false) {
810
                $relations = explode('.', $key);
811
                $fieldName = array_pop($relations);
812
                /** @var static $relObj */
813
                $relObj = $this;
814
                $relation = null;
815
                foreach ($relations as $i => $relation) {
816
                    // no support for has_many or many_many relationships,
817
                    // as the updater wouldn't know which object to write to (or create)
818
                    if ($relObj->$relation() instanceof DataObject) {
819
                        $parentObj = $relObj;
820
                        $relObj = $relObj->$relation();
821
                        // If the intermediate relationship objects haven't been created, then write them
822
                        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...
823
                            $relObj->write();
824
                            $relatedFieldName = $relation . "ID";
825
                            $parentObj->$relatedFieldName = $relObj->ID;
826
                            $parentObj->write();
827
                        }
828
                    } else {
829
                        user_error(
830
                            "DataObject::update(): Can't traverse relationship '$relation'," .
831
                            "it has to be a has_one relationship or return a single DataObject",
832
                            E_USER_NOTICE
833
                        );
834
                        // unset relation object so we don't write properties to the wrong object
835
                        $relObj = null;
836
                        break;
837
                    }
838
                }
839
840
                if ($relObj) {
841
                    $relObj->$fieldName = $value;
842
                    $relObj->write();
843
                    $relatedFieldName = $relation . "ID";
844
                    $this->$relatedFieldName = $relObj->ID;
845
                    $relObj->flushCache();
846
                } else {
847
                    $class = static::class;
848
                    user_error("Couldn't follow dot syntax '{$key}' on '{$class}' object", E_USER_WARNING);
849
                }
850
            } else {
851
                $this->$key = $value;
852
            }
853
        }
854
        return $this;
855
    }
856
857
    /**
858
     * Pass changes as a map, and try to
859
     * get automatic casting for these fields.
860
     * Doesn't write to the database. To write the data,
861
     * use the write() method.
862
     *
863
     * @param array $data A map of field name to data values to update.
864
     * @return DataObject $this
865
     */
866
    public function castedUpdate($data)
867
    {
868
        foreach ($data as $k => $v) {
869
            $this->setCastedField($k, $v);
870
        }
871
        return $this;
872
    }
873
874
    /**
875
     * Merges data and relations from another object of same class,
876
     * without conflict resolution. Allows to specify which
877
     * dataset takes priority in case its not empty.
878
     * has_one-relations are just transferred with priority 'right'.
879
     * has_many and many_many-relations are added regardless of priority.
880
     *
881
     * Caution: has_many/many_many relations are moved rather than duplicated,
882
     * meaning they are not connected to the merged object any longer.
883
     * Caution: Just saves updated has_many/many_many relations to the database,
884
     * doesn't write the updated object itself (just writes the object-properties).
885
     * Caution: Does not delete the merged object.
886
     * Caution: Does now overwrite Created date on the original object.
887
     *
888
     * @param DataObject $rightObj
889
     * @param string $priority left|right Determines who wins in case of a conflict (optional)
890
     * @param bool $includeRelations Merge any existing relations (optional)
891
     * @param bool $overwriteWithEmpty Overwrite existing left values with empty right values.
892
     *                            Only applicable with $priority='right'. (optional)
893
     * @return Boolean
894
     */
895
    public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false)
896
    {
897
        $leftObj = $this;
898
899
        if ($leftObj->ClassName != $rightObj->ClassName) {
900
            // we can't merge similiar subclasses because they might have additional relations
901
            user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
902
			(expected '{$leftObj->ClassName}').", E_USER_WARNING);
903
            return false;
904
        }
905
906
        if (!$rightObj->ID) {
907
            user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
908
				to make sure all relations are transferred properly.').", E_USER_WARNING);
909
            return false;
910
        }
911
912
        // makes sure we don't merge data like ID or ClassName
913
        $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...
914
        foreach ($rightData as $key => $rightSpec) {
915
            // Don't merge ID
916
            if ($key === 'ID') {
917
                continue;
918
            }
919
920
            // Only merge relations if allowed
921
            if ($rightSpec === 'ForeignKey' && !$includeRelations) {
922
                continue;
923
            }
924
925
            // don't merge conflicting values if priority is 'left'
926
            if ($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) {
927
                continue;
928
            }
929
930
            // don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
931
            if ($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) {
932
                continue;
933
            }
934
935
            // TODO remove redundant merge of has_one fields
936
            $leftObj->{$key} = $rightObj->{$key};
937
        }
938
939
        // merge relations
940
        if ($includeRelations) {
941
            if ($manyMany = $this->manyMany()) {
942
                foreach ($manyMany as $relationship => $class) {
943
                    /** @var DataObject $leftComponents */
944
                    $leftComponents = $leftObj->getManyManyComponents($relationship);
945
                    $rightComponents = $rightObj->getManyManyComponents($relationship);
946
                    if ($rightComponents && $rightComponents->exists()) {
947
                        $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

947
                        $leftComponents->/** @scrutinizer ignore-call */ 
948
                                         addMany($rightComponents->column('ID'));
Loading history...
948
                    }
949
                    $leftComponents->write();
950
                }
951
            }
952
953
            if ($hasMany = $this->hasMany()) {
954
                foreach ($hasMany as $relationship => $class) {
955
                    $leftComponents = $leftObj->getComponents($relationship);
956
                    $rightComponents = $rightObj->getComponents($relationship);
957
                    if ($rightComponents && $rightComponents->exists()) {
958
                        $leftComponents->addMany($rightComponents->column('ID'));
959
                    }
960
                    $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

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

960
                    $leftComponents->/** @scrutinizer ignore-call */ 
961
                                     write();
Loading history...
961
                }
962
            }
963
        }
964
965
        return true;
966
    }
967
968
    /**
969
     * Forces the record to think that all its data has changed.
970
     * Doesn't write to the database. Only sets fields as changed
971
     * if they are not already marked as changed.
972
     *
973
     * @return $this
974
     */
975
    public function forceChange()
976
    {
977
        // Ensure lazy fields loaded
978
        $this->loadLazyFields();
979
        $fields = static::getSchema()->fieldSpecs(static::class);
980
981
        // $this->record might not contain the blank values so we loop on $this->inheritedDatabaseFields() as well
982
        $fieldNames = array_unique(array_merge(
983
            array_keys($this->record),
984
            array_keys($fields)
985
        ));
986
987
        foreach ($fieldNames as $fieldName) {
988
            if (!isset($this->changed[$fieldName])) {
989
                $this->changed[$fieldName] = self::CHANGE_STRICT;
990
            }
991
            // Populate the null values in record so that they actually get written
992
            if (!isset($this->record[$fieldName])) {
993
                $this->record[$fieldName] = null;
994
            }
995
        }
996
997
        // @todo Find better way to allow versioned to write a new version after forceChange
998
        if ($this->isChanged('Version')) {
999
            unset($this->changed['Version']);
1000
        }
1001
        return $this;
1002
    }
1003
1004
    /**
1005
     * Validate the current object.
1006
     *
1007
     * By default, there is no validation - objects are always valid!  However, you can overload this method in your
1008
     * DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
1009
     *
1010
     * Invalid objects won't be able to be written - a warning will be thrown and no write will occur.  onBeforeWrite()
1011
     * and onAfterWrite() won't get called either.
1012
     *
1013
     * It is expected that you call validate() in your own application to test that an object is valid before
1014
     * attempting a write, and respond appropriately if it isn't.
1015
     *
1016
     * @see {@link ValidationResult}
1017
     * @return ValidationResult
1018
     */
1019
    public function validate()
1020
    {
1021
        $result = ValidationResult::create();
1022
        $this->extend('validate', $result);
1023
        return $result;
1024
    }
1025
1026
    /**
1027
     * Public accessor for {@see DataObject::validate()}
1028
     *
1029
     * @return ValidationResult
1030
     */
1031
    public function doValidate()
1032
    {
1033
        Deprecation::notice('5.0', 'Use validate');
1034
        return $this->validate();
1035
    }
1036
1037
    /**
1038
     * Event handler called before writing to the database.
1039
     * You can overload this to clean up or otherwise process data before writing it to the
1040
     * database.  Don't forget to call parent::onBeforeWrite(), though!
1041
     *
1042
     * This called after {@link $this->validate()}, so you can be sure that your data is valid.
1043
     *
1044
     * @uses DataExtension->onBeforeWrite()
1045
     */
1046
    protected function onBeforeWrite()
1047
    {
1048
        $this->brokenOnWrite = false;
1049
1050
        $dummy = null;
1051
        $this->extend('onBeforeWrite', $dummy);
1052
    }
1053
1054
    /**
1055
     * Event handler called after writing to the database.
1056
     * You can overload this to act upon changes made to the data after it is written.
1057
     * $this->changed will have a record
1058
     * database.  Don't forget to call parent::onAfterWrite(), though!
1059
     *
1060
     * @uses DataExtension->onAfterWrite()
1061
     */
1062
    protected function onAfterWrite()
1063
    {
1064
        $dummy = null;
1065
        $this->extend('onAfterWrite', $dummy);
1066
    }
1067
1068
    /**
1069
     * Find all objects that will be cascade deleted if this object is deleted
1070
     *
1071
     * Notes:
1072
     *   - If this object is versioned, objects will only be searched in the same stage as the given record.
1073
     *   - This will only be useful prior to deletion, as post-deletion this record will no longer exist.
1074
     *
1075
     * @param bool $recursive True if recursive
1076
     * @param ArrayList $list Optional list to add items to
1077
     * @return ArrayList list of objects
1078
     */
1079
    public function findCascadeDeletes($recursive = true, $list = null)
1080
    {
1081
        // Find objects in these relationships
1082
        return $this->findRelatedObjects('cascade_deletes', $recursive, $list);
1083
    }
1084
1085
    /**
1086
     * Event handler called before deleting from the database.
1087
     * You can overload this to clean up or otherwise process data before delete this
1088
     * record.  Don't forget to call parent::onBeforeDelete(), though!
1089
     *
1090
     * @uses DataExtension->onBeforeDelete()
1091
     */
1092
    protected function onBeforeDelete()
1093
    {
1094
        $this->brokenOnDelete = false;
1095
1096
        $dummy = null;
1097
        $this->extend('onBeforeDelete', $dummy);
1098
1099
        // Cascade deletes
1100
        $deletes = $this->findCascadeDeletes(false);
1101
        foreach ($deletes as $delete) {
1102
            $delete->delete();
1103
        }
1104
    }
1105
1106
    protected function onAfterDelete()
1107
    {
1108
        $this->extend('onAfterDelete');
1109
    }
1110
1111
    /**
1112
     * Load the default values in from the self::$defaults array.
1113
     * Will traverse the defaults of the current class and all its parent classes.
1114
     * Called by the constructor when creating new records.
1115
     *
1116
     * @uses DataExtension->populateDefaults()
1117
     * @return DataObject $this
1118
     */
1119
    public function populateDefaults()
1120
    {
1121
        $classes = array_reverse(ClassInfo::ancestry($this));
1122
1123
        foreach ($classes as $class) {
1124
            $defaults = Config::inst()->get($class, 'defaults', Config::UNINHERITED);
1125
1126
            if ($defaults && !is_array($defaults)) {
1127
                user_error(
1128
                    "Bad '" . static::class . "' defaults given: " . var_export($defaults, true),
1129
                    E_USER_WARNING
1130
                );
1131
                $defaults = null;
1132
            }
1133
1134
            if ($defaults) {
1135
                foreach ($defaults as $fieldName => $fieldValue) {
1136
                // SRM 2007-03-06: Stricter check
1137
                    if (!isset($this->$fieldName) || $this->$fieldName === null) {
1138
                        $this->$fieldName = $fieldValue;
1139
                    }
1140
                // Set many-many defaults with an array of ids
1141
                    if (is_array($fieldValue) && $this->getSchema()->manyManyComponent(static::class, $fieldName)) {
1142
                        /** @var ManyManyList $manyManyJoin */
1143
                        $manyManyJoin = $this->$fieldName();
1144
                        $manyManyJoin->setByIDList($fieldValue);
1145
                    }
1146
                }
1147
            }
1148
            if ($class == self::class) {
1149
                break;
1150
            }
1151
        }
1152
1153
        $this->extend('populateDefaults');
1154
        return $this;
1155
    }
1156
1157
    /**
1158
     * Determine validation of this object prior to write
1159
     *
1160
     * @return ValidationException Exception generated by this write, or null if valid
1161
     */
1162
    protected function validateWrite()
1163
    {
1164
        if ($this->ObsoleteClassName) {
0 ignored issues
show
Bug Best Practice introduced by
The property ObsoleteClassName does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1165
            return new ValidationException(
1166
                "Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " .
1167
                "you need to change the ClassName before you can write it"
1168
            );
1169
        }
1170
1171
        // Note: Validation can only be disabled at the global level, not per-model
1172
        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...
1173
            $result = $this->validate();
1174
            if (!$result->isValid()) {
1175
                return new ValidationException($result);
1176
            }
1177
        }
1178
        return null;
1179
    }
1180
1181
    /**
1182
     * Prepare an object prior to write
1183
     *
1184
     * @throws ValidationException
1185
     */
1186
    protected function preWrite()
1187
    {
1188
        // Validate this object
1189
        if ($writeException = $this->validateWrite()) {
1190
            // Used by DODs to clean up after themselves, eg, Versioned
1191
            $this->invokeWithExtensions('onAfterSkippedWrite');
1192
            throw $writeException;
1193
        }
1194
1195
        // Check onBeforeWrite
1196
        $this->brokenOnWrite = true;
1197
        $this->onBeforeWrite();
1198
        if ($this->brokenOnWrite) {
1199
            user_error(static::class . " has a broken onBeforeWrite() function."
1200
                . " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
1201
        }
1202
    }
1203
1204
    /**
1205
     * Detects and updates all changes made to this object
1206
     *
1207
     * @param bool $forceChanges If set to true, force all fields to be treated as changed
1208
     * @return bool True if any changes are detected
1209
     */
1210
    protected function updateChanges($forceChanges = false)
1211
    {
1212
        if ($forceChanges) {
1213
            // Force changes, but only for loaded fields
1214
            foreach ($this->record as $field => $value) {
1215
                $this->changed[$field] = static::CHANGE_VALUE;
1216
            }
1217
            return true;
1218
        }
1219
        return $this->isChanged();
1220
    }
1221
1222
    /**
1223
     * Writes a subset of changes for a specific table to the given manipulation
1224
     *
1225
     * @param string $baseTable Base table
1226
     * @param string $now Timestamp to use for the current time
1227
     * @param bool $isNewRecord Whether this should be treated as a new record write
1228
     * @param array $manipulation Manipulation to write to
1229
     * @param string $class Class of table to manipulate
1230
     */
1231
    protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class)
1232
    {
1233
        $schema = $this->getSchema();
1234
        $table = $schema->tableName($class);
1235
        $manipulation[$table] = array();
1236
1237
        // Extract records for this table
1238
        foreach ($this->record as $fieldName => $fieldValue) {
1239
            // we're not attempting to reset the BaseTable->ID
1240
            // Ignore unchanged fields or attempts to reset the BaseTable->ID
1241
            if (empty($this->changed[$fieldName]) || ($table === $baseTable && $fieldName === 'ID')) {
1242
                continue;
1243
            }
1244
1245
            // Ensure this field pertains to this table
1246
            $specification = $schema->fieldSpec($class, $fieldName, DataObjectSchema::DB_ONLY | DataObjectSchema::UNINHERITED);
1247
            if (!$specification) {
1248
                continue;
1249
            }
1250
1251
            // if database column doesn't correlate to a DBField instance...
1252
            $fieldObj = $this->dbObject($fieldName);
1253
            if (!$fieldObj) {
1254
                $fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
1255
            }
1256
1257
            // Write to manipulation
1258
            $fieldObj->writeToManipulation($manipulation[$table]);
1259
        }
1260
1261
        // Ensure update of Created and LastEdited columns
1262
        if ($baseTable === $table) {
1263
            $manipulation[$table]['fields']['LastEdited'] = $now;
1264
            if ($isNewRecord) {
1265
                $manipulation[$table]['fields']['Created']
1266
                    = empty($this->record['Created'])
1267
                        ? $now
1268
                        : $this->record['Created'];
1269
                $manipulation[$table]['fields']['ClassName'] = static::class;
1270
            }
1271
        }
1272
1273
        // Inserts done one the base table are performed in another step, so the manipulation should instead
1274
        // attempt an update, as though it were a normal update.
1275
        $manipulation[$table]['command'] = $isNewRecord ? 'insert' : 'update';
1276
        $manipulation[$table]['id'] = $this->record['ID'];
1277
        $manipulation[$table]['class'] = $class;
1278
    }
1279
1280
    /**
1281
     * Ensures that a blank base record exists with the basic fixed fields for this dataobject
1282
     *
1283
     * Does nothing if an ID is already assigned for this record
1284
     *
1285
     * @param string $baseTable Base table
1286
     * @param string $now Timestamp to use for the current time
1287
     */
1288
    protected function writeBaseRecord($baseTable, $now)
1289
    {
1290
        // Generate new ID if not specified
1291
        if ($this->isInDB()) {
1292
            return;
1293
        }
1294
1295
        // Perform an insert on the base table
1296
        $insert = new SQLInsert('"' . $baseTable . '"');
1297
        $insert
1298
            ->assign('"Created"', $now)
1299
            ->execute();
1300
        $this->changed['ID'] = self::CHANGE_VALUE;
1301
        $this->record['ID'] = DB::get_generated_id($baseTable);
1302
    }
1303
1304
    /**
1305
     * Generate and write the database manipulation for all changed fields
1306
     *
1307
     * @param string $baseTable Base table
1308
     * @param string $now Timestamp to use for the current time
1309
     * @param bool $isNewRecord If this is a new record
1310
     * @throws InvalidArgumentException
1311
     */
1312
    protected function writeManipulation($baseTable, $now, $isNewRecord)
1313
    {
1314
        // Generate database manipulations for each class
1315
        $manipulation = array();
1316
        foreach (ClassInfo::ancestry(static::class, true) as $class) {
1317
            $this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
1318
        }
1319
1320
        // Allow extensions to extend this manipulation
1321
        $this->extend('augmentWrite', $manipulation);
1322
1323
        // New records have their insert into the base data table done first, so that they can pass the
1324
        // generated ID on to the rest of the manipulation
1325
        if ($isNewRecord) {
1326
            $manipulation[$baseTable]['command'] = 'update';
1327
        }
1328
1329
        // Make sure none of our field assignment are arrays
1330
        foreach ($manipulation as $tableManipulation) {
1331
            if (!isset($tableManipulation['fields'])) {
1332
                continue;
1333
            }
1334
            foreach ($tableManipulation['fields'] as $fieldName => $fieldValue) {
1335
                if (is_array($fieldValue)) {
1336
                    $dbObject = $this->dbObject($fieldName);
1337
                    // If the field allows non-scalar values we'll let it do dynamic assignments
1338
                    if ($dbObject && $dbObject->scalarValueOnly()) {
1339
                        throw new InvalidArgumentException(
1340
                            'DataObject::writeManipulation: parameterised field assignments are disallowed'
1341
                        );
1342
                    }
1343
                }
1344
            }
1345
        }
1346
1347
        // Perform the manipulation
1348
        DB::manipulate($manipulation);
1349
    }
1350
1351
    /**
1352
     * Writes all changes to this object to the database.
1353
     *  - It will insert a record whenever ID isn't set, otherwise update.
1354
     *  - All relevant tables will be updated.
1355
     *  - $this->onBeforeWrite() gets called beforehand.
1356
     *  - Extensions such as Versioned will ammend the database-write to ensure that a version is saved.
1357
     *
1358
     *  @uses DataExtension->augmentWrite()
1359
     *
1360
     * @param boolean $showDebug Show debugging information
1361
     * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
1362
     * @param boolean $forceWrite Write to database even if there are no changes
1363
     * @param boolean $writeComponents Call write() on all associated component instances which were previously
1364
     *                                 retrieved through {@link getComponent()}, {@link getComponents()} or
1365
     *                                 {@link getManyManyComponents()} (Default: false)
1366
     * @return int The ID of the record
1367
     * @throws ValidationException Exception that can be caught and handled by the calling function
1368
     */
1369
    public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false)
1370
    {
1371
        $now = DBDatetime::now()->Rfc2822();
1372
1373
        // Execute pre-write tasks
1374
        $this->preWrite();
1375
1376
        // Check if we are doing an update or an insert
1377
        $isNewRecord = !$this->isInDB() || $forceInsert;
1378
1379
        // Check changes exist, abort if there are none
1380
        $hasChanges = $this->updateChanges($isNewRecord);
1381
        if ($hasChanges || $forceWrite || $isNewRecord) {
1382
            // Ensure Created and LastEdited are populated
1383
            if (!isset($this->record['Created'])) {
1384
                $this->record['Created'] = $now;
1385
            }
1386
            $this->record['LastEdited'] = $now;
1387
1388
            // New records have their insert into the base data table done first, so that they can pass the
1389
            // generated primary key on to the rest of the manipulation
1390
            $baseTable = $this->baseTable();
1391
            $this->writeBaseRecord($baseTable, $now);
1392
1393
            // Write the DB manipulation for all changed fields
1394
            $this->writeManipulation($baseTable, $now, $isNewRecord);
1395
1396
            // If there's any relations that couldn't be saved before, save them now (we have an ID here)
1397
            $this->writeRelations();
1398
            $this->onAfterWrite();
1399
            $this->changed = array();
1400
        } else {
1401
            if ($showDebug) {
1402
                Debug::message("no changes for DataObject");
1403
            }
1404
1405
            // Used by DODs to clean up after themselves, eg, Versioned
1406
            $this->invokeWithExtensions('onAfterSkippedWrite');
1407
        }
1408
1409
        // Write relations as necessary
1410
        if ($writeComponents) {
1411
            $this->writeComponents(true);
1412
        }
1413
1414
        // Clears the cache for this object so get_one returns the correct object.
1415
        $this->flushCache();
1416
1417
        return $this->record['ID'];
1418
    }
1419
1420
    /**
1421
     * Writes cached relation lists to the database, if possible
1422
     */
1423
    public function writeRelations()
1424
    {
1425
        if (!$this->isInDB()) {
1426
            return;
1427
        }
1428
1429
        // If there's any relations that couldn't be saved before, save them now (we have an ID here)
1430
        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...
1431
            foreach ($this->unsavedRelations as $name => $list) {
1432
                $list->changeToList($this->$name());
1433
            }
1434
            $this->unsavedRelations = array();
1435
        }
1436
    }
1437
1438
    /**
1439
     * Write the cached components to the database. Cached components could refer to two different instances of the
1440
     * same record.
1441
     *
1442
     * @param bool $recursive Recursively write components
1443
     * @return DataObject $this
1444
     */
1445
    public function writeComponents($recursive = false)
1446
    {
1447
        if ($this->components) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->components of type SilverStripe\ORM\DataObject[] 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...
1448
            foreach ($this->components as $component) {
1449
                $component->write(false, false, false, $recursive);
1450
            }
1451
        }
1452
1453
        if ($join = $this->getJoin()) {
1454
            $join->write(false, false, false, $recursive);
1455
        }
1456
1457
        return $this;
1458
    }
1459
1460
    /**
1461
     * Delete this data object.
1462
     * $this->onBeforeDelete() gets called.
1463
     * Note that in Versioned objects, both Stage and Live will be deleted.
1464
     *  @uses DataExtension->augmentSQL()
1465
     */
1466
    public function delete()
1467
    {
1468
        $this->brokenOnDelete = true;
1469
        $this->onBeforeDelete();
1470
        if ($this->brokenOnDelete) {
1471
            user_error(static::class . " has a broken onBeforeDelete() function."
1472
                . " Make sure that you call parent::onBeforeDelete().", E_USER_ERROR);
1473
        }
1474
1475
        // Deleting a record without an ID shouldn't do anything
1476
        if (!$this->ID) {
1477
            throw new LogicException("DataObject::delete() called on a DataObject without an ID");
1478
        }
1479
1480
        // TODO: This is quite ugly.  To improve:
1481
        //  - move the details of the delete code in the DataQuery system
1482
        //  - update the code to just delete the base table, and rely on cascading deletes in the DB to do the rest
1483
        //    obviously, that means getting requireTable() to configure cascading deletes ;-)
1484
        $srcQuery = DataList::create(static::class)
1485
            ->filter('ID', $this->ID)
1486
            ->dataQuery()
1487
            ->query();
1488
        $queriedTables = $srcQuery->queriedTables();
1489
        $this->extend('updateDeleteTables', $queriedTables, $srcQuery);
1490
        foreach ($queriedTables as $table) {
1491
            $delete = SQLDelete::create("\"$table\"", array('"ID"' => $this->ID));
1492
            $this->extend('updateDeleteTable', $delete, $table, $queriedTables, $srcQuery);
1493
            $delete->execute();
1494
        }
1495
        // Remove this item out of any caches
1496
        $this->flushCache();
1497
1498
        $this->onAfterDelete();
1499
1500
        $this->OldID = $this->ID;
1501
        $this->ID = 0;
1502
    }
1503
1504
    /**
1505
     * Delete the record with the given ID.
1506
     *
1507
     * @param string $className The class name of the record to be deleted
1508
     * @param int $id ID of record to be deleted
1509
     */
1510
    public static function delete_by_id($className, $id)
1511
    {
1512
        $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...
1513
        if ($obj) {
0 ignored issues
show
introduced by
$obj is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
1514
            $obj->delete();
1515
        } else {
1516
            user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
1517
        }
1518
    }
1519
1520
    /**
1521
     * Get the class ancestry, including the current class name.
1522
     * The ancestry will be returned as an array of class names, where the 0th element
1523
     * will be the class that inherits directly from DataObject, and the last element
1524
     * will be the current class.
1525
     *
1526
     * @return array Class ancestry
1527
     */
1528
    public function getClassAncestry()
1529
    {
1530
        return ClassInfo::ancestry(static::class);
1531
    }
1532
1533
    /**
1534
     * Return a component object from a one to one relationship, as a DataObject.
1535
     * If no component is available, an 'empty component' will be returned for
1536
     * non-polymorphic relations, or for polymorphic relations with a class set.
1537
     *
1538
     * @param string $componentName Name of the component
1539
     * @return DataObject The component object. It's exact type will be that of the component.
1540
     * @throws Exception
1541
     */
1542
    public function getComponent($componentName)
1543
    {
1544
        if (isset($this->components[$componentName])) {
1545
            return $this->components[$componentName];
1546
        }
1547
1548
        $schema = static::getSchema();
1549
        if ($class = $schema->hasOneComponent(static::class, $componentName)) {
1550
            $joinField = $componentName . 'ID';
1551
            $joinID    = $this->getField($joinField);
1552
1553
            // Extract class name for polymorphic relations
1554
            if ($class === self::class) {
1555
                $class = $this->getField($componentName . 'Class');
1556
                if (empty($class)) {
1557
                    return null;
1558
                }
1559
            }
1560
1561
            if ($joinID) {
1562
                // Ensure that the selected object originates from the same stage, subsite, etc
1563
                $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...
1564
                    ->filter('ID', $joinID)
1565
                    ->setDataQueryParam($this->getInheritableQueryParams())
1566
                    ->first();
1567
            }
1568
1569
            if (empty($component)) {
1570
                $component = Injector::inst()->create($class);
1571
            }
1572
        } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
1573
            $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
1574
            $joinID = $this->ID;
1575
1576
            if ($joinID) {
1577
                // Prepare filter for appropriate join type
1578
                if ($polymorphic) {
1579
                    $filter = array(
1580
                        "{$joinField}ID" => $joinID,
1581
                        "{$joinField}Class" => static::class,
1582
                    );
1583
                } else {
1584
                    $filter = array(
1585
                        $joinField => $joinID
1586
                    );
1587
                }
1588
1589
                // Ensure that the selected object originates from the same stage, subsite, etc
1590
                $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...
1591
                    ->filter($filter)
1592
                    ->setDataQueryParam($this->getInheritableQueryParams())
1593
                    ->first();
1594
            }
1595
1596
            if (empty($component)) {
1597
                $component = Injector::inst()->create($class);
1598
                if ($polymorphic) {
1599
                    $component->{$joinField . 'ID'} = $this->ID;
1600
                    $component->{$joinField . 'Class'} = static::class;
1601
                } else {
1602
                    $component->$joinField = $this->ID;
1603
                }
1604
            }
1605
        } else {
1606
            throw new InvalidArgumentException(
1607
                "DataObject->getComponent(): Could not find component '$componentName'."
1608
            );
1609
        }
1610
1611
        $this->components[$componentName] = $component;
1612
        return $component;
1613
    }
1614
1615
    /**
1616
     * Returns a one-to-many relation as a HasManyList
1617
     *
1618
     * @param string $componentName Name of the component
1619
     * @return HasManyList|UnsavedRelationList The components of the one-to-many relationship.
1620
     */
1621
    public function getComponents($componentName)
1622
    {
1623
        $result = null;
1624
1625
        $schema = $this->getSchema();
1626
        $componentClass = $schema->hasManyComponent(static::class, $componentName);
1627
        if (!$componentClass) {
1628
            throw new InvalidArgumentException(sprintf(
1629
                "DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
1630
                $componentName,
1631
                static::class
1632
            ));
1633
        }
1634
1635
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
1636
        if (!$this->ID) {
1637
            if (!isset($this->unsavedRelations[$componentName])) {
1638
                $this->unsavedRelations[$componentName] =
1639
                    new UnsavedRelationList(static::class, $componentName, $componentClass);
1640
            }
1641
            return $this->unsavedRelations[$componentName];
1642
        }
1643
1644
        // Determine type and nature of foreign relation
1645
        $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'has_many', $polymorphic);
1646
        /** @var HasManyList $result */
1647
        if ($polymorphic) {
1648
            $result = PolymorphicHasManyList::create($componentClass, $joinField, static::class);
1649
        } else {
1650
            $result = HasManyList::create($componentClass, $joinField);
1651
        }
1652
1653
        return $result
1654
            ->setDataQueryParam($this->getInheritableQueryParams())
1655
            ->forForeignID($this->ID);
1656
    }
1657
1658
    /**
1659
     * Find the foreign class of a relation on this DataObject, regardless of the relation type.
1660
     *
1661
     * @param string $relationName Relation name.
1662
     * @return string Class name, or null if not found.
1663
     */
1664
    public function getRelationClass($relationName)
1665
    {
1666
        // Parse many_many
1667
        $manyManyComponent = $this->getSchema()->manyManyComponent(static::class, $relationName);
1668
        if ($manyManyComponent) {
1669
            return $manyManyComponent['childClass'];
1670
        }
1671
1672
        // Go through all relationship configuration fields.
1673
        $config = $this->config();
1674
        $candidates = array_merge(
1675
            ($relations = $config->get('has_one')) ? $relations : array(),
1676
            ($relations = $config->get('has_many')) ? $relations : array(),
1677
            ($relations = $config->get('belongs_to')) ? $relations : array()
1678
        );
1679
1680
        if (isset($candidates[$relationName])) {
1681
            $remoteClass = $candidates[$relationName];
1682
1683
            // If dot notation is present, extract just the first part that contains the class.
1684
            if (($fieldPos = strpos($remoteClass, '.'))!==false) {
1685
                return substr($remoteClass, 0, $fieldPos);
1686
            }
1687
1688
            // Otherwise just return the class
1689
            return $remoteClass;
1690
        }
1691
1692
        return null;
1693
    }
1694
1695
    /**
1696
     * Given a relation name, determine the relation type
1697
     *
1698
     * @param string $component Name of component
1699
     * @return string has_one, has_many, many_many, belongs_many_many or belongs_to
1700
     */
1701
    public function getRelationType($component)
1702
    {
1703
        $types = array('has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to');
1704
        $config = $this->config();
1705
        foreach ($types as $type) {
1706
            $relations = $config->get($type);
1707
            if ($relations && isset($relations[$component])) {
1708
                return $type;
1709
            }
1710
        }
1711
        return null;
1712
    }
1713
1714
    /**
1715
     * Given a relation declared on a remote class, generate a substitute component for the opposite
1716
     * side of the relation.
1717
     *
1718
     * Notes on behaviour:
1719
     *  - This can still be used on components that are defined on both sides, but do not need to be.
1720
     *  - All has_ones on remote class will be treated as local has_many, even if they are belongs_to
1721
     *  - Cannot be used on polymorphic relationships
1722
     *  - Cannot be used on unsaved objects.
1723
     *
1724
     * @param string $remoteClass
1725
     * @param string $remoteRelation
1726
     * @return DataList|DataObject The component, either as a list or single object
1727
     * @throws BadMethodCallException
1728
     * @throws InvalidArgumentException
1729
     */
1730
    public function inferReciprocalComponent($remoteClass, $remoteRelation)
1731
    {
1732
        $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...
1733
        $class = $remote->getRelationClass($remoteRelation);
1734
        $schema = static::getSchema();
1735
1736
        // Validate arguments
1737
        if (!$this->isInDB()) {
1738
            throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects");
1739
        }
1740
        if (empty($class)) {
1741
            throw new InvalidArgumentException(sprintf(
1742
                "%s invoked with invalid relation %s.%s",
1743
                __METHOD__,
1744
                $remoteClass,
1745
                $remoteRelation
1746
            ));
1747
        }
1748
        if ($class === self::class) {
1749
            throw new InvalidArgumentException(sprintf(
1750
                "%s cannot generate opposite component of relation %s.%s as it is polymorphic. " .
1751
                "This method does not support polymorphic relationships",
1752
                __METHOD__,
1753
                $remoteClass,
1754
                $remoteRelation
1755
            ));
1756
        }
1757
        if (!is_a($this, $class, true)) {
1758
            throw new InvalidArgumentException(sprintf(
1759
                "Relation %s on %s does not refer to objects of type %s",
1760
                $remoteRelation,
1761
                $remoteClass,
1762
                static::class
1763
            ));
1764
        }
1765
1766
        // Check the relation type to mock
1767
        $relationType = $remote->getRelationType($remoteRelation);
1768
        switch ($relationType) {
1769
            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...
1770
                // Mock has_many
1771
                $joinField = "{$remoteRelation}ID";
1772
                $componentClass = $schema->classForField($remoteClass, $joinField);
1773
                $result = HasManyList::create($componentClass, $joinField);
1774
                return $result
1775
                    ->setDataQueryParam($this->getInheritableQueryParams())
1776
                    ->forForeignID($this->ID);
1777
            }
1778
            case 'belongs_to':
1779
            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...
1780
                // These relations must have a has_one on the other end, so find it
1781
                $joinField = $schema->getRemoteJoinField($remoteClass, $remoteRelation, $relationType, $polymorphic);
1782
                if ($polymorphic) {
1783
                    throw new InvalidArgumentException(sprintf(
1784
                        "%s cannot generate opposite component of relation %s.%s, as the other end appears" .
1785
                        "to be a has_one polymorphic. This method does not support polymorphic relationships",
1786
                        __METHOD__,
1787
                        $remoteClass,
1788
                        $remoteRelation
1789
                    ));
1790
                }
1791
                $joinID = $this->getField($joinField);
1792
                if (empty($joinID)) {
1793
                    return null;
1794
                }
1795
                // Get object by joined ID
1796
                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...
1797
                    ->filter('ID', $joinID)
1798
                    ->setDataQueryParam($this->getInheritableQueryParams())
1799
                    ->first();
1800
            }
1801
            case 'many_many':
1802
            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...
1803
                // Get components and extra fields from parent
1804
                $manyMany = $remote->getSchema()->manyManyComponent($remoteClass, $remoteRelation);
1805
                $extraFields = $schema->manyManyExtraFieldsForComponent($remoteClass, $remoteRelation) ?: array();
1806
1807
                // Reverse parent and component fields and create an inverse ManyManyList
1808
                /** @var RelationList $result */
1809
                $result = Injector::inst()->create(
1810
                    $manyMany['relationClass'],
1811
                    $manyMany['parentClass'], // Substitute parent class for dataClass
1812
                    $manyMany['join'],
1813
                    $manyMany['parentField'], // Reversed parent / child field
1814
                    $manyMany['childField'], // Reversed parent / child field
1815
                    $extraFields
1816
                );
1817
                $this->extend('updateManyManyComponents', $result);
1818
1819
                // If this is called on a singleton, then we return an 'orphaned relation' that can have the
1820
                // foreignID set elsewhere.
1821
                return $result
1822
                    ->setDataQueryParam($this->getInheritableQueryParams())
1823
                    ->forForeignID($this->ID);
1824
            }
1825
            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...
1826
                return null;
1827
            }
1828
        }
1829
    }
1830
1831
    /**
1832
     * Returns a many-to-many component, as a ManyManyList.
1833
     * @param string $componentName Name of the many-many component
1834
     * @return RelationList|UnsavedRelationList The set of components
1835
     */
1836
    public function getManyManyComponents($componentName)
1837
    {
1838
        $schema = static::getSchema();
1839
        $manyManyComponent = $schema->manyManyComponent(static::class, $componentName);
1840
        if (!$manyManyComponent) {
1841
            throw new InvalidArgumentException(sprintf(
1842
                "DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'",
1843
                $componentName,
1844
                static::class
1845
            ));
1846
        }
1847
1848
        // If we haven't been written yet, we can't save these relations, so use a list that handles this case
1849
        if (!$this->ID) {
1850
            if (!isset($this->unsavedRelations[$componentName])) {
1851
                $this->unsavedRelations[$componentName] =
1852
                    new UnsavedRelationList($manyManyComponent['parentClass'], $componentName, $manyManyComponent['childClass']);
1853
            }
1854
            return $this->unsavedRelations[$componentName];
1855
        }
1856
1857
        $extraFields = $schema->manyManyExtraFieldsForComponent(static::class, $componentName) ?: array();
1858
        /** @var RelationList $result */
1859
        $result = Injector::inst()->create(
1860
            $manyManyComponent['relationClass'],
1861
            $manyManyComponent['childClass'],
1862
            $manyManyComponent['join'],
1863
            $manyManyComponent['childField'],
1864
            $manyManyComponent['parentField'],
1865
            $extraFields
1866
        );
1867
1868
1869
        // Store component data in query meta-data
1870
        $result = $result->alterDataQuery(function ($query) use ($extraFields) {
1871
            /** @var DataQuery $query */
1872
            $query->setQueryParam('Component.ExtraFields', $extraFields);
1873
        });
1874
1875
        $this->extend('updateManyManyComponents', $result);
1876
1877
        // If this is called on a singleton, then we return an 'orphaned relation' that can have the
1878
        // foreignID set elsewhere.
1879
        return $result
1880
            ->setDataQueryParam($this->getInheritableQueryParams())
1881
            ->forForeignID($this->ID);
1882
    }
1883
1884
    /**
1885
     * Return the class of a one-to-one component.  If $component is null, return all of the one-to-one components and
1886
     * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.
1887
     *
1888
     * @return string|array The class of the one-to-one component, or an array of all one-to-one components and
1889
     *                          their classes.
1890
     */
1891
    public function hasOne()
1892
    {
1893
        return (array)$this->config()->get('has_one');
1894
    }
1895
1896
    /**
1897
     * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
1898
     * their class name will be returned.
1899
     *
1900
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1901
     *        the field data stripped off. It defaults to TRUE.
1902
     * @return string|array
1903
     */
1904
    public function belongsTo($classOnly = true)
1905
    {
1906
        $belongsTo = (array)$this->config()->get('belongs_to');
1907
        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...
1908
            return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
1909
        } else {
1910
            return $belongsTo ? $belongsTo : array();
1911
        }
1912
    }
1913
1914
    /**
1915
     * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
1916
     * relationships and their classes will be returned.
1917
     *
1918
     * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1919
     *        the field data stripped off. It defaults to TRUE.
1920
     * @return string|array|false
1921
     */
1922
    public function hasMany($classOnly = true)
1923
    {
1924
        $hasMany = (array)$this->config()->get('has_many');
1925
        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...
1926
            return preg_replace('/(.+)?\..+/', '$1', $hasMany);
1927
        } else {
1928
            return $hasMany ? $hasMany : array();
1929
        }
1930
    }
1931
1932
    /**
1933
     * Return the many-to-many extra fields specification.
1934
     *
1935
     * If you don't specify a component name, it returns all
1936
     * extra fields for all components available.
1937
     *
1938
     * @return array|null
1939
     */
1940
    public function manyManyExtraFields()
1941
    {
1942
        return $this->config()->get('many_many_extraFields');
1943
    }
1944
1945
    /**
1946
     * Return information about a many-to-many component.
1947
     * The return value is an array of (parentclass, childclass).  If $component is null, then all many-many
1948
     * components are returned.
1949
     *
1950
     * @see DataObjectSchema::manyManyComponent()
1951
     * @return array|null An array of (parentclass, childclass), or an array of all many-many components
1952
     */
1953
    public function manyMany()
1954
    {
1955
        $config = $this->config();
1956
        $manyManys = (array)$config->get('many_many');
1957
        $belongsManyManys = (array)$config->get('belongs_many_many');
1958
        $items = array_merge($manyManys, $belongsManyManys);
1959
        return $items;
1960
    }
1961
1962
    /**
1963
     * This returns an array (if it exists) describing the database extensions that are required, or false if none
1964
     *
1965
     * This is experimental, and is currently only a Postgres-specific enhancement.
1966
     *
1967
     * @param string $class
1968
     * @return array|false
1969
     */
1970
    public function database_extensions($class)
1971
    {
1972
        $extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
1973
        if ($extensions) {
1974
            return $extensions;
1975
        } else {
1976
            return false;
1977
        }
1978
    }
1979
1980
    /**
1981
     * Generates a SearchContext to be used for building and processing
1982
     * a generic search form for properties on this object.
1983
     *
1984
     * @return SearchContext
1985
     */
1986
    public function getDefaultSearchContext()
1987
    {
1988
        return new SearchContext(
1989
            static::class,
1990
            $this->scaffoldSearchFields(),
1991
            $this->defaultSearchFilters()
1992
        );
1993
    }
1994
1995
    /**
1996
     * Determine which properties on the DataObject are
1997
     * searchable, and map them to their default {@link FormField}
1998
     * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
1999
     *
2000
     * Some additional logic is included for switching field labels, based on
2001
     * how generic or specific the field type is.
2002
     *
2003
     * Used by {@link SearchContext}.
2004
     *
2005
     * @param array $_params
2006
     *   'fieldClasses': Associative array of field names as keys and FormField classes as values
2007
     *   'restrictFields': Numeric array of a field name whitelist
2008
     * @return FieldList
2009
     */
2010
    public function scaffoldSearchFields($_params = null)
2011
    {
2012
        $params = array_merge(
2013
            array(
2014
                'fieldClasses' => false,
2015
                'restrictFields' => false
2016
            ),
2017
            (array)$_params
2018
        );
2019
        $fields = new FieldList();
2020
        foreach ($this->searchableFields() as $fieldName => $spec) {
2021
            if ($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) {
2022
                continue;
2023
            }
2024
2025
            // If a custom fieldclass is provided as a string, use it
2026
            $field = null;
2027
            if ($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
2028
                $fieldClass = $params['fieldClasses'][$fieldName];
2029
                $field = new $fieldClass($fieldName);
2030
            // If we explicitly set a field, then construct that
2031
            } elseif (isset($spec['field'])) {
2032
                // If it's a string, use it as a class name and construct
2033
                if (is_string($spec['field'])) {
2034
                    $fieldClass = $spec['field'];
2035
                    $field = new $fieldClass($fieldName);
2036
2037
                // If it's a FormField object, then just use that object directly.
2038
                } elseif ($spec['field'] instanceof FormField) {
2039
                    $field = $spec['field'];
2040
2041
                // Otherwise we have a bug
2042
                } else {
2043
                    user_error("Bad value for searchable_fields, 'field' value: "
2044
                        . var_export($spec['field'], true), E_USER_WARNING);
2045
                }
2046
2047
            // Otherwise, use the database field's scaffolder
2048
            } else {
2049
                $field = $this->relObject($fieldName)->scaffoldSearchField();
2050
            }
2051
2052
            // Allow fields to opt out of search
2053
            if (!$field) {
2054
                continue;
2055
            }
2056
2057
            if (strstr($fieldName, '.')) {
2058
                $field->setName(str_replace('.', '__', $fieldName));
2059
            }
2060
            $field->setTitle($spec['title']);
2061
2062
            $fields->push($field);
2063
        }
2064
        return $fields;
2065
    }
2066
2067
    /**
2068
     * Scaffold a simple edit form for all properties on this dataobject,
2069
     * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
2070
     * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
2071
     *
2072
     * @uses FormScaffolder
2073
     *
2074
     * @param array $_params Associative array passing through properties to {@link FormScaffolder}.
2075
     * @return FieldList
2076
     */
2077
    public function scaffoldFormFields($_params = null)
2078
    {
2079
        $params = array_merge(
2080
            array(
2081
                'tabbed' => false,
2082
                'includeRelations' => false,
2083
                'restrictFields' => false,
2084
                'fieldClasses' => false,
2085
                'ajaxSafe' => false
2086
            ),
2087
            (array)$_params
2088
        );
2089
2090
        $fs = FormScaffolder::create($this);
2091
        $fs->tabbed = $params['tabbed'];
2092
        $fs->includeRelations = $params['includeRelations'];
2093
        $fs->restrictFields = $params['restrictFields'];
2094
        $fs->fieldClasses = $params['fieldClasses'];
2095
        $fs->ajaxSafe = $params['ajaxSafe'];
2096
2097
        return $fs->getFieldList();
2098
    }
2099
2100
    /**
2101
     * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
2102
     * being called on extensions
2103
     *
2104
     * @param callable $callback The callback to execute
2105
     */
2106
    protected function beforeUpdateCMSFields($callback)
2107
    {
2108
        $this->beforeExtending('updateCMSFields', $callback);
2109
    }
2110
2111
    /**
2112
     * Centerpiece of every data administration interface in Silverstripe,
2113
     * which returns a {@link FieldList} suitable for a {@link Form} object.
2114
     * If not overloaded, we're using {@link scaffoldFormFields()} to automatically
2115
     * generate this set. To customize, overload this method in a subclass
2116
     * or extended onto it by using {@link DataExtension->updateCMSFields()}.
2117
     *
2118
     * <code>
2119
     * class MyCustomClass extends DataObject {
2120
     *  static $db = array('CustomProperty'=>'Boolean');
2121
     *
2122
     *  function getCMSFields() {
2123
     *    $fields = parent::getCMSFields();
2124
     *    $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
2125
     *    return $fields;
2126
     *  }
2127
     * }
2128
     * </code>
2129
     *
2130
     * @see Good example of complex FormField building: SiteTree::getCMSFields()
2131
     *
2132
     * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.
2133
     */
2134
    public function getCMSFields()
2135
    {
2136
        $tabbedFields = $this->scaffoldFormFields(array(
2137
            // Don't allow has_many/many_many relationship editing before the record is first saved
2138
            'includeRelations' => ($this->ID > 0),
2139
            'tabbed' => true,
2140
            'ajaxSafe' => true
2141
        ));
2142
2143
        $this->extend('updateCMSFields', $tabbedFields);
2144
2145
        return $tabbedFields;
2146
    }
2147
2148
    /**
2149
     * need to be overload by solid dataobject, so that the customised actions of that dataobject,
2150
     * including that dataobject's extensions customised actions could be added to the EditForm.
2151
     *
2152
     * @return FieldList an Empty FieldList(); need to be overload by solid subclass
2153
     */
2154
    public function getCMSActions()
2155
    {
2156
        $actions = new FieldList();
2157
        $this->extend('updateCMSActions', $actions);
2158
        return $actions;
2159
    }
2160
2161
2162
    /**
2163
     * Used for simple frontend forms without relation editing
2164
     * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()}
2165
     * by default. To customize, either overload this method in your
2166
     * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.
2167
     *
2168
     * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API
2169
     *
2170
     * @param array $params See {@link scaffoldFormFields()}
2171
     * @return FieldList Always returns a simple field collection without TabSet.
2172
     */
2173
    public function getFrontEndFields($params = null)
2174
    {
2175
        $untabbedFields = $this->scaffoldFormFields($params);
2176
        $this->extend('updateFrontEndFields', $untabbedFields);
2177
2178
        return $untabbedFields;
2179
    }
2180
2181
    public function getViewerTemplates($suffix = '')
2182
    {
2183
        return SSViewer::get_templates_by_class(static::class, $suffix, $this->baseClass());
2184
    }
2185
2186
    /**
2187
     * Gets the value of a field.
2188
     * Called by {@link __get()} and any getFieldName() methods you might create.
2189
     *
2190
     * @param string $field The name of the field
2191
     * @return mixed The field value
2192
     */
2193
    public function getField($field)
2194
    {
2195
        // If we already have an object in $this->record, then we should just return that
2196
        if (isset($this->record[$field]) && is_object($this->record[$field])) {
2197
            return $this->record[$field];
2198
        }
2199
2200
        // Do we have a field that needs to be lazy loaded?
2201
        if (isset($this->record[$field . '_Lazy'])) {
2202
            $tableClass = $this->record[$field . '_Lazy'];
2203
            $this->loadLazyFields($tableClass);
2204
        }
2205
2206
        // In case of complex fields, return the DBField object
2207
        if (static::getSchema()->compositeField(static::class, $field)) {
2208
            $this->record[$field] = $this->dbObject($field);
2209
        }
2210
2211
        return isset($this->record[$field]) ? $this->record[$field] : null;
2212
    }
2213
2214
    /**
2215
     * Loads all the stub fields that an initial lazy load didn't load fully.
2216
     *
2217
     * @param string $class Class to load the values from. Others are joined as required.
2218
     * Not specifying a tableClass will load all lazy fields from all tables.
2219
     * @return bool Flag if lazy loading succeeded
2220
     */
2221
    protected function loadLazyFields($class = null)
2222
    {
2223
        if (!$this->isInDB() || !is_numeric($this->ID)) {
2224
            return false;
2225
        }
2226
2227
        if (!$class) {
2228
            $loaded = array();
2229
2230
            foreach ($this->record as $key => $value) {
2231
                if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
2232
                    $this->loadLazyFields($value);
2233
                    $loaded[$value] = $value;
2234
                }
2235
            }
2236
2237
            return false;
2238
        }
2239
2240
        $dataQuery = new DataQuery($class);
2241
2242
        // Reset query parameter context to that of this DataObject
2243
        if ($params = $this->getSourceQueryParams()) {
2244
            foreach ($params as $key => $value) {
2245
                $dataQuery->setQueryParam($key, $value);
2246
            }
2247
        }
2248
2249
        // Limit query to the current record, unless it has the Versioned extension,
2250
        // in which case it requires special handling through augmentLoadLazyFields()
2251
        $schema = static::getSchema();
2252
        $baseIDColumn = $schema->sqlColumnForField($this, 'ID');
2253
        $dataQuery->where([
2254
            $baseIDColumn => $this->record['ID']
2255
        ])->limit(1);
2256
2257
        $columns = array();
2258
2259
        // Add SQL for fields, both simple & multi-value
2260
        // TODO: This is copy & pasted from buildSQL(), it could be moved into a method
2261
        $databaseFields = $schema->databaseFields($class, false);
2262
        foreach ($databaseFields as $k => $v) {
2263
            if (!isset($this->record[$k]) || $this->record[$k] === null) {
2264
                $columns[] = $k;
2265
            }
2266
        }
2267
2268
        if ($columns) {
2269
            $query = $dataQuery->query();
2270
            $this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
2271
            $this->extend('augmentSQL', $query, $dataQuery);
2272
2273
            $dataQuery->setQueriedColumns($columns);
2274
            $newData = $dataQuery->execute()->record();
2275
2276
            // Load the data into record
2277
            if ($newData) {
2278
                foreach ($newData as $k => $v) {
2279
                    if (in_array($k, $columns)) {
2280
                        $this->record[$k] = $v;
2281
                        $this->original[$k] = $v;
2282
                        unset($this->record[$k . '_Lazy']);
2283
                    }
2284
                }
2285
2286
            // No data means that the query returned nothing; assign 'null' to all the requested fields
2287
            } else {
2288
                foreach ($columns as $k) {
2289
                    $this->record[$k] = null;
2290
                    $this->original[$k] = null;
2291
                    unset($this->record[$k . '_Lazy']);
2292
                }
2293
            }
2294
        }
2295
        return true;
2296
    }
2297
2298
    /**
2299
     * Return the fields that have changed.
2300
     *
2301
     * The change level affects what the functions defines as "changed":
2302
     * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
2303
     * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
2304
     *   for example a change from 0 to null would not be included.
2305
     *
2306
     * Example return:
2307
     * <code>
2308
     * array(
2309
     *   'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
2310
     * )
2311
     * </code>
2312
     *
2313
     * @param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true
2314
     * to return all database fields, or an array for an explicit filter. false returns all fields.
2315
     * @param int $changeLevel The strictness of what is defined as change. Defaults to strict
2316
     * @return array
2317
     */
2318
    public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT)
2319
    {
2320
        $changedFields = array();
2321
2322
        // Update the changed array with references to changed obj-fields
2323
        foreach ($this->record as $k => $v) {
2324
            // Prevents DBComposite infinite looping on isChanged
2325
            if (is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
2326
                continue;
2327
            }
2328
            if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
2329
                $this->changed[$k] = self::CHANGE_VALUE;
2330
            }
2331
        }
2332
2333
        if (is_array($databaseFieldsOnly)) {
2334
            $fields = array_intersect_key((array)$this->changed, array_flip($databaseFieldsOnly));
2335
        } elseif ($databaseFieldsOnly) {
2336
            $fieldsSpecs = static::getSchema()->fieldSpecs(static::class);
2337
            $fields = array_intersect_key((array)$this->changed, $fieldsSpecs);
2338
        } else {
2339
            $fields = $this->changed;
2340
        }
2341
2342
        // Filter the list to those of a certain change level
2343
        if ($changeLevel > self::CHANGE_STRICT) {
2344
            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...
2345
                foreach ($fields as $name => $level) {
2346
                    if ($level < $changeLevel) {
2347
                        unset($fields[$name]);
2348
                    }
2349
                }
2350
            }
2351
        }
2352
2353
        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...
2354
            foreach ($fields as $name => $level) {
2355
                $changedFields[$name] = array(
2356
                'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
2357
                'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
2358
                'level' => $level
2359
                );
2360
            }
2361
        }
2362
2363
        return $changedFields;
2364
    }
2365
2366
    /**
2367
     * Uses {@link getChangedFields()} to determine if fields have been changed
2368
     * since loading them from the database.
2369
     *
2370
     * @param string $fieldName Name of the database field to check, will check for any if not given
2371
     * @param int $changeLevel See {@link getChangedFields()}
2372
     * @return boolean
2373
     */
2374
    public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT)
2375
    {
2376
        $fields = $fieldName ? array($fieldName) : true;
2377
        $changed = $this->getChangedFields($fields, $changeLevel);
2378
        if (!isset($fieldName)) {
2379
            return !empty($changed);
2380
        } else {
2381
            return array_key_exists($fieldName, $changed);
2382
        }
2383
    }
2384
2385
    /**
2386
     * Set the value of the field
2387
     * Called by {@link __set()} and any setFieldName() methods you might create.
2388
     *
2389
     * @param string $fieldName Name of the field
2390
     * @param mixed $val New field value
2391
     * @return $this
2392
     */
2393
    public function setField($fieldName, $val)
2394
    {
2395
        $this->objCacheClear();
2396
        //if it's a has_one component, destroy the cache
2397
        if (substr($fieldName, -2) == 'ID') {
2398
            unset($this->components[substr($fieldName, 0, -2)]);
2399
        }
2400
2401
        // If we've just lazy-loaded the column, then we need to populate the $original array
2402
        if (isset($this->record[$fieldName . '_Lazy'])) {
2403
            $tableClass = $this->record[$fieldName . '_Lazy'];
2404
            $this->loadLazyFields($tableClass);
2405
        }
2406
2407
        // Situation 1: Passing an DBField
2408
        if ($val instanceof DBField) {
2409
            $val->setName($fieldName);
2410
            $val->saveInto($this);
2411
2412
            // Situation 1a: Composite fields should remain bound in case they are
2413
            // later referenced to update the parent dataobject
2414
            if ($val instanceof DBComposite) {
2415
                $val->bindTo($this);
2416
                $this->record[$fieldName] = $val;
2417
            }
2418
        // Situation 2: Passing a literal or non-DBField object
2419
        } else {
2420
            // If this is a proper database field, we shouldn't be getting non-DBField objects
2421
            if (is_object($val) && static::getSchema()->fieldSpec(static::class, $fieldName)) {
2422
                throw new InvalidArgumentException('DataObject::setField: passed an object that is not a DBField');
2423
            }
2424
2425
            if (!empty($val) && !is_scalar($val)) {
2426
                $dbField = $this->dbObject($fieldName);
2427
                if ($dbField && $dbField->scalarValueOnly()) {
2428
                    throw new InvalidArgumentException(
2429
                        sprintf(
2430
                            'DataObject::setField: %s only accepts scalars',
2431
                            $fieldName
2432
                        )
2433
                    );
2434
                }
2435
            }
2436
2437
            // if a field is not existing or has strictly changed
2438
            if (!isset($this->record[$fieldName]) || $this->record[$fieldName] !== $val) {
2439
                // TODO Add check for php-level defaults which are not set in the db
2440
                // TODO Add check for hidden input-fields (readonly) which are not set in the db
2441
                // At the very least, the type has changed
2442
                $this->changed[$fieldName] = self::CHANGE_STRICT;
2443
2444
                if ((!isset($this->record[$fieldName]) && $val)
2445
                    || (isset($this->record[$fieldName]) && $this->record[$fieldName] != $val)
2446
                ) {
2447
                    // Value has changed as well, not just the type
2448
                    $this->changed[$fieldName] = self::CHANGE_VALUE;
2449
                }
2450
2451
                // Value is always saved back when strict check succeeds.
2452
                $this->record[$fieldName] = $val;
2453
            }
2454
        }
2455
        return $this;
2456
    }
2457
2458
    /**
2459
     * Set the value of the field, using a casting object.
2460
     * This is useful when you aren't sure that a date is in SQL format, for example.
2461
     * setCastedField() can also be used, by forms, to set related data.  For example, uploaded images
2462
     * can be saved into the Image table.
2463
     *
2464
     * @param string $fieldName Name of the field
2465
     * @param mixed $value New field value
2466
     * @return $this
2467
     */
2468
    public function setCastedField($fieldName, $value)
2469
    {
2470
        if (!$fieldName) {
2471
            user_error("DataObject::setCastedField: Called without a fieldName", E_USER_ERROR);
2472
        }
2473
        $fieldObj = $this->dbObject($fieldName);
2474
        if ($fieldObj) {
0 ignored issues
show
introduced by
$fieldObj is of type SilverStripe\ORM\FieldType\DBField, thus it always evaluated to true.
Loading history...
2475
            $fieldObj->setValue($value);
2476
            $fieldObj->saveInto($this);
2477
        } else {
2478
            $this->$fieldName = $value;
2479
        }
2480
        return $this;
2481
    }
2482
2483
    /**
2484
     * {@inheritdoc}
2485
     */
2486
    public function castingHelper($field)
2487
    {
2488
        $fieldSpec = static::getSchema()->fieldSpec(static::class, $field);
2489
        if ($fieldSpec) {
2490
            return $fieldSpec;
2491
        }
2492
2493
        // many_many_extraFields aren't presented by db(), so we check if the source query params
2494
        // provide us with meta-data for a many_many relation we can inspect for extra fields.
2495
        $queryParams = $this->getSourceQueryParams();
2496
        if (!empty($queryParams['Component.ExtraFields'])) {
2497
            $extraFields = $queryParams['Component.ExtraFields'];
2498
2499
            if (isset($extraFields[$field])) {
2500
                return $extraFields[$field];
2501
            }
2502
        }
2503
2504
        return parent::castingHelper($field);
2505
    }
2506
2507
    /**
2508
     * Returns true if the given field exists in a database column on any of
2509
     * the objects tables and optionally look up a dynamic getter with
2510
     * get<fieldName>().
2511
     *
2512
     * @param string $field Name of the field
2513
     * @return boolean True if the given field exists
2514
     */
2515
    public function hasField($field)
2516
    {
2517
        $schema = static::getSchema();
2518
        return (
2519
            array_key_exists($field, $this->record)
2520
            || $schema->fieldSpec(static::class, $field)
2521
            || (substr($field, -2) == 'ID') && $schema->hasOneComponent(static::class, substr($field, 0, -2))
2522
            || $this->hasMethod("get{$field}")
2523
        );
2524
    }
2525
2526
    /**
2527
     * Returns true if the given field exists as a database column
2528
     *
2529
     * @param string $field Name of the field
2530
     *
2531
     * @return boolean
2532
     */
2533
    public function hasDatabaseField($field)
2534
    {
2535
        $spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY);
2536
        return !empty($spec);
2537
    }
2538
2539
    /**
2540
     * Returns true if the member is allowed to do the given action.
2541
     * See {@link extendedCan()} for a more versatile tri-state permission control.
2542
     *
2543
     * @param string $perm The permission to be checked, such as 'View'.
2544
     * @param Member $member The member whose permissions need checking.  Defaults to the currently logged
2545
     * in user.
2546
     * @param array $context Additional $context to pass to extendedCan()
2547
     *
2548
     * @return boolean True if the the member is allowed to do the given action
2549
     */
2550
    public function can($perm, $member = null, $context = array())
2551
    {
2552
        if (!$member) {
2553
            $member = Security::getCurrentUser();
2554
        }
2555
2556
        if ($member && Permission::checkMember($member, "ADMIN")) {
2557
            return true;
2558
        }
2559
2560
        if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
2561
            $method = 'can' . ucfirst($perm);
2562
            return $this->$method($member);
2563
        }
2564
2565
        $results = $this->extendedCan('can', $member);
2566
        if (isset($results)) {
2567
            return $results;
2568
        }
2569
2570
        return ($member && Permission::checkMember($member, $perm));
2571
    }
2572
2573
    /**
2574
     * Process tri-state responses from permission-alterting extensions.  The extensions are
2575
     * expected to return one of three values:
2576
     *
2577
     *  - false: Disallow this permission, regardless of what other extensions say
2578
     *  - true: Allow this permission, as long as no other extensions return false
2579
     *  - NULL: Don't affect the outcome
2580
     *
2581
     * This method itself returns a tri-state value, and is designed to be used like this:
2582
     *
2583
     * <code>
2584
     * $extended = $this->extendedCan('canDoSomething', $member);
2585
     * if($extended !== null) return $extended;
2586
     * else return $normalValue;
2587
     * </code>
2588
     *
2589
     * @param string $methodName Method on the same object, e.g. {@link canEdit()}
2590
     * @param Member|int $member
2591
     * @param array $context Optional context
2592
     * @return boolean|null
2593
     */
2594
    public function extendedCan($methodName, $member, $context = array())
2595
    {
2596
        $results = $this->extend($methodName, $member, $context);
2597
        if ($results && is_array($results)) {
2598
            // Remove NULLs
2599
            $results = array_filter($results, function ($v) {
2600
                return !is_null($v);
2601
            });
2602
            // If there are any non-NULL responses, then return the lowest one of them.
2603
            // If any explicitly deny the permission, then we don't get access
2604
            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...
2605
                return min($results);
2606
            }
2607
        }
2608
        return null;
2609
    }
2610
2611
    /**
2612
     * @param Member $member
2613
     * @return boolean
2614
     */
2615
    public function canView($member = null)
2616
    {
2617
        $extended = $this->extendedCan(__FUNCTION__, $member);
2618
        if ($extended !== null) {
2619
            return $extended;
2620
        }
2621
        return Permission::check('ADMIN', 'any', $member);
2622
    }
2623
2624
    /**
2625
     * @param Member $member
2626
     * @return boolean
2627
     */
2628
    public function canEdit($member = null)
2629
    {
2630
        $extended = $this->extendedCan(__FUNCTION__, $member);
2631
        if ($extended !== null) {
2632
            return $extended;
2633
        }
2634
        return Permission::check('ADMIN', 'any', $member);
2635
    }
2636
2637
    /**
2638
     * @param Member $member
2639
     * @return boolean
2640
     */
2641
    public function canDelete($member = null)
2642
    {
2643
        $extended = $this->extendedCan(__FUNCTION__, $member);
2644
        if ($extended !== null) {
2645
            return $extended;
2646
        }
2647
        return Permission::check('ADMIN', 'any', $member);
2648
    }
2649
2650
    /**
2651
     * @param Member $member
2652
     * @param array $context Additional context-specific data which might
2653
     * affect whether (or where) this object could be created.
2654
     * @return boolean
2655
     */
2656
    public function canCreate($member = null, $context = array())
2657
    {
2658
        $extended = $this->extendedCan(__FUNCTION__, $member, $context);
2659
        if ($extended !== null) {
2660
            return $extended;
2661
        }
2662
        return Permission::check('ADMIN', 'any', $member);
2663
    }
2664
2665
    /**
2666
     * Debugging used by Debug::show()
2667
     *
2668
     * @return string HTML data representing this object
2669
     */
2670
    public function debug()
2671
    {
2672
        $class = static::class;
2673
        $val = "<h3>Database record: {$class}</h3>\n<ul>\n";
2674
        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...
2675
            foreach ($this->record as $fieldName => $fieldVal) {
2676
                $val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
2677
            }
2678
        }
2679
        $val .= "</ul>\n";
2680
        return $val;
2681
    }
2682
2683
    /**
2684
     * Return the DBField object that represents the given field.
2685
     * This works similarly to obj() with 2 key differences:
2686
     *   - it still returns an object even when the field has no value.
2687
     *   - it only matches fields and not methods
2688
     *   - it matches foreign keys generated by has_one relationships, eg, "ParentID"
2689
     *
2690
     * @param string $fieldName Name of the field
2691
     * @return DBField The field as a DBField object
2692
     */
2693
    public function dbObject($fieldName)
2694
    {
2695
        // Check for field in DB
2696
        $schema = static::getSchema();
2697
        $helper = $schema->fieldSpec(static::class, $fieldName, DataObjectSchema::INCLUDE_CLASS);
2698
        if (!$helper) {
2699
            return null;
2700
        }
2701
2702
        if (!isset($this->record[$fieldName]) && isset($this->record[$fieldName . '_Lazy'])) {
2703
            $tableClass = $this->record[$fieldName . '_Lazy'];
2704
            $this->loadLazyFields($tableClass);
2705
        }
2706
2707
        $value = isset($this->record[$fieldName])
2708
            ? $this->record[$fieldName]
2709
            : null;
2710
2711
        // If we have a DBField object in $this->record, then return that
2712
        if ($value instanceof DBField) {
2713
            return $value;
2714
        }
2715
2716
        list($class, $spec) = explode('.', $helper);
2717
        /** @var DBField $obj */
2718
        $table = $schema->tableName($class);
2719
        $obj = Injector::inst()->create($spec, $fieldName);
2720
        $obj->setTable($table);
2721
        $obj->setValue($value, $this, false);
2722
        return $obj;
2723
    }
2724
2725
    /**
2726
     * Traverses to a DBField referenced by relationships between data objects.
2727
     *
2728
     * The path to the related field is specified with dot separated syntax
2729
     * (eg: Parent.Child.Child.FieldName).
2730
     *
2731
     * @param string $fieldPath
2732
     *
2733
     * @return mixed DBField of the field on the object or a DataList instance.
2734
     */
2735
    public function relObject($fieldPath)
2736
    {
2737
        $object = null;
2738
2739
        if (strpos($fieldPath, '.') !== false) {
2740
            $parts = explode('.', $fieldPath);
2741
            $fieldName = array_pop($parts);
2742
2743
            // Traverse dot syntax
2744
            $component = $this;
2745
2746
            foreach ($parts as $relation) {
2747
                if ($component instanceof SS_List) {
2748
                    if (method_exists($component, $relation)) {
2749
                        $component = $component->$relation();
2750
                    } else {
2751
                        /** @var DataList $component */
2752
                        $component = $component->relation($relation);
2753
                    }
2754
                } else {
2755
                    $component = $component->$relation();
2756
                }
2757
            }
2758
2759
            $object = $component->dbObject($fieldName);
2760
        } else {
2761
            $object = $this->dbObject($fieldPath);
2762
        }
2763
2764
        return $object;
2765
    }
2766
2767
    /**
2768
     * Traverses to a field referenced by relationships between data objects, returning the value
2769
     * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)
2770
     *
2771
     * @param $fieldName string
2772
     * @return string | null - will return null on a missing value
2773
     */
2774
    public function relField($fieldName)
2775
    {
2776
        $component = $this;
2777
2778
        // We're dealing with relations here so we traverse the dot syntax
2779
        if (strpos($fieldName, '.') !== false) {
2780
            $relations = explode('.', $fieldName);
2781
            $fieldName = array_pop($relations);
2782
            foreach ($relations as $relation) {
2783
                if (!$component) {
2784
                    return null;
2785
                // Inspect $component for element $relation
2786
                } elseif ($component->hasMethod($relation)) {
2787
                    // Check nested method
2788
                    $component = $component->$relation();
2789
                } elseif ($component instanceof SS_List) {
2790
                    // Select adjacent relation from DataList
2791
                    /** @var DataList $component */
2792
                    $component = $component->relation($relation);
2793
                } elseif ($component instanceof DataObject
2794
                    && ($dbObject = $component->dbObject($relation))
2795
                ) {
2796
                    // Select db object
2797
                    $component = $dbObject;
2798
                } else {
2799
                    user_error("$relation is not a relation/field on " . get_class($component), E_USER_ERROR);
2800
                }
2801
            }
2802
        }
2803
2804
        // Bail if the component is null
2805
        if (!$component) {
2806
            return null;
2807
        }
2808
        if ($component->hasMethod($fieldName)) {
2809
            return $component->$fieldName();
2810
        }
2811
        return $component->$fieldName;
2812
    }
2813
2814
    /**
2815
     * Temporary hack to return an association name, based on class, to get around the mangle
2816
     * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
2817
     *
2818
     * @param string $className
2819
     * @return string
2820
     */
2821
    public function getReverseAssociation($className)
2822
    {
2823
        if (is_array($this->manyMany())) {
0 ignored issues
show
introduced by
The condition is_array($this->manyMany()) is always true.
Loading history...
2824
            $many_many = array_flip($this->manyMany());
2825
            if (array_key_exists($className, $many_many)) {
2826
                return $many_many[$className];
2827
            }
2828
        }
2829
        if (is_array($this->hasMany())) {
0 ignored issues
show
introduced by
The condition is_array($this->hasMany()) is always true.
Loading history...
2830
            $has_many = array_flip($this->hasMany());
2831
            if (array_key_exists($className, $has_many)) {
2832
                return $has_many[$className];
2833
            }
2834
        }
2835
        if (is_array($this->hasOne())) {
0 ignored issues
show
introduced by
The condition is_array($this->hasOne()) is always true.
Loading history...
2836
            $has_one = array_flip($this->hasOne());
2837
            if (array_key_exists($className, $has_one)) {
2838
                return $has_one[$className];
2839
            }
2840
        }
2841
2842
        return false;
2843
    }
2844
2845
    /**
2846
     * Return all objects matching the filter
2847
     * sub-classes are automatically selected and included
2848
     *
2849
     * @param string $callerClass The class of objects to be returned
2850
     * @param string|array $filter A filter to be inserted into the WHERE clause.
2851
     * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
2852
     * @param string|array $sort A sort expression to be inserted into the ORDER
2853
     * BY clause.  If omitted, self::$default_sort will be used.
2854
     * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
2855
     * @param string|array $limit A limit expression to be inserted into the LIMIT clause.
2856
     * @param string $containerClass The container class to return the results in.
2857
     *
2858
     * @todo $containerClass is Ignored, why?
2859
     *
2860
     * @return DataList The objects matching the filter, in the class specified by $containerClass
2861
     */
2862
    public static function get(
2863
        $callerClass = null,
2864
        $filter = "",
2865
        $sort = "",
2866
        $join = "",
2867
        $limit = null,
2868
        $containerClass = DataList::class
2869
    ) {
2870
2871
        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...
2872
            $callerClass = get_called_class();
2873
            if ($callerClass == self::class) {
2874
                throw new \InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
2875
            }
2876
2877
            if ($filter || $sort || $join || $limit || ($containerClass != DataList::class)) {
2878
                throw new \InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
2879
                    . ' arguments');
2880
            }
2881
2882
            return DataList::create(get_called_class());
2883
        }
2884
2885
        if ($join) {
2886
            throw new \InvalidArgumentException(
2887
                'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
2888
            );
2889
        }
2890
2891
        $result = DataList::create($callerClass)->where($filter)->sort($sort);
2892
2893
        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

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

2894
            $limitArguments = explode(',', /** @scrutinizer ignore-type */ $limit);
Loading history...
2895
            $result = $result->limit($limitArguments[1], $limitArguments[0]);
2896
        } elseif ($limit) {
2897
            $result = $result->limit($limit);
2898
        }
2899
2900
        return $result;
2901
    }
2902
2903
2904
    /**
2905
     * Return the first item matching the given query.
2906
     * All calls to get_one() are cached.
2907
     *
2908
     * @param string $callerClass The class of objects to be returned
2909
     * @param string|array $filter A filter to be inserted into the WHERE clause.
2910
     * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
2911
     * @param boolean $cache Use caching
2912
     * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
2913
     *
2914
     * @return DataObject|null The first item matching the query
2915
     */
2916
    public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "")
2917
    {
2918
        $SNG = singleton($callerClass);
2919
2920
        $cacheComponents = array($filter, $orderby, $SNG->extend('cacheKeyComponent'));
2921
        $cacheKey = md5(serialize($cacheComponents));
2922
2923
        $item = null;
2924
        if (!$cache || !isset(self::$_cache_get_one[$callerClass][$cacheKey])) {
2925
            $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...
2926
            $item = $dl->first();
2927
2928
            if ($cache) {
2929
                self::$_cache_get_one[$callerClass][$cacheKey] = $item;
2930
                if (!self::$_cache_get_one[$callerClass][$cacheKey]) {
2931
                    self::$_cache_get_one[$callerClass][$cacheKey] = false;
2932
                }
2933
            }
2934
        }
2935
2936
        if ($cache) {
2937
            return self::$_cache_get_one[$callerClass][$cacheKey] ?: null;
2938
        } else {
2939
            return $item;
2940
        }
2941
    }
2942
2943
    /**
2944
     * Flush the cached results for all relations (has_one, has_many, many_many)
2945
     * Also clears any cached aggregate data.
2946
     *
2947
     * @param boolean $persistent When true will also clear persistent data stored in the Cache system.
2948
     *                            When false will just clear session-local cached data
2949
     * @return DataObject $this
2950
     */
2951
    public function flushCache($persistent = true)
2952
    {
2953
        if (static::class == self::class) {
0 ignored issues
show
introduced by
The condition static::class == self::class is always true.
Loading history...
2954
            self::$_cache_get_one = array();
2955
            return $this;
2956
        }
2957
2958
        $classes = ClassInfo::ancestry(static::class);
2959
        foreach ($classes as $class) {
2960
            if (isset(self::$_cache_get_one[$class])) {
2961
                unset(self::$_cache_get_one[$class]);
2962
            }
2963
        }
2964
2965
        $this->extend('flushCache');
2966
2967
        $this->components = array();
2968
        return $this;
2969
    }
2970
2971
    /**
2972
     * Flush the get_one global cache and destroy associated objects.
2973
     */
2974
    public static function flush_and_destroy_cache()
2975
    {
2976
        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...
2977
            foreach (self::$_cache_get_one as $class => $items) {
2978
                if (is_array($items)) {
2979
                    foreach ($items as $item) {
2980
                        if ($item) {
2981
                            $item->destroy();
2982
                        }
2983
                    }
2984
                }
2985
            }
2986
        }
2987
        self::$_cache_get_one = array();
2988
    }
2989
2990
    /**
2991
     * Reset all global caches associated with DataObject.
2992
     */
2993
    public static function reset()
2994
    {
2995
        // @todo Decouple these
2996
        DBClassName::clear_classname_cache();
2997
        ClassInfo::reset_db_cache();
2998
        static::getSchema()->reset();
2999
        self::$_cache_get_one = array();
3000
        self::$_cache_field_labels = array();
3001
    }
3002
3003
    /**
3004
     * Return the given element, searching by ID
3005
     *
3006
     * @param string $callerClass The class of the object to be returned
3007
     * @param int $id The id of the element
3008
     * @param boolean $cache See {@link get_one()}
3009
     *
3010
     * @return DataObject The element
3011
     */
3012
    public static function get_by_id($callerClass, $id, $cache = true)
3013
    {
3014
        if (!is_numeric($id)) {
0 ignored issues
show
introduced by
The condition is_numeric($id) is always true.
Loading history...
3015
            user_error("DataObject::get_by_id passed a non-numeric ID #$id", E_USER_WARNING);
3016
        }
3017
3018
        // Pass to get_one
3019
        $column = static::getSchema()->sqlColumnForField($callerClass, 'ID');
3020
        return DataObject::get_one($callerClass, array($column => $id), $cache);
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...
3021
    }
3022
3023
    /**
3024
     * Get the name of the base table for this object
3025
     *
3026
     * @return string
3027
     */
3028
    public function baseTable()
3029
    {
3030
        return static::getSchema()->baseDataTable($this);
3031
    }
3032
3033
    /**
3034
     * Get the base class for this object
3035
     *
3036
     * @return string
3037
     */
3038
    public function baseClass()
3039
    {
3040
        return static::getSchema()->baseDataClass($this);
3041
    }
3042
3043
    /**
3044
     * @var array Parameters used in the query that built this object.
3045
     * This can be used by decorators (e.g. lazy loading) to
3046
     * run additional queries using the same context.
3047
     */
3048
    protected $sourceQueryParams;
3049
3050
    /**
3051
     * @see $sourceQueryParams
3052
     * @return array
3053
     */
3054
    public function getSourceQueryParams()
3055
    {
3056
        return $this->sourceQueryParams;
3057
    }
3058
3059
    /**
3060
     * Get list of parameters that should be inherited to relations on this object
3061
     *
3062
     * @return array
3063
     */
3064
    public function getInheritableQueryParams()
3065
    {
3066
        $params = $this->getSourceQueryParams();
3067
        $this->extend('updateInheritableQueryParams', $params);
3068
        return $params;
3069
    }
3070
3071
    /**
3072
     * @see $sourceQueryParams
3073
     * @param array
3074
     */
3075
    public function setSourceQueryParams($array)
3076
    {
3077
        $this->sourceQueryParams = $array;
3078
    }
3079
3080
    /**
3081
     * @see $sourceQueryParams
3082
     * @param string $key
3083
     * @param string $value
3084
     */
3085
    public function setSourceQueryParam($key, $value)
3086
    {
3087
        $this->sourceQueryParams[$key] = $value;
3088
    }
3089
3090
    /**
3091
     * @see $sourceQueryParams
3092
     * @param string $key
3093
     * @return string
3094
     */
3095
    public function getSourceQueryParam($key)
3096
    {
3097
        if (isset($this->sourceQueryParams[$key])) {
3098
            return $this->sourceQueryParams[$key];
3099
        }
3100
        return null;
3101
    }
3102
3103
    //-------------------------------------------------------------------------------------------//
3104
3105
    /**
3106
     * Check the database schema and update it as necessary.
3107
     *
3108
     * @uses DataExtension->augmentDatabase()
3109
     */
3110
    public function requireTable()
3111
    {
3112
        // Only build the table if we've actually got fields
3113
        $schema = static::getSchema();
3114
        $table = $schema->tableName(static::class);
3115
        $fields = $schema->databaseFields(static::class, false);
3116
        $indexes = $schema->databaseIndexes(static::class, false);
3117
        $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

3117
        /** @scrutinizer ignore-call */ 
3118
        $extensions = self::database_extensions(static::class);
Loading history...
3118
3119
        if (empty($table)) {
3120
            throw new LogicException(
3121
                "Class " . static::class . " not loaded by manifest, or no database table configured"
3122
            );
3123
        }
3124
3125
        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...
3126
            $hasAutoIncPK = get_parent_class($this) === self::class;
3127
            DB::require_table(
3128
                $table,
3129
                $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

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

3130
                /** @scrutinizer ignore-type */ $indexes,
Loading history...
3131
                $hasAutoIncPK,
3132
                $this->config()->get('create_table_options'),
3133
                $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

3133
                /** @scrutinizer ignore-type */ $extensions
Loading history...
3134
            );
3135
        } else {
3136
            DB::dont_require_table($table);
3137
        }
3138
3139
        // Build any child tables for many_many items
3140
        if ($manyMany = $this->uninherited('many_many')) {
3141
            $extras = $this->uninherited('many_many_extraFields');
3142
            foreach ($manyMany as $component => $spec) {
3143
                // Get many_many spec
3144
                $manyManyComponent = $schema->manyManyComponent(static::class, $component);
3145
                $parentField = $manyManyComponent['parentField'];
3146
                $childField = $manyManyComponent['childField'];
3147
                $tableOrClass = $manyManyComponent['join'];
3148
3149
                // Skip if backed by actual class
3150
                if (class_exists($tableOrClass)) {
3151
                    continue;
3152
                }
3153
3154
                // Build fields
3155
                $manymanyFields = array(
3156
                    $parentField => "Int",
3157
                    $childField => "Int",
3158
                );
3159
                if (isset($extras[$component])) {
3160
                    $manymanyFields = array_merge($manymanyFields, $extras[$component]);
3161
                }
3162
3163
                // Build index list
3164
                $manymanyIndexes = [
3165
                    $parentField => [
3166
                        'type' => 'index',
3167
                        'name' => $parentField,
3168
                        'columns' => [$parentField],
3169
                    ],
3170
                    $childField => [
3171
                        'type' => 'index',
3172
                        'name' =>$childField,
3173
                        'columns' => [$childField],
3174
                    ],
3175
                ];
3176
                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

3176
                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

3176
                DB::require_table($tableOrClass, /** @scrutinizer ignore-type */ $manymanyFields, $manymanyIndexes, true, null, $extensions);
Loading history...
3177
            }
3178
        }
3179
3180
        // Let any extentions make their own database fields
3181
        $this->extend('augmentDatabase', $dummy);
3182
    }
3183
3184
    /**
3185
     * Add default records to database. This function is called whenever the
3186
     * database is built, after the database tables have all been created. Overload
3187
     * this to add default records when the database is built, but make sure you
3188
     * call parent::requireDefaultRecords().
3189
     *
3190
     * @uses DataExtension->requireDefaultRecords()
3191
     */
3192
    public function requireDefaultRecords()
3193
    {
3194
        $defaultRecords = $this->config()->uninherited('default_records');
3195
3196
        if (!empty($defaultRecords)) {
3197
            $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...
3198
            if (!$hasData) {
3199
                $className = static::class;
3200
                foreach ($defaultRecords as $record) {
3201
                    $obj = Injector::inst()->create($className, $record);
3202
                    $obj->write();
3203
                }
3204
                DB::alteration_message("Added default records to $className table", "created");
3205
            }
3206
        }
3207
3208
        // Let any extentions make their own database default data
3209
        $this->extend('requireDefaultRecords', $dummy);
3210
    }
3211
3212
    /**
3213
     * Get the default searchable fields for this object, as defined in the
3214
     * $searchable_fields list. If searchable fields are not defined on the
3215
     * data object, uses a default selection of summary fields.
3216
     *
3217
     * @return array
3218
     */
3219
    public function searchableFields()
3220
    {
3221
        // can have mixed format, need to make consistent in most verbose form
3222
        $fields = $this->config()->get('searchable_fields');
3223
        $labels = $this->fieldLabels();
3224
3225
        // fallback to summary fields (unless empty array is explicitly specified)
3226
        if (! $fields && ! is_array($fields)) {
3227
            $summaryFields = array_keys($this->summaryFields());
3228
            $fields = array();
3229
3230
            // remove the custom getters as the search should not include them
3231
            $schema = static::getSchema();
3232
            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...
3233
                foreach ($summaryFields as $key => $name) {
3234
                    $spec = $name;
3235
3236
                    // Extract field name in case this is a method called on a field (e.g. "Date.Nice")
3237
                    if (($fieldPos = strpos($name, '.')) !== false) {
3238
                        $name = substr($name, 0, $fieldPos);
3239
                    }
3240
3241
                    if ($schema->fieldSpec($this, $name)) {
3242
                        $fields[] = $name;
3243
                    } elseif ($this->relObject($spec)) {
3244
                        $fields[] = $spec;
3245
                    }
3246
                }
3247
            }
3248
        }
3249
3250
        // we need to make sure the format is unified before
3251
        // augmenting fields, so extensions can apply consistent checks
3252
        // but also after augmenting fields, because the extension
3253
        // might use the shorthand notation as well
3254
3255
        // rewrite array, if it is using shorthand syntax
3256
        $rewrite = array();
3257
        foreach ($fields as $name => $specOrName) {
3258
            $identifer = (is_int($name)) ? $specOrName : $name;
3259
3260
            if (is_int($name)) {
3261
                // 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...
3262
                $rewrite[$identifer] = array();
3263
            } elseif (is_array($specOrName)) {
3264
                // 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...
3265
                //   'filter => 'ExactMatchFilter',
3266
                //   '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...
3267
                //   '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...
3268
                // ))
3269
                $rewrite[$identifer] = array_merge(
3270
                    array('filter' => $this->relObject($identifer)->config()->get('default_search_filter_class')),
3271
                    (array)$specOrName
3272
                );
3273
            } else {
3274
                // 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...
3275
                $rewrite[$identifer] = array(
3276
                    'filter' => $specOrName,
3277
                );
3278
            }
3279
            if (!isset($rewrite[$identifer]['title'])) {
3280
                $rewrite[$identifer]['title'] = (isset($labels[$identifer]))
3281
                    ? $labels[$identifer] : FormField::name_to_label($identifer);
3282
            }
3283
            if (!isset($rewrite[$identifer]['filter'])) {
3284
                /** @skipUpgrade */
3285
                $rewrite[$identifer]['filter'] = 'PartialMatchFilter';
3286
            }
3287
        }
3288
3289
        $fields = $rewrite;
3290
3291
        // apply DataExtensions if present
3292
        $this->extend('updateSearchableFields', $fields);
3293
3294
        return $fields;
3295
    }
3296
3297
    /**
3298
     * Get any user defined searchable fields labels that
3299
     * exist. Allows overriding of default field names in the form
3300
     * interface actually presented to the user.
3301
     *
3302
     * The reason for keeping this separate from searchable_fields,
3303
     * which would be a logical place for this functionality, is to
3304
     * avoid bloating and complicating the configuration array. Currently
3305
     * much of this system is based on sensible defaults, and this property
3306
     * would generally only be set in the case of more complex relationships
3307
     * between data object being required in the search interface.
3308
     *
3309
     * Generates labels based on name of the field itself, if no static property
3310
     * {@link self::field_labels} exists.
3311
     *
3312
     * @uses $field_labels
3313
     * @uses FormField::name_to_label()
3314
     *
3315
     * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
3316
     *
3317
     * @return array|string Array of all element labels if no argument given, otherwise the label of the field
3318
     */
3319
    public function fieldLabels($includerelations = true)
3320
    {
3321
        $cacheKey = static::class . '_' . $includerelations;
3322
3323
        if (!isset(self::$_cache_field_labels[$cacheKey])) {
3324
            $customLabels = $this->config()->get('field_labels');
3325
            $autoLabels = array();
3326
3327
            // get all translated static properties as defined in i18nCollectStatics()
3328
            $ancestry = ClassInfo::ancestry(static::class);
3329
            $ancestry = array_reverse($ancestry);
3330
            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...
3331
                foreach ($ancestry as $ancestorClass) {
3332
                    if ($ancestorClass === ViewableData::class) {
3333
                        break;
3334
                    }
3335
                    $types = [
3336
                        'db' => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
3337
                    ];
3338
                    if ($includerelations) {
3339
                        $types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
3340
                        $types['has_many'] = (array)Config::inst()->get($ancestorClass, 'has_many', Config::UNINHERITED);
3341
                        $types['many_many'] = (array)Config::inst()->get($ancestorClass, 'many_many', Config::UNINHERITED);
3342
                        $types['belongs_many_many'] = (array)Config::inst()->get($ancestorClass, 'belongs_many_many', Config::UNINHERITED);
3343
                    }
3344
                    foreach ($types as $type => $attrs) {
3345
                        foreach ($attrs as $name => $spec) {
3346
                            $autoLabels[$name] = _t("{$ancestorClass}.{$type}_{$name}", FormField::name_to_label($name));
3347
                        }
3348
                    }
3349
                }
3350
            }
3351
3352
            $labels = array_merge((array)$autoLabels, (array)$customLabels);
3353
            $this->extend('updateFieldLabels', $labels);
3354
            self::$_cache_field_labels[$cacheKey] = $labels;
3355
        }
3356
3357
        return self::$_cache_field_labels[$cacheKey];
3358
    }
3359
3360
    /**
3361
     * Get a human-readable label for a single field,
3362
     * see {@link fieldLabels()} for more details.
3363
     *
3364
     * @uses fieldLabels()
3365
     * @uses FormField::name_to_label()
3366
     *
3367
     * @param string $name Name of the field
3368
     * @return string Label of the field
3369
     */
3370
    public function fieldLabel($name)
3371
    {
3372
        $labels = $this->fieldLabels();
3373
        return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name);
3374
    }
3375
3376
    /**
3377
     * Get the default summary fields for this object.
3378
     *
3379
     * @todo use the translation apparatus to return a default field selection for the language
3380
     *
3381
     * @return array
3382
     */
3383
    public function summaryFields()
3384
    {
3385
        $rawFields = $this->config()->get('summary_fields');
3386
3387
        // Merge associative / numeric keys
3388
        $fields = [];
3389
        foreach ($rawFields as $key => $value) {
3390
            if (is_int($key)) {
3391
                $key = $value;
3392
            }
3393
            $fields[$key] = $value;
3394
        }
3395
3396
        if (!$fields) {
3397
            $fields = array();
3398
            // try to scaffold a couple of usual suspects
3399
            if ($this->hasField('Name')) {
3400
                $fields['Name'] = 'Name';
3401
            }
3402
            if (static::getSchema()->fieldSpec($this, 'Title')) {
3403
                $fields['Title'] = 'Title';
3404
            }
3405
            if ($this->hasField('Description')) {
3406
                $fields['Description'] = 'Description';
3407
            }
3408
            if ($this->hasField('FirstName')) {
3409
                $fields['FirstName'] = 'First Name';
3410
            }
3411
        }
3412
        $this->extend("updateSummaryFields", $fields);
3413
3414
        // Final fail-over, just list ID field
3415
        if (!$fields) {
3416
            $fields['ID'] = 'ID';
3417
        }
3418
3419
        // Localize fields (if possible)
3420
        foreach ($this->fieldLabels(false) as $name => $label) {
3421
            // only attempt to localize if the label definition is the same as the field name.
3422
            // this will preserve any custom labels set in the summary_fields configuration
3423
            if (isset($fields[$name]) && $name === $fields[$name]) {
3424
                $fields[$name] = $label;
3425
            }
3426
        }
3427
3428
        return $fields;
3429
    }
3430
3431
    /**
3432
     * Defines a default list of filters for the search context.
3433
     *
3434
     * If a filter class mapping is defined on the data object,
3435
     * it is constructed here. Otherwise, the default filter specified in
3436
     * {@link DBField} is used.
3437
     *
3438
     * @todo error handling/type checking for valid FormField and SearchFilter subclasses?
3439
     *
3440
     * @return array
3441
     */
3442
    public function defaultSearchFilters()
3443
    {
3444
        $filters = array();
3445
3446
        foreach ($this->searchableFields() as $name => $spec) {
3447
            if (empty($spec['filter'])) {
3448
                /** @skipUpgrade */
3449
                $filters[$name] = 'PartialMatchFilter';
3450
            } elseif ($spec['filter'] instanceof SearchFilter) {
3451
                $filters[$name] = $spec['filter'];
3452
            } else {
3453
                $filters[$name] = Injector::inst()->create($spec['filter'], $name);
3454
            }
3455
        }
3456
3457
        return $filters;
3458
    }
3459
3460
    /**
3461
     * @return boolean True if the object is in the database
3462
     */
3463
    public function isInDB()
3464
    {
3465
        return is_numeric($this->ID) && $this->ID > 0;
3466
    }
3467
3468
    /*
3469
     * @ignore
3470
     */
3471
    private static $subclass_access = true;
3472
3473
    /**
3474
     * Temporarily disable subclass access in data object qeur
3475
     */
3476
    public static function disable_subclass_access()
3477
    {
3478
        self::$subclass_access = false;
3479
    }
3480
    public static function enable_subclass_access()
3481
    {
3482
        self::$subclass_access = true;
3483
    }
3484
3485
    //-------------------------------------------------------------------------------------------//
3486
3487
    /**
3488
     * Database field definitions.
3489
     * This is a map from field names to field type. The field
3490
     * type should be a class that extends .
3491
     * @var array
3492
     * @config
3493
     */
3494
    private static $db = [];
3495
3496
    /**
3497
     * Use a casting object for a field. This is a map from
3498
     * field name to class name of the casting object.
3499
     *
3500
     * @var array
3501
     */
3502
    private static $casting = array(
3503
        "Title" => 'Text',
3504
    );
3505
3506
    /**
3507
     * Specify custom options for a CREATE TABLE call.
3508
     * Can be used to specify a custom storage engine for specific database table.
3509
     * All options have to be keyed for a specific database implementation,
3510
     * identified by their class name (extending from {@link SS_Database}).
3511
     *
3512
     * <code>
3513
     * array(
3514
     *  'MySQLDatabase' => 'ENGINE=MyISAM'
3515
     * )
3516
     * </code>
3517
     *
3518
     * Caution: This API is experimental, and might not be
3519
     * included in the next major release. Please use with care.
3520
     *
3521
     * @var array
3522
     * @config
3523
     */
3524
    private static $create_table_options = array(
3525
        MySQLSchemaManager::ID => 'ENGINE=InnoDB'
3526
    );
3527
3528
    /**
3529
     * If a field is in this array, then create a database index
3530
     * on that field. This is a map from fieldname to index type.
3531
     * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
3532
     *
3533
     * @var array
3534
     * @config
3535
     */
3536
    private static $indexes = null;
3537
3538
    /**
3539
     * Inserts standard column-values when a DataObject
3540
     * is instanciated. Does not insert default records {@see $default_records}.
3541
     * This is a map from fieldname to default value.
3542
     *
3543
     *  - If you would like to change a default value in a sub-class, just specify it.
3544
     *  - If you would like to disable the default value given by a parent class, set the default value to 0,'',
3545
     *    or false in your subclass.  Setting it to null won't work.
3546
     *
3547
     * @var array
3548
     * @config
3549
     */
3550
    private static $defaults = [];
3551
3552
    /**
3553
     * Multidimensional array which inserts default data into the database
3554
     * on a db/build-call as long as the database-table is empty. Please use this only
3555
     * for simple constructs, not for SiteTree-Objects etc. which need special
3556
     * behaviour such as publishing and ParentNodes.
3557
     *
3558
     * Example:
3559
     * array(
3560
     *  array('Title' => "DefaultPage1", 'PageTitle' => 'page1'),
3561
     *  array('Title' => "DefaultPage2")
3562
     * ).
3563
     *
3564
     * @var array
3565
     * @config
3566
     */
3567
    private static $default_records = null;
3568
3569
    /**
3570
     * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a
3571
     * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class.
3572
     *
3573
     * Note that you cannot have a has_one and belongs_to relationship with the same name.
3574
     *
3575
     *  @var array
3576
     * @config
3577
     */
3578
    private static $has_one = [];
3579
3580
    /**
3581
     * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.
3582
     *
3583
     * This does not actually create any data structures, but allows you to query the other object in a one-to-one
3584
     * relationship from the child object. If you have multiple belongs_to links to another object you can use the
3585
     * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use.
3586
     *
3587
     * Note that you cannot have a has_one and belongs_to relationship with the same name.
3588
     *
3589
     * @var array
3590
     * @config
3591
     */
3592
    private static $belongs_to = [];
3593
3594
    /**
3595
     * This defines a one-to-many relationship. It is a map of component name to the remote data class.
3596
     *
3597
     * This relationship type does not actually create a data structure itself - you need to define a matching $has_one
3598
     * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this
3599
     * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show
3600
     * which foreign key to use.
3601
     *
3602
     * @var array
3603
     * @config
3604
     */
3605
    private static $has_many = [];
3606
3607
    /**
3608
     * many-many relationship definitions.
3609
     * This is a map from component name to data type.
3610
     * @var array
3611
     * @config
3612
     */
3613
    private static $many_many = [];
3614
3615
    /**
3616
     * Extra fields to include on the connecting many-many table.
3617
     * This is a map from field name to field type.
3618
     *
3619
     * Example code:
3620
     * <code>
3621
     * public static $many_many_extraFields = array(
3622
     *  'Members' => array(
3623
     *          'Role' => 'Varchar(100)'
3624
     *      )
3625
     * );
3626
     * </code>
3627
     *
3628
     * @var array
3629
     * @config
3630
     */
3631
    private static $many_many_extraFields = [];
3632
3633
    /**
3634
     * The inverse side of a many-many relationship.
3635
     * This is a map from component name to data type.
3636
     * @var array
3637
     * @config
3638
     */
3639
    private static $belongs_many_many = [];
3640
3641
    /**
3642
     * The default sort expression. This will be inserted in the ORDER BY
3643
     * clause of a SQL query if no other sort expression is provided.
3644
     * @var string
3645
     * @config
3646
     */
3647
    private static $default_sort = null;
3648
3649
    /**
3650
     * Default list of fields that can be scaffolded by the ModelAdmin
3651
     * search interface.
3652
     *
3653
     * Overriding the default filter, with a custom defined filter:
3654
     * <code>
3655
     *  static $searchable_fields = array(
3656
     *     "Name" => "PartialMatchFilter"
3657
     *  );
3658
     * </code>
3659
     *
3660
     * Overriding the default form fields, with a custom defined field.
3661
     * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}.
3662
     * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}.
3663
     * <code>
3664
     *  static $searchable_fields = array(
3665
     *    "Name" => array(
3666
     *      "field" => "TextField"
3667
     *    )
3668
     *  );
3669
     * </code>
3670
     *
3671
     * Overriding the default form field, filter and title:
3672
     * <code>
3673
     *  static $searchable_fields = array(
3674
     *    "Organisation.ZipCode" => array(
3675
     *      "field" => "TextField",
3676
     *      "filter" => "PartialMatchFilter",
3677
     *      "title" => 'Organisation ZIP'
3678
     *    )
3679
     *  );
3680
     * </code>
3681
     * @config
3682
     */
3683
    private static $searchable_fields = null;
3684
3685
    /**
3686
     * User defined labels for searchable_fields, used to override
3687
     * default display in the search form.
3688
     * @config
3689
     */
3690
    private static $field_labels = [];
3691
3692
    /**
3693
     * Provides a default list of fields to be used by a 'summary'
3694
     * view of this object.
3695
     * @config
3696
     */
3697
    private static $summary_fields = [];
3698
3699
    public function provideI18nEntities()
3700
    {
3701
        // Note: see http://guides.rubyonrails.org/i18n.html#pluralization for rules
3702
        // Best guess for a/an rule. Better guesses require overriding in subclasses
3703
        $pluralName = $this->plural_name();
3704
        $singularName = $this->singular_name();
3705
        $conjunction = preg_match('/^[aeiou]/i', $singularName) ? 'An ' : 'A ';
3706
        return [
3707
            static::class . '.SINGULARNAME' => $this->singular_name(),
3708
            static::class . '.PLURALNAME' => $pluralName,
3709
            static::class . '.PLURALS' => [
3710
                'one' => $conjunction . $singularName,
3711
                'other' => '{count} ' . $pluralName
3712
            ]
3713
        ];
3714
    }
3715
3716
    /**
3717
     * Returns true if the given method/parameter has a value
3718
     * (Uses the DBField::hasValue if the parameter is a database field)
3719
     *
3720
     * @param string $field The field name
3721
     * @param array $arguments
3722
     * @param bool $cache
3723
     * @return boolean
3724
     */
3725
    public function hasValue($field, $arguments = null, $cache = true)
3726
    {
3727
        // has_one fields should not use dbObject to check if a value is given
3728
        $hasOne = static::getSchema()->hasOneComponent(static::class, $field);
3729
        if (!$hasOne && ($obj = $this->dbObject($field))) {
3730
            return $obj->exists();
3731
        } else {
3732
            return parent::hasValue($field, $arguments, $cache);
3733
        }
3734
    }
3735
3736
    /**
3737
     * If selected through a many_many through relation, this is the instance of the joined record
3738
     *
3739
     * @return DataObject
3740
     */
3741
    public function getJoin()
3742
    {
3743
        return $this->joinRecord;
3744
    }
3745
3746
    /**
3747
     * Set joining object
3748
     *
3749
     * @param DataObject $object
3750
     * @param string $alias Alias
3751
     * @return $this
3752
     */
3753
    public function setJoin(DataObject $object, $alias = null)
3754
    {
3755
        $this->joinRecord = $object;
3756
        if ($alias) {
3757
            if (static::getSchema()->fieldSpec(static::class, $alias)) {
3758
                throw new InvalidArgumentException(
3759
                    "Joined record $alias cannot also be a db field"
3760
                );
3761
            }
3762
            $this->record[$alias] = $object;
3763
        }
3764
        return $this;
3765
    }
3766
3767
    /**
3768
     * Find objects in the given relationships, merging them into the given list
3769
     *
3770
     * @param string $source Config property to extract relationships from
3771
     * @param bool $recursive True if recursive
3772
     * @param ArrayList $list If specified, items will be added to this list. If not, a new
3773
     * instance of ArrayList will be constructed and returned
3774
     * @return ArrayList The list of related objects
3775
     */
3776
    public function findRelatedObjects($source, $recursive = true, $list = null)
3777
    {
3778
        if (!$list) {
3779
            $list = new ArrayList();
3780
        }
3781
3782
        // Skip search for unsaved records
3783
        if (!$this->isInDB()) {
3784
            return $list;
3785
        }
3786
3787
        $relationships = $this->config()->get($source) ?: [];
3788
        foreach ($relationships as $relationship) {
3789
            // Warn if invalid config
3790
            if (!$this->hasMethod($relationship)) {
3791
                trigger_error(sprintf(
3792
                    "Invalid %s config value \"%s\" on object on class \"%s\"",
3793
                    $source,
3794
                    $relationship,
3795
                    get_class($this)
3796
                ), E_USER_WARNING);
3797
                continue;
3798
            }
3799
3800
            // Inspect value of this relationship
3801
            $items = $this->{$relationship}();
3802
3803
            // Merge any new item
3804
            $newItems = $this->mergeRelatedObjects($list, $items);
3805
3806
            // Recurse if necessary
3807
            if ($recursive) {
3808
                foreach ($newItems as $item) {
3809
                    /** @var DataObject $item */
3810
                    $item->findRelatedObjects($source, true, $list);
3811
                }
3812
            }
3813
        }
3814
        return $list;
3815
    }
3816
3817
    /**
3818
     * Helper method to merge owned/owning items into a list.
3819
     * Items already present in the list will be skipped.
3820
     *
3821
     * @param ArrayList $list Items to merge into
3822
     * @param mixed $items List of new items to merge
3823
     * @return ArrayList List of all newly added items that did not already exist in $list
3824
     */
3825
    public function mergeRelatedObjects($list, $items)
3826
    {
3827
        $added = new ArrayList();
3828
        if (!$items) {
3829
            return $added;
3830
        }
3831
        if ($items instanceof DataObject) {
3832
            $items = [$items];
3833
        }
3834
3835
        /** @var DataObject $item */
3836
        foreach ($items as $item) {
3837
            $this->mergeRelatedObject($list, $added, $item);
3838
        }
3839
        return $added;
3840
    }
3841
3842
    /**
3843
     * Merge single object into a list, but ensures that existing objects are not
3844
     * re-added.
3845
     *
3846
     * @param ArrayList $list Global list
3847
     * @param ArrayList $added Additional list to insert into
3848
     * @param DataObject $item Item to add
3849
     */
3850
    protected function mergeRelatedObject($list, $added, $item)
3851
    {
3852
        // Identify item
3853
        $itemKey = get_class($item) . '/' . $item->ID;
3854
3855
        // Write if saved, versioned, and not already added
3856
        if ($item->isInDB() && !isset($list[$itemKey])) {
3857
            $list[$itemKey] = $item;
3858
            $added[$itemKey] = $item;
3859
        }
3860
3861
        // Add joined record (from many_many through) automatically
3862
        $joined = $item->getJoin();
3863
        if ($joined) {
0 ignored issues
show
introduced by
$joined is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
3864
            $this->mergeRelatedObject($list, $added, $joined);
3865
        }
3866
    }
3867
}
3868