Completed
Push — master ( c6c71f...1e53f2 )
by Hamish
11:24 queued 33s
created

DataObject::inferReciprocalComponent()   D

Complexity

Conditions 15
Paths 21

Size

Total Lines 97
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 97
rs 4.9121
cc 15
eloc 64
nc 21
nop 2

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
use SilverStripe\Model\FieldType\DBPolymorphicForeignKey;
4
use SilverStripe\Model\FieldType\DBField;
5
use SilverStripe\Model\FieldType\DBDatetime;
6
use SilverStripe\Model\FieldType\DBPrimaryKey;
7
use SilverStripe\Model\FieldType\DBComposite;
8
use SilverStripe\Model\FieldType\DBClassName;
9
10
/**
11
 * A single database record & abstract class for the data-access-model.
12
 *
13
 * <h2>Extensions</h2>
14
 *
15
 * See {@link Extension} and {@link DataExtension}.
16
 *
17
 * <h2>Permission Control</h2>
18
 *
19
 * Object-level access control by {@link Permission}. Permission codes are arbitrary
20
 * strings which can be selected on a group-by-group basis.
21
 *
22
 * <code>
23
 * class Article extends DataObject implements PermissionProvider {
24
 *  static $api_access = true;
25
 *
26
 *  function canView($member = false) {
27
 *    return Permission::check('ARTICLE_VIEW');
28
 *  }
29
 *  function canEdit($member = false) {
30
 *    return Permission::check('ARTICLE_EDIT');
31
 *  }
32
 *  function canDelete() {
33
 *    return Permission::check('ARTICLE_DELETE');
34
 *  }
35
 *  function canCreate() {
36
 *    return Permission::check('ARTICLE_CREATE');
37
 *  }
38
 *  function providePermissions() {
39
 *    return array(
40
 *      'ARTICLE_VIEW' => 'Read an article object',
41
 *      'ARTICLE_EDIT' => 'Edit an article object',
42
 *      'ARTICLE_DELETE' => 'Delete an article object',
43
 *      'ARTICLE_CREATE' => 'Create an article object',
44
 *    );
45
 *  }
46
 * }
47
 * </code>
48
 *
49
 * Object-level access control by {@link Group} membership:
50
 * <code>
51
 * class Article extends DataObject {
52
 *   static $api_access = true;
53
 *
54
 *   function canView($member = false) {
55
 *     if(!$member) $member = Member::currentUser();
56
 *     return $member->inGroup('Subscribers');
57
 *   }
58
 *   function canEdit($member = false) {
59
 *     if(!$member) $member = Member::currentUser();
60
 *     return $member->inGroup('Editors');
61
 *   }
62
 *
63
 *   // ...
64
 * }
65
 * </code>
66
 *
67
 * If any public method on this class is prefixed with an underscore,
68
 * the results are cached in memory through {@link cachedCall()}.
69
 *
70
 *
71
 * @todo Add instance specific removeExtension() which undos loadExtraStatics()
72
 *  and defineMethods()
73
 *
74
 * @package framework
75
 * @subpackage model
76
 *
77
 * @property integer ID ID of the DataObject, 0 if the DataObject doesn't exist in database.
78
 * @property string ClassName Class name of the DataObject
79
 * @property string LastEdited Date and time of DataObject's last modification.
80
 * @property string Created Date and time of DataObject creation.
81
 */
82
class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider {
83
84
	/**
85
	 * Human-readable singular name.
86
	 * @var string
87
	 * @config
88
	 */
89
	private static $singular_name = null;
90
91
	/**
92
	 * Human-readable plural name
93
	 * @var string
94
	 * @config
95
	 */
96
	private static $plural_name = null;
97
98
	/**
99
	 * Allow API access to this object?
100
	 * @todo Define the options that can be set here
101
	 * @config
102
	 */
103
	private static $api_access = false;
104
105
	/**
106
	 * Allows specification of a default value for the ClassName field.
107
	 * Configure this value only in subclasses of DataObject.
108
	 *
109
	 * @config
110
	 * @var string
111
	 */
112
	private static $default_classname = null;
113
114
	/**
115
	 * True if this DataObject has been destroyed.
116
	 * @var boolean
117
	 */
118
	public $destroyed = false;
119
120
	/**
121
	 * The DataModel from this this object comes
122
	 */
123
	protected $model;
124
125
	/**
126
	 * Data stored in this objects database record. An array indexed by fieldname.
127
	 *
128
	 * Use {@link toMap()} if you want an array representation
129
	 * of this object, as the $record array might contain lazy loaded field aliases.
130
	 *
131
	 * @var array
132
	 */
133
	protected $record;
134
135
	/**
136
	 * Represents a field that hasn't changed (before === after, thus before == after)
137
	 */
138
	const CHANGE_NONE = 0;
139
140
	/**
141
	 * Represents a field that has changed type, although not the loosely defined value.
142
	 * (before !== after && before == after)
143
	 * E.g. change 1 to true or "true" to true, but not true to 0.
144
	 * Value changes are by nature also considered strict changes.
145
	 */
146
	const CHANGE_STRICT = 1;
147
148
	/**
149
	 * Represents a field that has changed the loosely defined value
150
	 * (before != after, thus, before !== after))
151
	 * E.g. change false to true, but not false to 0
152
	 */
153
	const CHANGE_VALUE = 2;
154
155
	/**
156
	 * An array indexed by fieldname, true if the field has been changed.
157
	 * Use {@link getChangedFields()} and {@link isChanged()} to inspect
158
	 * the changed state.
159
	 *
160
	 * @var array
161
	 */
162
	private $changed;
163
164
	/**
165
	 * The database record (in the same format as $record), before
166
	 * any changes.
167
	 * @var array
168
	 */
169
	protected $original;
170
171
	/**
172
	 * Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete()
173
	 * @var boolean
174
	 */
175
	protected $brokenOnDelete = false;
176
177
	/**
178
	 * Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite()
179
	 * @var boolean
180
	 */
181
	protected $brokenOnWrite = false;
182
183
	/**
184
	 * @config
185
	 * @var boolean Should dataobjects be validated before they are written?
186
	 * Caution: Validation can contain safeguards against invalid/malicious data,
187
	 * and check permission levels (e.g. on {@link Group}). Therefore it is recommended
188
	 * to only disable validation for very specific use cases.
189
	 */
190
	private static $validation_enabled = true;
191
192
	/**
193
	 * Static caches used by relevant functions.
194
	 */
195
	protected static $_cache_has_own_table = array();
196
	protected static $_cache_get_one;
197
	protected static $_cache_get_class_ancestry;
198
	protected static $_cache_composite_fields = array();
199
	protected static $_cache_database_fields = array();
200
	protected static $_cache_field_labels = array();
201
202
	/**
203
	 * Base fields which are not defined in static $db
204
	 *
205
	 * @config
206
	 * @var array
207
	 */
208
	private static $fixed_fields = array(
209
		'ID' => 'PrimaryKey',
210
		'ClassName' => 'DBClassName',
211
		'LastEdited' => 'SS_Datetime',
212
		'Created' => 'SS_Datetime',
213
	);
214
215
	/**
216
	 * Core dataobject extensions
217
	 *
218
	 * @config
219
	 * @var array
220
	 */
221
	private static $extensions = array(
222
		'AssetControl' => '\\SilverStripe\\Filesystem\\AssetControlExtension'
223
	);
224
225
	/**
226
	 * Non-static relationship cache, indexed by component name.
227
	 */
228
	protected $components;
229
230
	/**
231
	 * Non-static cache of has_many and many_many relations that can't be written until this object is saved.
232
	 */
233
	protected $unsavedRelations;
234
235
	/**
236
	 * Return the complete map of fields to specification on this object, including fixed_fields.
237
	 * "ID" will be included on every table.
238
	 *
239
	 * Composite DB field specifications are returned by reference if necessary, but not in the return
240
	 * array.
241
	 *
242
	 * Can be called directly on an object. E.g. Member::database_fields()
243
	 *
244
	 * @param string $class Class name to query from
245
	 * @return array Map of fieldname to specification, similiar to {@link DataObject::$db}.
246
	 */
247
	public static function database_fields($class = null) {
248
		if(empty($class)) {
249
			$class = get_called_class();
250
		}
251
252
		// Refresh cache
253
		self::cache_database_fields($class);
254
255
		// Return cached values
256
		return self::$_cache_database_fields[$class];
257
	}
258
259
	/**
260
	 * Cache all database and composite fields for the given class.
261
	 * Will do nothing if already cached
262
	 *
263
	 * @param string $class Class name to cache
264
	 */
265
	protected static function cache_database_fields($class) {
266
		// Skip if already cached
267
		if( isset(self::$_cache_database_fields[$class])
268
			&& isset(self::$_cache_composite_fields[$class])
269
		) {
270
			return;
271
		}
272
273
		$compositeFields = array();
274
		$dbFields = array();
275
276
		// Ensure fixed fields appear at the start
277
		$fixedFields = self::config()->fixed_fields;
0 ignored issues
show
Documentation introduced by
The property fixed_fields does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
278
		if(get_parent_class($class) === 'DataObject') {
279
			// Merge fixed with ClassName spec and custom db fields
280
			$dbFields = $fixedFields;
281
		} else {
282
			$dbFields['ID'] = $fixedFields['ID'];
283
		}
284
285
		// Check each DB value as either a field or composite field
286
		$db = Config::inst()->get($class, 'db', Config::UNINHERITED) ?: array();
287
		foreach($db as $fieldName => $fieldSpec) {
0 ignored issues
show
Bug introduced by
The expression $db of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
288
			$fieldClass = strtok($fieldSpec, '(');
289
			if(singleton($fieldClass) instanceof DBComposite) {
290
				$compositeFields[$fieldName] = $fieldSpec;
291
			} else {
292
				$dbFields[$fieldName] = $fieldSpec;
293
			}
294
		}
295
296
		// Add in all has_ones
297
		$hasOne = Config::inst()->get($class, 'has_one', Config::UNINHERITED) ?: array();
298
		foreach($hasOne as $fieldName => $hasOneClass) {
0 ignored issues
show
Bug introduced by
The expression $hasOne of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
299
			if($hasOneClass === 'DataObject') {
300
				$compositeFields[$fieldName] = 'PolymorphicForeignKey';
301
			} else {
302
				$dbFields["{$fieldName}ID"] = 'ForeignKey';
303
			}
304
		}
305
306
		// Merge composite fields into DB
307
		foreach($compositeFields as $fieldName => $fieldSpec) {
308
			$fieldObj = Object::create_from_string($fieldSpec, $fieldName);
309
			$fieldObj->setTable($class);
310
			$nestedFields = $fieldObj->compositeDatabaseFields();
311
			foreach($nestedFields as $nestedName => $nestedSpec) {
312
				$dbFields["{$fieldName}{$nestedName}"] = $nestedSpec;
313
			}
314
		}
315
316
		// Return cached results
317
		self::$_cache_database_fields[$class] = $dbFields;
318
		self::$_cache_composite_fields[$class] = $compositeFields;
319
	}
320
321
	/**
322
	 * Get all database columns explicitly defined on a class in {@link DataObject::$db}
323
	 * and {@link DataObject::$has_one}. Resolves instances of {@link DBComposite}
324
	 * into the actual database fields, rather than the name of the field which
325
	 * might not equate a database column.
326
	 *
327
	 * Does not include "base fields" like "ID", "ClassName", "Created", "LastEdited",
328
	 * see {@link database_fields()}.
329
	 *
330
	 * Can be called directly on an object. E.g. Member::custom_database_fields()
331
	 *
332
	 * @uses DBComposite->compositeDatabaseFields()
333
	 *
334
	 * @param string $class Class name to query from
335
	 * @return array Map of fieldname to specification, similiar to {@link DataObject::$db}.
336
	 */
337
	public static function custom_database_fields($class = null) {
338
		if(empty($class)) {
339
			$class = get_called_class();
340
		}
341
342
		// Get all fields
343
		$fields = self::database_fields($class);
344
345
		// Remove fixed fields. This assumes that NO fixed_fields are composite
346
		$fields = array_diff_key($fields, self::config()->fixed_fields);
347
		return $fields;
348
	}
349
350
	/**
351
	 * Returns the field class if the given db field on the class is a composite field.
352
	 * Will check all applicable ancestor classes and aggregate results.
353
	 *
354
	 * @param string $class Class to check
355
	 * @param string $name Field to check
356
	 * @param boolean $aggregated True if parent classes should be checked, or false to limit to this class
357
	 * @return string|false Class spec name of composite field if it exists, or false if not
358
	 */
359
	public static function is_composite_field($class, $name, $aggregated = true) {
360
		$fields = self::composite_fields($class, $aggregated);
361
		return isset($fields[$name]) ? $fields[$name] : false;
362
	}
363
364
	/**
365
	 * Returns a list of all the composite if the given db field on the class is a composite field.
366
	 * Will check all applicable ancestor classes and aggregate results.
367
	 *
368
	 * Can be called directly on an object. E.g. Member::composite_fields(), or Member::composite_fields(null, true)
369
	 * to aggregate.
370
	 *
371
	 * Includes composite has_one (Polymorphic) fields
372
	 *
373
	 * @param string $class Name of class to check
374
	 * @param bool $aggregated Include fields in entire hierarchy, rather than just on this table
375
	 * @return array List of composite fields and their class spec
376
	 */
377
	public static function composite_fields($class = null, $aggregated = true) {
378
		// Check $class
379
		if(empty($class)) {
380
			$class = get_called_class();
381
		}
382
		if($class === 'DataObject') {
383
			return array();
384
		}
385
386
		// Refresh cache
387
		self::cache_database_fields($class);
388
389
		// Get fields for this class
390
		$compositeFields = self::$_cache_composite_fields[$class];
391
		if(!$aggregated) {
392
			return $compositeFields;
393
		}
394
395
		// Recursively merge
396
		return array_merge(
397
			$compositeFields,
398
			self::composite_fields(get_parent_class($class))
399
		);
400
	}
401
402
	/**
403
	 * Construct a new DataObject.
404
	 *
405
	 * @param array|null $record This will be null for a new database record.  Alternatively, you can pass an array of
406
	 * field values.  Normally this contructor is only used by the internal systems that get objects from the database.
407
	 * @param boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods.
408
	 *                             Singletons don't have their defaults set.
409
	 * @param DataModel $model
410
	 * @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects.
411
	 */
412
	public function __construct($record = null, $isSingleton = false, $model = null, $queryParams = array()) {
413
		parent::__construct();
414
415
		// Set query params on the DataObject to tell the lazy loading mechanism the context the object creation context
416
		$this->setSourceQueryParams($queryParams);
417
418
		// Set the fields data.
419
		if(!$record) {
420
			$record = array(
421
				'ID' => 0,
422
				'ClassName' => get_class($this),
423
				'RecordClassName' => get_class($this)
424
			);
425
		}
426
427
		if(!is_array($record) && !is_a($record, "stdClass")) {
428
			if(is_object($record)) $passed = "an object of type '$record->class'";
429
			else $passed = "The value '$record'";
430
431
			user_error("DataObject::__construct passed $passed.  It's supposed to be passed an array,"
432
				. " taken straight from the database.  Perhaps you should use DataList::create()->First(); instead?",
433
				E_USER_WARNING);
434
			$record = null;
435
		}
436
437
		if(is_a($record, "stdClass")) {
438
			$record = (array)$record;
439
		}
440
441
		// Set $this->record to $record, but ignore NULLs
442
		$this->record = array();
443
		foreach($record as $k => $v) {
0 ignored issues
show
Bug introduced by
The expression $record of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
444
			// Ensure that ID is stored as a number and not a string
445
			// To do: this kind of clean-up should be done on all numeric fields, in some relatively
446
			// performant manner
447
			if($v !== null) {
448
				if($k == 'ID' && is_numeric($v)) $this->record[$k] = (int)$v;
449
				else $this->record[$k] = $v;
450
			}
451
		}
452
453
		// Identify fields that should be lazy loaded, but only on existing records
454
		if(!empty($record['ID'])) {
455
			$currentObj = get_class($this);
456
			while($currentObj != 'DataObject') {
457
				$fields = self::custom_database_fields($currentObj);
458
				foreach($fields as $field => $type) {
459
					if(!array_key_exists($field, $record)) $this->record[$field.'_Lazy'] = $currentObj;
460
				}
461
				$currentObj = get_parent_class($currentObj);
462
			}
463
		}
464
465
		$this->original = $this->record;
466
467
		// Keep track of the modification date of all the data sourced to make this page
468
		// From this we create a Last-Modified HTTP header
469
		if(isset($record['LastEdited'])) {
470
			HTTP::register_modification_date($record['LastEdited']);
471
		}
472
473
		// this must be called before populateDefaults(), as field getters on a DataObject
474
		// may call getComponent() and others, which rely on $this->model being set.
475
		$this->model = $model ? $model : DataModel::inst();
476
477
		// Must be called after parent constructor
478
		if(!$isSingleton && (!isset($this->record['ID']) || !$this->record['ID'])) {
479
			$this->populateDefaults();
480
		}
481
482
		// prevent populateDefaults() and setField() from marking overwritten defaults as changed
483
		$this->changed = array();
484
	}
485
486
	/**
487
	 * Set the DataModel
488
	 * @param DataModel $model
489
	 * @return DataObject $this
490
	 */
491
	public function setDataModel(DataModel $model) {
492
		$this->model = $model;
493
		return $this;
494
	}
495
496
	/**
497
	 * Destroy all of this objects dependant objects and local caches.
498
	 * You'll need to call this to get the memory of an object that has components or extensions freed.
499
	 */
500
	public function destroy() {
501
		//$this->destroyed = true;
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...
502
		gc_collect_cycles();
503
		$this->flushCache(false);
504
	}
505
506
	/**
507
	 * Create a duplicate of this node.
508
	 * Note: now also duplicates relations.
509
	 *
510
	 * @param bool $doWrite Perform a write() operation before returning the object.
511
	 * If this is true, it will create the duplicate in the database.
512
	 * @return DataObject A duplicate of this node. The exact type will be the type of this node.
513
	 */
514
	public function duplicate($doWrite = true) {
515
		$className = $this->class;
516
		$clone = new $className( $this->toMap(), false, $this->model );
517
		$clone->ID = 0;
518
519
		$clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite);
520
		if($doWrite) {
521
			$clone->write();
522
			$this->duplicateManyManyRelations($this, $clone);
523
		}
524
		$clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite);
525
526
		return $clone;
527
	}
528
529
	/**
530
	 * Copies the many_many and belongs_many_many relations from one object to another instance of the name of object
531
	 * The destinationObject must be written to the database already and have an ID. Writing is performed
532
	 * automatically when adding the new relations.
533
	 *
534
	 * @param DataObject $sourceObject the source object to duplicate from
535
	 * @param DataObject $destinationObject the destination object to populate with the duplicated relations
536
	 * @return DataObject with the new many_many relations copied in
537
	 */
538
	protected function duplicateManyManyRelations($sourceObject, $destinationObject) {
539
		if (!$destinationObject || $destinationObject->ID < 1) {
540
			user_error("Can't duplicate relations for an object that has not been written to the database",
541
				E_USER_ERROR);
542
		}
543
544
		//duplicate complex relations
545
		// DO NOT copy has_many relations, because copying the relation would result in us changing the has_one
546
		// relation on the other side of this relation to point at the copy and no longer the original (being a
547
		// has_one, it can only point at one thing at a time). So, all relations except has_many can and are copied
548
		if ($sourceObject->hasOne()) foreach($sourceObject->hasOne() as $name => $type) {
549
			$this->duplicateRelations($sourceObject, $destinationObject, $name);
550
		}
551
		if ($sourceObject->manyMany()) foreach($sourceObject->manyMany() as $name => $type) {
552
			//many_many include belongs_many_many
553
			$this->duplicateRelations($sourceObject, $destinationObject, $name);
554
		}
555
556
		return $destinationObject;
557
	}
558
559
	/**
560
	 * Helper function to duplicate relations from one object to another
561
	 * @param $sourceObject the source object to duplicate from
562
	 * @param $destinationObject the destination object to populate with the duplicated relations
563
	 * @param $name the name of the relation to duplicate (e.g. members)
564
	 */
565
	private function duplicateRelations($sourceObject, $destinationObject, $name) {
566
		$relations = $sourceObject->$name();
567
		if ($relations) {
568
			if ($relations instanceOf RelationList) {   //many-to-something relation
569
				if ($relations->Count() > 0) {  //with more than one thing it is related to
570
					foreach($relations as $relation) {
571
						$destinationObject->$name()->add($relation);
572
					}
573
				}
574
			} else {    //one-to-one relation
575
				$destinationObject->{"{$name}ID"} = $relations->ID;
576
			}
577
		}
578
	}
579
580
	public function getObsoleteClassName() {
581
		$className = $this->getField("ClassName");
582
		if (!ClassInfo::exists($className)) return $className;
583
	}
584
585
	public function getClassName() {
586
		$className = $this->getField("ClassName");
587
		if (!ClassInfo::exists($className)) return get_class($this);
588
		return $className;
589
	}
590
591
	/**
592
	 * Set the ClassName attribute. {@link $class} is also updated.
593
	 * Warning: This will produce an inconsistent record, as the object
594
	 * instance will not automatically switch to the new subclass.
595
	 * Please use {@link newClassInstance()} for this purpose,
596
	 * or destroy and reinstanciate the record.
597
	 *
598
	 * @param string $className The new ClassName attribute (a subclass of {@link DataObject})
599
	 * @return DataObject $this
600
	 */
601
	public function setClassName($className) {
602
		$className = trim($className);
603
		if(!$className || !is_subclass_of($className, 'DataObject')) return;
604
605
		$this->class = $className;
606
		$this->setField("ClassName", $className);
607
		return $this;
608
	}
609
610
	/**
611
	 * Create a new instance of a different class from this object's record.
612
	 * This is useful when dynamically changing the type of an instance. Specifically,
613
	 * it ensures that the instance of the class is a match for the className of the
614
	 * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName}
615
	 * property manually before calling this method, as it will confuse change detection.
616
	 *
617
	 * If the new class is different to the original class, defaults are populated again
618
	 * because this will only occur automatically on instantiation of a DataObject if
619
	 * there is no record, or the record has no ID. In this case, we do have an ID but
620
	 * we still need to repopulate the defaults.
621
	 *
622
	 * @param string $newClassName The name of the new class
623
	 *
624
	 * @return DataObject The new instance of the new class, The exact type will be of the class name provided.
625
	 */
626
	public function newClassInstance($newClassName) {
627
		$originalClass = $this->ClassName;
628
		$newInstance = new $newClassName(array_merge(
629
			$this->record,
630
			array(
631
				'ClassName' => $originalClass,
632
				'RecordClassName' => $originalClass,
633
			)
634
		), false, $this->model);
635
636
		if($newClassName != $originalClass) {
637
			$newInstance->setClassName($newClassName);
638
			$newInstance->populateDefaults();
639
			$newInstance->forceChange();
640
		}
641
642
		return $newInstance;
643
	}
644
645
	/**
646
	 * Adds methods from the extensions.
647
	 * Called by Object::__construct() once per class.
648
	 */
649
	public function defineMethods() {
650
		parent::defineMethods();
651
652
		// Define the extra db fields - this is only necessary for extensions added in the
653
		// class definition.  Object::add_extension() will call this at definition time for
654
		// those objects, which is a better mechanism.  Perhaps extensions defined inside the
655
		// class def can somehow be applied at definiton time also?
656
		if($this->extension_instances) foreach($this->extension_instances as $i => $instance) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->extension_instances of type Extension[] 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...
657
			if(!$instance->class) {
658
				$class = get_class($instance);
659
				user_error("DataObject::defineMethods(): Please ensure {$class}::__construct() calls"
660
					. " parent::__construct()", E_USER_ERROR);
661
			}
662
		}
663
664
		if($this->class == 'DataObject') return;
665
666
		// Set up accessors for joined items
667
		if($manyMany = $this->manyMany()) {
668
			foreach($manyMany as $relationship => $class) {
669
				$this->addWrapperMethod($relationship, 'getManyManyComponents');
670
			}
671
		}
672
		if($hasMany = $this->hasMany()) {
673
674
			foreach($hasMany as $relationship => $class) {
0 ignored issues
show
Bug introduced by
The expression $hasMany of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
675
				$this->addWrapperMethod($relationship, 'getComponents');
676
			}
677
678
		}
679
		if($hasOne = $this->hasOne()) {
680
			foreach($hasOne as $relationship => $class) {
681
				$this->addWrapperMethod($relationship, 'getComponent');
682
			}
683
		}
684
		if($belongsTo = $this->belongsTo()) foreach(array_keys($belongsTo) as $relationship) {
685
			$this->addWrapperMethod($relationship, 'getComponent');
686
		}
687
	}
688
689
	/**
690
	 * Returns true if this object "exists", i.e., has a sensible value.
691
	 * The default behaviour for a DataObject is to return true if
692
	 * the object exists in the database, you can override this in subclasses.
693
	 *
694
	 * @return boolean true if this object exists
695
	 */
696
	public function exists() {
697
		return (isset($this->record['ID']) && $this->record['ID'] > 0);
698
	}
699
700
	/**
701
	 * Returns TRUE if all values (other than "ID") are
702
	 * considered empty (by weak boolean comparison).
703
	 *
704
	 * @return boolean
705
	 */
706
	public function isEmpty() {
707
		$fixed = $this->config()->fixed_fields;
0 ignored issues
show
Documentation introduced by
The property fixed_fields does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
708
		foreach($this->toMap() as $field => $value){
709
			// only look at custom fields
710
			if(isset($fixed[$field])) {
711
				continue;
712
			}
713
714
			$dbObject = $this->dbObject($field);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $dbObject is correct as $this->dbObject($field) (which targets DataObject::dbObject()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
715
			if(!$dbObject) {
716
				continue;
717
			}
718
			if($dbObject->exists()) {
719
				return false;
720
			}
721
		}
722
		return true;
723
	}
724
725
	/**
726
	 * Get the user friendly singular name of this DataObject.
727
	 * If the name is not defined (by redefining $singular_name in the subclass),
728
	 * this returns the class name.
729
	 *
730
	 * @return string User friendly singular name of this DataObject
731
	 */
732
	public function singular_name() {
733
		if(!$name = $this->stat('singular_name')) {
734
			$name = ucwords(trim(strtolower(preg_replace('/_?([A-Z])/', ' $1', $this->class))));
735
		}
736
737
		return $name;
738
	}
739
740
	/**
741
	 * Get the translated user friendly singular name of this DataObject
742
	 * same as singular_name() but runs it through the translating function
743
	 *
744
	 * Translating string is in the form:
745
	 *     $this->class.SINGULARNAME
746
	 * Example:
747
	 *     Page.SINGULARNAME
748
	 *
749
	 * @return string User friendly translated singular name of this DataObject
750
	 */
751
	public function i18n_singular_name() {
752
		return _t($this->class.'.SINGULARNAME', $this->singular_name());
753
	}
754
755
	/**
756
	 * Get the user friendly plural name of this DataObject
757
	 * If the name is not defined (by renaming $plural_name in the subclass),
758
	 * this returns a pluralised version of the class name.
759
	 *
760
	 * @return string User friendly plural name of this DataObject
761
	 */
762
	public function plural_name() {
763
		if($name = $this->stat('plural_name')) {
764
			return $name;
765
		} else {
766
			$name = $this->singular_name();
767
			//if the penultimate character is not a vowel, replace "y" with "ies"
768
			if (preg_match('/[^aeiou]y$/i', $name)) {
769
				$name = substr($name,0,-1) . 'ie';
770
			}
771
			return ucfirst($name . 's');
772
		}
773
	}
774
775
	/**
776
	 * Get the translated user friendly plural name of this DataObject
777
	 * Same as plural_name but runs it through the translation function
778
	 * Translation string is in the form:
779
	 *      $this->class.PLURALNAME
780
	 * Example:
781
	 *      Page.PLURALNAME
782
	 *
783
	 * @return string User friendly translated plural name of this DataObject
784
	 */
785
	public function i18n_plural_name()
786
	{
787
		$name = $this->plural_name();
788
		return _t($this->class.'.PLURALNAME', $name);
789
	}
790
791
	/**
792
	 * Standard implementation of a title/label for a specific
793
	 * record. Tries to find properties 'Title' or 'Name',
794
	 * and falls back to the 'ID'. Useful to provide
795
	 * user-friendly identification of a record, e.g. in errormessages
796
	 * or UI-selections.
797
	 *
798
	 * Overload this method to have a more specialized implementation,
799
	 * e.g. for an Address record this could be:
800
	 * <code>
801
	 * function getTitle() {
802
	 *   return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
803
	 * }
804
	 * </code>
805
	 *
806
	 * @return string
807
	 */
808
	public function getTitle() {
809
		if($this->hasDatabaseField('Title')) return $this->getField('Title');
810
		if($this->hasDatabaseField('Name')) return $this->getField('Name');
811
812
		return "#{$this->ID}";
813
	}
814
815
	/**
816
	 * Returns the associated database record - in this case, the object itself.
817
	 * This is included so that you can call $dataOrController->data() and get a DataObject all the time.
818
	 *
819
	 * @return DataObject Associated database record
820
	 */
821
	public function data() {
822
		return $this;
823
	}
824
825
	/**
826
	 * Convert this object to a map.
827
	 *
828
	 * @return array The data as a map.
829
	 */
830
	public function toMap() {
831
		$this->loadLazyFields();
832
		return $this->record;
833
	}
834
835
	/**
836
	 * Return all currently fetched database fields.
837
	 *
838
	 * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
839
	 * Obviously, this makes it a lot faster.
840
	 *
841
	 * @return array The data as a map.
842
	 */
843
	public function getQueriedDatabaseFields() {
844
		return $this->record;
845
	}
846
847
	/**
848
	 * Update a number of fields on this object, given a map of the desired changes.
849
	 *
850
	 * The field names can be simple names, or you can use a dot syntax to access $has_one relations.
851
	 * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
852
	 *
853
	 * update() doesn't write the main object, but if you use the dot syntax, it will write()
854
	 * the related objects that it alters.
855
	 *
856
	 * @param array $data A map of field name to data values to update.
857
	 * @return DataObject $this
858
	 */
859
	public function update($data) {
860
		foreach($data as $k => $v) {
861
			// Implement dot syntax for updates
862
			if(strpos($k,'.') !== false) {
863
				$relations = explode('.', $k);
864
				$fieldName = array_pop($relations);
865
				$relObj = $this;
866
				foreach($relations as $i=>$relation) {
867
					// no support for has_many or many_many relationships,
868
					// as the updater wouldn't know which object to write to (or create)
869
					if($relObj->$relation() instanceof DataObject) {
870
						$parentObj = $relObj;
871
						$relObj = $relObj->$relation();
872
						// If the intermediate relationship objects have been created, then write them
873
						if($i<sizeof($relation)-1 && !$relObj->ID || (!$relObj->ID && $parentObj != $this)) {
874
							$relObj->write();
875
							$relatedFieldName = $relation."ID";
876
							$parentObj->$relatedFieldName = $relObj->ID;
877
							$parentObj->write();
878
						}
879
					} else {
880
						user_error(
881
							"DataObject::update(): Can't traverse relationship '$relation'," .
882
							"it has to be a has_one relationship or return a single DataObject",
883
							E_USER_NOTICE
884
						);
885
						// unset relation object so we don't write properties to the wrong object
886
						unset($relObj);
887
						break;
888
					}
889
				}
890
891
				if($relObj) {
892
					$relObj->$fieldName = $v;
893
					$relObj->write();
894
					$relatedFieldName = $relation."ID";
0 ignored issues
show
Bug introduced by
The variable $relation seems to be defined by a foreach iteration on line 866. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
895
					$this->$relatedFieldName = $relObj->ID;
896
					$relObj->flushCache();
897
				} else {
898
					user_error("Couldn't follow dot syntax '$k' on '$this->class' object", E_USER_WARNING);
899
				}
900
			} else {
901
				$this->$k = $v;
902
			}
903
		}
904
		return $this;
905
	}
906
907
	/**
908
	 * Pass changes as a map, and try to
909
	 * get automatic casting for these fields.
910
	 * Doesn't write to the database. To write the data,
911
	 * use the write() method.
912
	 *
913
	 * @param array $data A map of field name to data values to update.
914
	 * @return DataObject $this
915
	 */
916
	public function castedUpdate($data) {
917
		foreach($data as $k => $v) {
918
			$this->setCastedField($k,$v);
919
		}
920
		return $this;
921
	}
922
923
	/**
924
	 * Merges data and relations from another object of same class,
925
	 * without conflict resolution. Allows to specify which
926
	 * dataset takes priority in case its not empty.
927
	 * has_one-relations are just transferred with priority 'right'.
928
	 * has_many and many_many-relations are added regardless of priority.
929
	 *
930
	 * Caution: has_many/many_many relations are moved rather than duplicated,
931
	 * meaning they are not connected to the merged object any longer.
932
	 * Caution: Just saves updated has_many/many_many relations to the database,
933
	 * doesn't write the updated object itself (just writes the object-properties).
934
	 * Caution: Does not delete the merged object.
935
	 * Caution: Does now overwrite Created date on the original object.
936
	 *
937
	 * @param $obj DataObject
938
	 * @param $priority String left|right Determines who wins in case of a conflict (optional)
939
	 * @param $includeRelations Boolean Merge any existing relations (optional)
940
	 * @param $overwriteWithEmpty Boolean Overwrite existing left values with empty right values.
941
	 *                            Only applicable with $priority='right'. (optional)
942
	 * @return Boolean
943
	 */
944
	public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false) {
945
		$leftObj = $this;
946
947
		if($leftObj->ClassName != $rightObj->ClassName) {
948
			// we can't merge similiar subclasses because they might have additional relations
949
			user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
950
			(expected '{$leftObj->ClassName}').", E_USER_WARNING);
951
			return false;
952
		}
953
954
		if(!$rightObj->ID) {
955
			user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
956
				to make sure all relations are transferred properly.').", E_USER_WARNING);
957
			return false;
958
		}
959
960
		// makes sure we don't merge data like ID or ClassName
961
		$leftData = $leftObj->db();
962
		$rightData = $rightObj->db();
963
964
		foreach($rightData as $key=>$rightSpec) {
965
			// Don't merge ID
966
			if($key === 'ID') {
967
				continue;
968
			}
969
970
			// Only merge relations if allowed
971
			if($rightSpec === 'ForeignKey' && !$includeRelations) {
972
				continue;
973
			}
974
975
			// don't merge conflicting values if priority is 'left'
976
			if($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) {
977
				continue;
978
			}
979
980
			// don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
981
			if($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) {
982
				continue;
983
			}
984
985
			// TODO remove redundant merge of has_one fields
986
			$leftObj->{$key} = $rightObj->{$key};
987
		}
988
989
		// merge relations
990
		if($includeRelations) {
991
			if($manyMany = $this->manyMany()) {
992
				foreach($manyMany as $relationship => $class) {
993
					$leftComponents = $leftObj->getManyManyComponents($relationship);
994
					$rightComponents = $rightObj->getManyManyComponents($relationship);
995
					if($rightComponents && $rightComponents->exists()) {
996
						$leftComponents->addMany($rightComponents->column('ID'));
997
					}
998
					$leftComponents->write();
999
				}
1000
			}
1001
1002
			if($hasMany = $this->hasMany()) {
1003
				foreach($hasMany as $relationship => $class) {
0 ignored issues
show
Bug introduced by
The expression $hasMany of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1004
					$leftComponents = $leftObj->getComponents($relationship);
1005
					$rightComponents = $rightObj->getComponents($relationship);
1006
					if($rightComponents && $rightComponents->exists()) {
1007
						$leftComponents->addMany($rightComponents->column('ID'));
1008
					}
1009
					$leftComponents->write();
1010
				}
1011
1012
			}
1013
		}
1014
1015
		return true;
1016
	}
1017
1018
	/**
1019
	 * Forces the record to think that all its data has changed.
1020
	 * Doesn't write to the database. Only sets fields as changed
1021
	 * if they are not already marked as changed.
1022
	 *
1023
	 * @return DataObject $this
1024
	 */
1025
	public function forceChange() {
1026
		// Ensure lazy fields loaded
1027
		$this->loadLazyFields();
1028
1029
		// $this->record might not contain the blank values so we loop on $this->inheritedDatabaseFields() as well
1030
		$fieldNames = array_unique(array_merge(
1031
			array_keys($this->record),
1032
			array_keys($this->db())
1033
		));
1034
1035
		foreach($fieldNames as $fieldName) {
1036
			if(!isset($this->changed[$fieldName])) $this->changed[$fieldName] = self::CHANGE_STRICT;
1037
			// Populate the null values in record so that they actually get written
1038
			if(!isset($this->record[$fieldName])) $this->record[$fieldName] = null;
1039
		}
1040
1041
		// @todo Find better way to allow versioned to write a new version after forceChange
1042
		if($this->isChanged('Version')) unset($this->changed['Version']);
1043
		return $this;
1044
	}
1045
1046
	/**
1047
	 * Validate the current object.
1048
	 *
1049
	 * By default, there is no validation - objects are always valid!  However, you can overload this method in your
1050
	 * DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
1051
	 *
1052
	 * Invalid objects won't be able to be written - a warning will be thrown and no write will occur.  onBeforeWrite()
1053
	 * and onAfterWrite() won't get called either.
1054
	 *
1055
	 * It is expected that you call validate() in your own application to test that an object is valid before
1056
	 * attempting a write, and respond appropriately if it isn't.
1057
	 *
1058
	 * @see {@link ValidationResult}
1059
	 * @return ValidationResult
1060
	 */
1061
	public function validate() {
1062
		$result = ValidationResult::create();
1063
		$this->extend('validate', $result);
1064
		return $result;
1065
	}
1066
1067
	/**
1068
	 * Public accessor for {@see DataObject::validate()}
1069
	 *
1070
	 * @return ValidationResult
1071
	 */
1072
	public function doValidate() {
1073
		Deprecation::notice('5.0', 'Use validate');
1074
		return $this->validate();
1075
	}
1076
1077
	/**
1078
	 * Event handler called before writing to the database.
1079
	 * You can overload this to clean up or otherwise process data before writing it to the
1080
	 * database.  Don't forget to call parent::onBeforeWrite(), though!
1081
	 *
1082
	 * This called after {@link $this->validate()}, so you can be sure that your data is valid.
1083
	 *
1084
	 * @uses DataExtension->onBeforeWrite()
1085
	 */
1086
	protected function onBeforeWrite() {
1087
		$this->brokenOnWrite = false;
1088
1089
		$dummy = null;
1090
		$this->extend('onBeforeWrite', $dummy);
1091
	}
1092
1093
	/**
1094
	 * Event handler called after writing to the database.
1095
	 * You can overload this to act upon changes made to the data after it is written.
1096
	 * $this->changed will have a record
1097
	 * database.  Don't forget to call parent::onAfterWrite(), though!
1098
	 *
1099
	 * @uses DataExtension->onAfterWrite()
1100
	 */
1101
	protected function onAfterWrite() {
1102
		$dummy = null;
1103
		$this->extend('onAfterWrite', $dummy);
1104
	}
1105
1106
	/**
1107
	 * Event handler called before deleting from the database.
1108
	 * You can overload this to clean up or otherwise process data before delete this
1109
	 * record.  Don't forget to call parent::onBeforeDelete(), though!
1110
	 *
1111
	 * @uses DataExtension->onBeforeDelete()
1112
	 */
1113
	protected function onBeforeDelete() {
1114
		$this->brokenOnDelete = false;
1115
1116
		$dummy = null;
1117
		$this->extend('onBeforeDelete', $dummy);
1118
	}
1119
1120
	protected function onAfterDelete() {
1121
		$this->extend('onAfterDelete');
1122
	}
1123
1124
	/**
1125
	 * Load the default values in from the self::$defaults array.
1126
	 * Will traverse the defaults of the current class and all its parent classes.
1127
	 * Called by the constructor when creating new records.
1128
	 *
1129
	 * @uses DataExtension->populateDefaults()
1130
	 * @return DataObject $this
1131
	 */
1132
	public function populateDefaults() {
1133
		$classes = array_reverse(ClassInfo::ancestry($this));
1134
1135
		foreach($classes as $class) {
1136
			$defaults = Config::inst()->get($class, 'defaults', Config::UNINHERITED);
1137
1138
			if($defaults && !is_array($defaults)) {
1139
				user_error("Bad '$this->class' defaults given: " . var_export($defaults, true),
1140
					E_USER_WARNING);
1141
				$defaults = null;
1142
			}
1143
1144
			if($defaults) foreach($defaults as $fieldName => $fieldValue) {
0 ignored issues
show
Bug introduced by
The expression $defaults of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1145
				// SRM 2007-03-06: Stricter check
1146
				if(!isset($this->$fieldName) || $this->$fieldName === null) {
1147
					$this->$fieldName = $fieldValue;
1148
				}
1149
				// Set many-many defaults with an array of ids
1150
				if(is_array($fieldValue) && $this->manyManyComponent($fieldName)) {
1151
					$manyManyJoin = $this->$fieldName();
1152
					$manyManyJoin->setByIdList($fieldValue);
1153
				}
1154
			}
1155
			if($class == 'DataObject') {
1156
				break;
1157
			}
1158
		}
1159
1160
		$this->extend('populateDefaults');
1161
		return $this;
1162
	}
1163
1164
	/**
1165
	 * Determine validation of this object prior to write
1166
	 *
1167
	 * @return ValidationException Exception generated by this write, or null if valid
1168
	 */
1169
	protected function validateWrite() {
1170
		if ($this->ObsoleteClassName) {
0 ignored issues
show
Bug introduced by
The property ObsoleteClassName does not seem to exist. Did you mean ClassName?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1171
			return new ValidationException(
1172
				"Object is of class '{$this->ObsoleteClassName}' which doesn't exist - ".
0 ignored issues
show
Bug introduced by
The property ObsoleteClassName does not seem to exist. Did you mean ClassName?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1173
				"you need to change the ClassName before you can write it",
1174
				E_USER_WARNING
1175
			);
1176
		}
1177
1178
		if(Config::inst()->get('DataObject', 'validation_enabled')) {
1179
			$result = $this->validate();
1180
			if (!$result->valid()) {
1181
				return new ValidationException(
1182
					$result,
1183
					$result->message(),
1184
					E_USER_WARNING
1185
				);
1186
			}
1187
		}
1188
	}
1189
1190
	/**
1191
	 * Prepare an object prior to write
1192
	 *
1193
	 * @throws ValidationException
1194
	 */
1195
	protected function preWrite() {
1196
		// Validate this object
1197
		if($writeException = $this->validateWrite()) {
1198
			// Used by DODs to clean up after themselves, eg, Versioned
1199
			$this->invokeWithExtensions('onAfterSkippedWrite');
1200
			throw $writeException;
1201
		}
1202
1203
		// Check onBeforeWrite
1204
		$this->brokenOnWrite = true;
1205
		$this->onBeforeWrite();
1206
		if($this->brokenOnWrite) {
1207
			user_error("$this->class has a broken onBeforeWrite() function."
1208
				. " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
1209
		}
1210
	}
1211
1212
	/**
1213
	 * Detects and updates all changes made to this object
1214
	 *
1215
	 * @param bool $forceChanges If set to true, force all fields to be treated as changed
1216
	 * @return bool True if any changes are detected
1217
	 */
1218
	protected function updateChanges($forceChanges = false) {
1219
		// Update the changed array with references to changed obj-fields
1220
		foreach($this->record as $field => $value) {
1221
			// Only mark ID as changed if $forceChanges
1222
			if($field === 'ID' && !$forceChanges) continue;
1223
			// Determine if this field should be forced, or can mark itself, changed
1224
			if($forceChanges
1225
				|| !$this->isInDB()
1226
				|| (is_object($value) && method_exists($value, 'isChanged') && $value->isChanged())
1227
			) {
1228
				$this->changed[$field] = self::CHANGE_VALUE;
1229
			}
1230
		}
1231
1232
		// Check changes exist, abort if there are no changes
1233
		return $this->changed && (bool)array_filter($this->changed);
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->changed 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...
1234
	}
1235
1236
	/**
1237
	 * Writes a subset of changes for a specific table to the given manipulation
1238
	 *
1239
	 * @param string $baseTable Base table
1240
	 * @param string $now Timestamp to use for the current time
1241
	 * @param bool $isNewRecord Whether this should be treated as a new record write
1242
	 * @param array $manipulation Manipulation to write to
1243
	 * @param string $class Table and Class to select and write to
1244
	 */
1245
	protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class) {
1246
		$manipulation[$class] = array();
1247
1248
		// Extract records for this table
1249
		foreach($this->record as $fieldName => $fieldValue) {
1250
1251
			// Check if this record pertains to this table, and
1252
			// we're not attempting to reset the BaseTable->ID
1253
			if(	empty($this->changed[$fieldName])
1254
				|| ($class === $baseTable && $fieldName === 'ID')
1255
				|| (!self::has_own_table_database_field($class, $fieldName)
1256
					&& !self::is_composite_field($class, $fieldName, false))
0 ignored issues
show
Bug Best Practice introduced by
The expression self::is_composite_field...ass, $fieldName, false) of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1257
			) {
1258
				continue;
1259
			}
1260
1261
1262
			// if database column doesn't correlate to a DBField instance...
1263
			$fieldObj = $this->dbObject($fieldName);
1264
			if(!$fieldObj) {
1265
				$fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
1266
			}
1267
1268
			// Write to manipulation
1269
			$fieldObj->writeToManipulation($manipulation[$class]);
1270
		}
1271
1272
		// Ensure update of Created and LastEdited columns
1273
		if($baseTable === $class) {
1274
			$manipulation[$class]['fields']['LastEdited'] = $now;
1275
			if($isNewRecord) {
1276
				$manipulation[$class]['fields']['Created']
1277
					= empty($this->record['Created'])
1278
						? $now
1279
						: $this->record['Created'];
1280
				$manipulation[$class]['fields']['ClassName'] = $this->class;
1281
			}
1282
		}
1283
1284
		// Inserts done one the base table are performed in another step, so the manipulation should instead
1285
		// attempt an update, as though it were a normal update.
1286
		$manipulation[$class]['command'] = $isNewRecord ? 'insert' : 'update';
1287
		$manipulation[$class]['id'] = $this->record['ID'];
1288
	}
1289
1290
	/**
1291
	 * Ensures that a blank base record exists with the basic fixed fields for this dataobject
1292
	 *
1293
	 * Does nothing if an ID is already assigned for this record
1294
	 *
1295
	 * @param string $baseTable Base table
1296
	 * @param string $now Timestamp to use for the current time
1297
	 */
1298
	protected function writeBaseRecord($baseTable, $now) {
1299
		// Generate new ID if not specified
1300
		if($this->isInDB()) return;
1301
1302
		// Perform an insert on the base table
1303
		$insert = new SQLInsert('"'.$baseTable.'"');
1304
		$insert
1305
			->assign('"Created"', $now)
1306
			->execute();
1307
		$this->changed['ID'] = self::CHANGE_VALUE;
1308
		$this->record['ID'] = DB::get_generated_id($baseTable);
1309
	}
1310
1311
	/**
1312
	 * Generate and write the database manipulation for all changed fields
1313
	 *
1314
	 * @param string $baseTable Base table
1315
	 * @param string $now Timestamp to use for the current time
1316
	 * @param bool $isNewRecord If this is a new record
1317
	 */
1318
	protected function writeManipulation($baseTable, $now, $isNewRecord) {
1319
		// Generate database manipulations for each class
1320
		$manipulation = array();
1321
		foreach($this->getClassAncestry() as $class) {
1322
			if(self::has_own_table($class)) {
1323
				$this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
1324
			}
1325
		}
1326
1327
		// Allow extensions to extend this manipulation
1328
		$this->extend('augmentWrite', $manipulation);
1329
1330
		// New records have their insert into the base data table done first, so that they can pass the
1331
		// generated ID on to the rest of the manipulation
1332
		if($isNewRecord) {
1333
			$manipulation[$baseTable]['command'] = 'update';
1334
		}
1335
1336
		// Perform the manipulation
1337
		DB::manipulate($manipulation);
1338
	}
1339
1340
	/**
1341
	 * Writes all changes to this object to the database.
1342
	 *  - It will insert a record whenever ID isn't set, otherwise update.
1343
	 *  - All relevant tables will be updated.
1344
	 *  - $this->onBeforeWrite() gets called beforehand.
1345
	 *  - Extensions such as Versioned will ammend the database-write to ensure that a version is saved.
1346
	 *
1347
	 *  @uses DataExtension->augmentWrite()
1348
	 *
1349
	 * @param boolean $showDebug Show debugging information
1350
	 * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
1351
	 * @param boolean $forceWrite Write to database even if there are no changes
1352
	 * @param boolean $writeComponents Call write() on all associated component instances which were previously
1353
	 *                                 retrieved through {@link getComponent()}, {@link getComponents()} or
1354
	 *                                 {@link getManyManyComponents()} (Default: false)
1355
	 * @return int The ID of the record
1356
	 * @throws ValidationException Exception that can be caught and handled by the calling function
1357
	 */
1358
	public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
1359
		$now = DBDatetime::now()->Rfc2822();
1360
1361
		// Execute pre-write tasks
1362
		$this->preWrite();
1363
1364
		// Check if we are doing an update or an insert
1365
		$isNewRecord = !$this->isInDB() || $forceInsert;
1366
1367
		// Check changes exist, abort if there are none
1368
		$hasChanges = $this->updateChanges($forceInsert);
1369
		if($hasChanges || $forceWrite || $isNewRecord) {
1370
			// New records have their insert into the base data table done first, so that they can pass the
1371
			// generated primary key on to the rest of the manipulation
1372
			$baseTable = ClassInfo::baseDataClass($this->class);
1373
			$this->writeBaseRecord($baseTable, $now);
1374
1375
			// Write the DB manipulation for all changed fields
1376
			$this->writeManipulation($baseTable, $now, $isNewRecord);
1377
1378
			// If there's any relations that couldn't be saved before, save them now (we have an ID here)
1379
			$this->writeRelations();
1380
			$this->onAfterWrite();
1381
			$this->changed = array();
1382
		} else {
1383
			if($showDebug) Debug::message("no changes for DataObject");
1384
1385
			// Used by DODs to clean up after themselves, eg, Versioned
1386
			$this->invokeWithExtensions('onAfterSkippedWrite');
1387
		}
1388
1389
		// Ensure Created and LastEdited are populated
1390
		if(!isset($this->record['Created'])) {
1391
			$this->record['Created'] = $now;
1392
		}
1393
		$this->record['LastEdited'] = $now;
1394
1395
		// Write relations as necessary
1396
		if($writeComponents) $this->writeComponents(true);
1397
1398
		// Clears the cache for this object so get_one returns the correct object.
1399
		$this->flushCache();
1400
1401
		return $this->record['ID'];
1402
	}
1403
1404
	/**
1405
	 * Writes cached relation lists to the database, if possible
1406
	 */
1407
	public function writeRelations() {
1408
		if(!$this->isInDB()) return;
1409
1410
		// If there's any relations that couldn't be saved before, save them now (we have an ID here)
1411
		if($this->unsavedRelations) {
1412
			foreach($this->unsavedRelations as $name => $list) {
1413
				$list->changeToList($this->$name());
1414
			}
1415
			$this->unsavedRelations = array();
1416
		}
1417
	}
1418
1419
	/**
1420
	 * Write the cached components to the database. Cached components could refer to two different instances of the
1421
	 * same record.
1422
	 *
1423
	 * @param $recursive Recursively write components
1424
	 * @return DataObject $this
1425
	 */
1426
	public function writeComponents($recursive = false) {
1427
		if(!$this->components) return $this;
1428
1429
		foreach($this->components as $component) {
1430
			$component->write(false, false, false, $recursive);
1431
		}
1432
		return $this;
1433
	}
1434
1435
	/**
1436
	 * Delete this data object.
1437
	 * $this->onBeforeDelete() gets called.
1438
	 * Note that in Versioned objects, both Stage and Live will be deleted.
1439
	 *  @uses DataExtension->augmentSQL()
1440
	 */
1441
	public function delete() {
1442
		$this->brokenOnDelete = true;
1443
		$this->onBeforeDelete();
1444
		if($this->brokenOnDelete) {
1445
			user_error("$this->class has a broken onBeforeDelete() function."
1446
				. " Make sure that you call parent::onBeforeDelete().", E_USER_ERROR);
1447
		}
1448
1449
		// Deleting a record without an ID shouldn't do anything
1450
		if(!$this->ID) throw new LogicException("DataObject::delete() called on a DataObject without an ID");
1451
1452
		// TODO: This is quite ugly.  To improve:
1453
		//  - move the details of the delete code in the DataQuery system
1454
		//  - update the code to just delete the base table, and rely on cascading deletes in the DB to do the rest
1455
		//    obviously, that means getting requireTable() to configure cascading deletes ;-)
1456
		$srcQuery = DataList::create($this->class, $this->model)->where("ID = $this->ID")->dataQuery()->query();
1457
		foreach($srcQuery->queriedTables() as $table) {
1458
			$delete = new SQLDelete("\"$table\"", array('"ID"' => $this->ID));
1459
			$delete->execute();
1460
		}
1461
		// Remove this item out of any caches
1462
		$this->flushCache();
1463
1464
		$this->onAfterDelete();
1465
1466
		$this->OldID = $this->ID;
0 ignored issues
show
Documentation introduced by
The property OldID does not exist on object<DataObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1467
		$this->ID = 0;
1468
	}
1469
1470
	/**
1471
	 * Delete the record with the given ID.
1472
	 *
1473
	 * @param string $className The class name of the record to be deleted
1474
	 * @param int $id ID of record to be deleted
1475
	 */
1476
	public static function delete_by_id($className, $id) {
1477
		$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...
1478
		if($obj) {
1479
			$obj->delete();
1480
		} else {
1481
			user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
1482
		}
1483
	}
1484
1485
	/**
1486
	 * Get the class ancestry, including the current class name.
1487
	 * The ancestry will be returned as an array of class names, where the 0th element
1488
	 * will be the class that inherits directly from DataObject, and the last element
1489
	 * will be the current class.
1490
	 *
1491
	 * @return array Class ancestry
1492
	 */
1493
	public function getClassAncestry() {
1494
		if(!isset(self::$_cache_get_class_ancestry[$this->class])) {
1495
			self::$_cache_get_class_ancestry[$this->class] = array($this->class);
1496
			while(($class=get_parent_class(self::$_cache_get_class_ancestry[$this->class][0])) != "DataObject") {
1497
				array_unshift(self::$_cache_get_class_ancestry[$this->class], $class);
1498
			}
1499
		}
1500
		return self::$_cache_get_class_ancestry[$this->class];
1501
	}
1502
1503
	/**
1504
	 * Return a component object from a one to one relationship, as a DataObject.
1505
	 * If no component is available, an 'empty component' will be returned for
1506
	 * non-polymorphic relations, or for polymorphic relations with a class set.
1507
	 *
1508
	 * @param string $componentName Name of the component
1509
	 * @return DataObject The component object. It's exact type will be that of the component.
1510
	 * @throws Exception
1511
	 */
1512
	public function getComponent($componentName) {
1513
		if(isset($this->components[$componentName])) {
1514
			return $this->components[$componentName];
1515
		}
1516
1517
		if($class = $this->hasOneComponent($componentName)) {
1518
			$joinField = $componentName . 'ID';
1519
			$joinID    = $this->getField($joinField);
1520
1521
			// Extract class name for polymorphic relations
1522
			if($class === 'DataObject') {
1523
				$class = $this->getField($componentName . 'Class');
1524
				if(empty($class)) return null;
1525
			}
1526
1527
			if($joinID) {
1528
				// Ensure that the selected object originates from the same stage, subsite, etc
1529
				$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...
1530
					->filter('ID', $joinID)
1531
					->setDataQueryParam($this->getInheritableQueryParams())
1532
					->first();
1533
			}
1534
1535
			if(empty($component)) {
1536
				$component = $this->model->$class->newObject();
1537
			}
1538
		} elseif($class = $this->belongsToComponent($componentName)) {
1539
			$joinField = $this->getRemoteJoinField($componentName, 'belongs_to', $polymorphic);
1540
			$joinID = $this->ID;
1541
1542
			if($joinID) {
1543
				// Prepare filter for appropriate join type
1544
				if($polymorphic) {
1545
					$filter = array(
1546
						"{$joinField}ID" => $joinID,
1547
						"{$joinField}Class" => $this->class
1548
					);
1549
				} else {
1550
					$filter = array(
1551
						$joinField => $joinID
1552
					);
1553
				}
1554
1555
				// Ensure that the selected object originates from the same stage, subsite, etc
1556
				$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...
1557
					->filter($filter)
1558
					->setDataQueryParam($this->getInheritableQueryParams())
1559
					->first();
1560
			}
1561
1562
			if(empty($component)) {
1563
				$component = $this->model->$class->newObject();
1564
				if($polymorphic) {
1565
					$component->{$joinField.'ID'} = $this->ID;
1566
					$component->{$joinField.'Class'} = $this->class;
1567
				} else {
1568
					$component->$joinField = $this->ID;
1569
				}
1570
			}
1571
		} else {
1572
			throw new InvalidArgumentException(
1573
				"DataObject->getComponent(): Could not find component '$componentName'."
1574
			);
1575
		}
1576
1577
		$this->components[$componentName] = $component;
1578
		return $component;
1579
	}
1580
1581
	/**
1582
	 * Returns a one-to-many relation as a HasManyList
1583
	 *
1584
	 * @param string $componentName Name of the component
1585
	 * @return HasManyList The components of the one-to-many relationship.
1586
	 */
1587
	public function getComponents($componentName) {
1588
		$result = null;
1589
1590
		$componentClass = $this->hasManyComponent($componentName);
1591
		if(!$componentClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $componentClass of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1592
			throw new InvalidArgumentException(sprintf(
1593
				"DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
1594
				$componentName,
1595
				$this->class
1596
			));
1597
		}
1598
1599
		// If we haven't been written yet, we can't save these relations, so use a list that handles this case
1600
		if(!$this->ID) {
1601
			if(!isset($this->unsavedRelations[$componentName])) {
1602
				$this->unsavedRelations[$componentName] =
1603
					new UnsavedRelationList($this->class, $componentName, $componentClass);
1604
			}
1605
			return $this->unsavedRelations[$componentName];
1606
		}
1607
1608
		// Determine type and nature of foreign relation
1609
		$joinField = $this->getRemoteJoinField($componentName, 'has_many', $polymorphic);
1610
		/** @var HasManyList $result */
1611
		if($polymorphic) {
1612
			$result = PolymorphicHasManyList::create($componentClass, $joinField, $this->class);
1613
		} else {
1614
			$result = HasManyList::create($componentClass, $joinField);
1615
		}
1616
1617
		if($this->model) {
1618
			$result->setDataModel($this->model);
1619
		}
1620
1621
		return $result
1622
			->setDataQueryParam($this->getInheritableQueryParams())
1623
			->forForeignID($this->ID);
1624
	}
1625
1626
	/**
1627
	 * Find the foreign class of a relation on this DataObject, regardless of the relation type.
1628
	 *
1629
	 * @param string $relationName Relation name.
1630
	 * @return string Class name, or null if not found.
1631
	 */
1632
	public function getRelationClass($relationName) {
1633
		// Go through all relationship configuration fields.
1634
		$candidates = array_merge(
1635
			($relations = Config::inst()->get($this->class, 'has_one')) ? $relations : array(),
1636
			($relations = Config::inst()->get($this->class, 'has_many')) ? $relations : array(),
1637
			($relations = Config::inst()->get($this->class, 'many_many')) ? $relations : array(),
1638
			($relations = Config::inst()->get($this->class, 'belongs_many_many')) ? $relations : array(),
1639
			($relations = Config::inst()->get($this->class, 'belongs_to')) ? $relations : array()
1640
		);
1641
1642
		if (isset($candidates[$relationName])) {
1643
			$remoteClass = $candidates[$relationName];
1644
1645
			// If dot notation is present, extract just the first part that contains the class.
1646
			if(($fieldPos = strpos($remoteClass, '.'))!==false) {
1647
				return substr($remoteClass, 0, $fieldPos);
1648
			}
1649
1650
			// Otherwise just return the class
1651
			return $remoteClass;
1652
		}
1653
1654
		return null;
1655
	}
1656
1657
	/**
1658
	 * Given a relation name, determine the relation type
1659
	 *
1660
	 * @param string $component Name of component
1661
	 * @return string has_one, has_many, many_many, belongs_many_many or belongs_to
1662
	 */
1663
	public function getRelationType($component) {
1664
		$types = array('has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to');
1665
		foreach($types as $type) {
1666
			$relations = Config::inst()->get($this->class, $type);
1667
			if($relations && isset($relations[$component])) {
1668
				return $type;
1669
			}
1670
		}
1671
		return null;
1672
	}
1673
1674
	/**
1675
	 * Given a relation declared on a remote class, generate a substitute component for the opposite
1676
	 * side of the relation.
1677
	 *
1678
	 * Notes on behaviour:
1679
	 *  - This can still be used on components that are defined on both sides, but do not need to be.
1680
	 *  - All has_ones on remote class will be treated as local has_many, even if they are belongs_to
1681
	 *  - Cannot be used on polymorphic relationships
1682
	 *  - Cannot be used on unsaved objects.
1683
	 *
1684
	 * @param string $remoteClass
1685
	 * @param string $remoteRelation
1686
	 * @return DataList|DataObject The component, either as a list or single object
1687
	 * @throws BadMethodCallException
1688
	 * @throws InvalidArgumentException
1689
	 */
1690
	public function inferReciprocalComponent($remoteClass, $remoteRelation) {
1691
		/** @var DataObject $remote */
1692
		$remote = $remoteClass::singleton();
1693
		$class = $remote->getRelationClass($remoteRelation);
1694
1695
		// Validate arguments
1696
		if(!$this->isInDB()) {
1697
			throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects");
1698
		}
1699
		if(empty($class)) {
1700
			throw new InvalidArgumentException(sprintf(
1701
				"%s invoked with invalid relation %s.%s",
1702
				__METHOD__,
1703
				$remoteClass,
1704
				$remoteRelation
1705
			));
1706
		}
1707
		if($class === 'DataObject') {
1708
			throw new InvalidArgumentException(sprintf(
1709
				"%s cannot generate opposite component of relation %s.%s as it is polymorphic. " .
1710
				"This method does not support polymorphic relationships",
1711
				__METHOD__,
1712
				$remoteClass,
1713
				$remoteRelation
1714
			));
1715
		}
1716
		if(!is_a($this, $class, true)) {
1717
			throw new InvalidArgumentException(sprintf(
1718
				"Relation %s on %s does not refer to objects of type %s",
1719
				$remoteRelation, $remoteClass, get_class($this)
1720
			));
1721
		}
1722
1723
		// Check the relation type to mock
1724
		$relationType = $remote->getRelationType($remoteRelation);
1725
		switch($relationType) {
1726
			case 'has_one': {
0 ignored issues
show
Coding Style introduced by
CASE statements must 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.

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

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

Loading history...
1727
				// Mock has_many
1728
				$joinField = "{$remoteRelation}ID";
1729
				$componentClass = ClassInfo::table_for_object_field($remoteClass, $joinField);
1730
				$result = HasManyList::create($componentClass, $joinField);
1731
				if ($this->model) {
1732
					$result->setDataModel($this->model);
1733
				}
1734
				return $result
1735
					->setDataQueryParam($this->getInheritableQueryParams())
1736
					->forForeignID($this->ID);
1737
			}
1738
			case 'belongs_to':
1739
			case 'has_many': {
0 ignored issues
show
Coding Style introduced by
CASE statements must 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.

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

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

Loading history...
1740
				// These relations must have a has_one on the other end, so find it
1741
				$joinField = $remote->getRemoteJoinField($remoteRelation, $relationType, $polymorphic);
1742
				if ($polymorphic) {
1743
					throw new InvalidArgumentException(sprintf(
1744
						"%s cannot generate opposite component of relation %s.%s, as the other end appears" .
1745
						"to be a has_one polymorphic. This method does not support polymorphic relationships",
1746
						__METHOD__,
1747
						$remoteClass,
1748
						$remoteRelation
1749
					));
1750
				}
1751
				$joinID = $this->getField($joinField);
1752
				if (empty($joinID)) {
1753
					return null;
1754
				}
1755
				// Get object by joined ID
1756
				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...
1757
					->filter('ID', $joinID)
1758
					->setDataQueryParam($this->getInheritableQueryParams())
1759
					->first();
1760
			}
1761
			case 'many_many':
1762
			case 'belongs_many_many': {
0 ignored issues
show
Coding Style introduced by
CASE statements must 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.

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

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

Loading history...
1763
				// Get components and extra fields from parent
1764
				list($componentClass, $parentClass, $componentField, $parentField, $table)
0 ignored issues
show
Unused Code introduced by
The assignment to $parentClass is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
1765
					= $remote->manyManyComponent($remoteRelation);
1766
				$extraFields = $remote->manyManyExtraFieldsForComponent($remoteRelation) ?: array();
1767
1768
				// Reverse parent and component fields and create an inverse ManyManyList
1769
				/** @var ManyManyList $result */
1770
				$result = ManyManyList::create($componentClass, $table, $componentField, $parentField, $extraFields);
1771
				if($this->model) {
1772
					$result->setDataModel($this->model);
1773
				}
1774
				$this->extend('updateManyManyComponents', $result);
1775
1776
				// If this is called on a singleton, then we return an 'orphaned relation' that can have the
1777
				// foreignID set elsewhere.
1778
				return $result
1779
					->setDataQueryParam($this->getInheritableQueryParams())
1780
					->forForeignID($this->ID);
1781
			}
1782
			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...
1783
				return null;
1784
			}
1785
		}
1786
	}
1787
1788
	/**
1789
	 * Tries to find the database key on another object that is used to store a
1790
	 * relationship to this class. If no join field can be found it defaults to 'ParentID'.
1791
	 *
1792
	 * If the remote field is polymorphic then $polymorphic is set to true, and the return value
1793
	 * is in the form 'Relation' instead of 'RelationID', referencing the composite DBField.
1794
	 *
1795
	 * @param string $component Name of the relation on the current object pointing to the
1796
	 * remote object.
1797
	 * @param string $type the join type - either 'has_many' or 'belongs_to'
1798
	 * @param boolean $polymorphic Flag set to true if the remote join field is polymorphic.
1799
	 * @return string
1800
	 * @throws Exception
1801
	 */
1802
	public function getRemoteJoinField($component, $type = 'has_many', &$polymorphic = false) {
1803
		// Extract relation from current object
1804
		if($type === 'has_many') {
1805
			$remoteClass = $this->hasManyComponent($component, false);
1806
		} else {
1807
			$remoteClass = $this->belongsToComponent($component, false);
1808
		}
1809
1810
		if(empty($remoteClass)) {
1811
			throw new Exception("Unknown $type component '$component' on class '$this->class'");
1812
		}
1813
		if(!ClassInfo::exists(strtok($remoteClass, '.'))) {
1814
			throw new Exception(
1815
				"Class '$remoteClass' not found, but used in $type component '$component' on class '$this->class'"
1816
			);
1817
		}
1818
1819
		// If presented with an explicit field name (using dot notation) then extract field name
1820
		$remoteField = null;
1821
		if(strpos($remoteClass, '.') !== false) {
1822
			list($remoteClass, $remoteField) = explode('.', $remoteClass);
1823
		}
1824
1825
		// Reference remote has_one to check against
1826
		$remoteRelations = Config::inst()->get($remoteClass, 'has_one');
1827
1828
		// Without an explicit field name, attempt to match the first remote field
1829
		// with the same type as the current class
1830
		if(empty($remoteField)) {
1831
			// look for remote has_one joins on this class or any parent classes
1832
			$remoteRelationsMap = array_flip($remoteRelations);
1833
			foreach(array_reverse(ClassInfo::ancestry($this)) as $class) {
1834
				if(array_key_exists($class, $remoteRelationsMap)) {
1835
					$remoteField = $remoteRelationsMap[$class];
1836
					break;
1837
				}
1838
			}
1839
		}
1840
1841
		// In case of an indeterminate remote field show an error
1842
		if(empty($remoteField)) {
1843
			$polymorphic = false;
1844
			$message = "No has_one found on class '$remoteClass'";
1845
			if($type == 'has_many') {
1846
				// include a hint for has_many that is missing a has_one
1847
				$message .= ", the has_many relation from '$this->class' to '$remoteClass'";
1848
				$message .= " requires a has_one on '$remoteClass'";
1849
			}
1850
			throw new Exception($message);
1851
		}
1852
1853
		// If given an explicit field name ensure the related class specifies this
1854
		if(empty($remoteRelations[$remoteField])) {
1855
			throw new Exception("Missing expected has_one named '$remoteField'
1856
				on class '$remoteClass' referenced by $type named '$component'
1857
				on class {$this->class}"
1858
			);
1859
		}
1860
1861
		// Inspect resulting found relation
1862
		if($remoteRelations[$remoteField] === 'DataObject') {
1863
			$polymorphic = true;
1864
			return $remoteField; // Composite polymorphic field does not include 'ID' suffix
1865
		} else {
1866
			$polymorphic = false;
1867
			return $remoteField . 'ID';
1868
		}
1869
	}
1870
1871
	/**
1872
	 * Returns a many-to-many component, as a ManyManyList.
1873
	 * @param string $componentName Name of the many-many component
1874
	 * @return ManyManyList The set of components
1875
	 */
1876
	public function getManyManyComponents($componentName) {
1877
		$manyManyComponent = $this->manyManyComponent($componentName);
1878
		if(!$manyManyComponent) {
1879
			throw new InvalidArgumentException(sprintf(
1880
				"DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'",
1881
				$componentName,
1882
				$this->class
1883
			));
1884
		}
1885
1886
		list($parentClass, $componentClass, $parentField, $componentField, $table) = $manyManyComponent;
1887
1888
		// If we haven't been written yet, we can't save these relations, so use a list that handles this case
1889
		if(!$this->ID) {
1890
			if(!isset($this->unsavedRelations[$componentName])) {
1891
				$this->unsavedRelations[$componentName] =
1892
					new UnsavedRelationList($parentClass, $componentName, $componentClass);
1893
			}
1894
			return $this->unsavedRelations[$componentName];
1895
		}
1896
1897
		$extraFields = $this->manyManyExtraFieldsForComponent($componentName) ?: array();
1898
		/** @var ManyManyList $result */
1899
		$result = ManyManyList::create($componentClass, $table, $componentField, $parentField, $extraFields);
1900
		if($this->model) {
1901
			$result->setDataModel($this->model);
1902
		}
1903
1904
		$this->extend('updateManyManyComponents', $result);
1905
1906
		// If this is called on a singleton, then we return an 'orphaned relation' that can have the
1907
		// foreignID set elsewhere.
1908
		return $result
1909
			->setDataQueryParam($this->getInheritableQueryParams())
1910
			->forForeignID($this->ID);
1911
	}
1912
1913
	/**
1914
	 * Return the class of a one-to-one component.  If $component is null, return all of the one-to-one components and
1915
	 * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.
1916
	 *
1917
	 * @return string|array The class of the one-to-one component, or an array of all one-to-one components and
1918
	 * 							their classes.
1919
	 */
1920
	public function hasOne() {
1921
		return (array)Config::inst()->get($this->class, 'has_one', Config::INHERITED);
1922
	}
1923
1924
	/**
1925
	 * Return data for a specific has_one component.
1926
	 * @param string $component
1927
	 * @return string|null
1928
	 */
1929
	public function hasOneComponent($component) {
1930
		$classes = ClassInfo::ancestry($this, true);
1931
1932
		foreach(array_reverse($classes) as $class) {
1933
			$hasOnes = Config::inst()->get($class, 'has_one', Config::UNINHERITED);
1934
			if(isset($hasOnes[$component])) {
1935
				return $hasOnes[$component];
1936
			}
1937
		}
1938
	}
1939
1940
	/**
1941
	 * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
1942
	 * their class name will be returned.
1943
	 *
1944
	 * @param string $component - Name of component
1945
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1946
	 *        the field data stripped off. It defaults to TRUE.
1947
	 * @return string|array
1948
	 */
1949
	public function belongsTo($component = null, $classOnly = true) {
1950
		if($component) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $component of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1951
			Deprecation::notice(
1952
				'4.0',
1953
				'Please use DataObject::belongsToComponent() instead of passing a component name to belongsTo()',
1954
				Deprecation::SCOPE_GLOBAL
1955
			);
1956
			return $this->belongsToComponent($component, $classOnly);
1957
		}
1958
1959
		$belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED);
1960
		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...
1961
			return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
1962
		} else {
1963
			return $belongsTo ? $belongsTo : array();
1964
		}
1965
	}
1966
1967
	/**
1968
	 * Return data for a specific belongs_to component.
1969
	 * @param string $component
1970
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1971
	 *        the field data stripped off. It defaults to TRUE.
1972
	 * @return string|null
1973
	 */
1974
	public function belongsToComponent($component, $classOnly = true) {
1975
		$belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED);
1976
1977
		if($belongsTo && array_key_exists($component, $belongsTo)) {
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...
1978
			$belongsTo = $belongsTo[$component];
1979
		} else {
1980
			return null;
1981
		}
1982
1983
		return ($classOnly) ? preg_replace('/(.+)?\..+/', '$1', $belongsTo) : $belongsTo;
1984
	}
1985
1986
	/**
1987
	 * Return all of the database fields in this object
1988
	 *
1989
	 * @param string $fieldName Limit the output to a specific field name
1990
	 * @param string $includeTable If returning a single column, prefix the column with the table name
1991
	 * in Table.Column(spec) format
1992
	 * @return array|string|null The database fields, or if searching a single field, just this one field if found
1993
	 * Field will be a string in ClassName(args) format, or Table.ClassName(args) format if $includeTable is true
1994
	 */
1995
	public function db($fieldName = null, $includeTable = false) {
1996
		$classes = ClassInfo::ancestry($this, true);
1997
1998
		// If we're looking for a specific field, we want to hit subclasses first as they may override field types
1999
		if($fieldName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2000
			$classes = array_reverse($classes);
2001
		}
2002
2003
		$db = array();
2004
		foreach($classes as $class) {
2005
			// Merge fields with new fields and composite fields
2006
			$fields = self::database_fields($class);
2007
			$compositeFields = self::composite_fields($class, false);
2008
			$db = array_merge($db, $fields, $compositeFields);
2009
2010
			// Check for search field
2011
			if($fieldName && isset($db[$fieldName])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2012
				// Return found field
2013
				if(!$includeTable) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $includeTable of type false|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2014
					return $db[$fieldName];
2015
				}
2016
2017
				// Set table for the given field
2018
				if(in_array($fieldName, $this->config()->fixed_fields)) {
2019
					$table = $this->baseTable();
2020
				} else {
2021
					$table = $class;
2022
				}
2023
				return $table . "." . $db[$fieldName];
2024
			}
2025
		}
2026
2027
		// At end of search complete
2028
		if($fieldName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2029
			return null;
2030
		} else {
2031
			return $db;
2032
		}
2033
	}
2034
2035
	/**
2036
	 * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
2037
	 * relationships and their classes will be returned.
2038
	 *
2039
	 * @param string $component Deprecated - Name of component
2040
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2041
	 *        the field data stripped off. It defaults to TRUE.
2042
	 * @return string|array|false
2043
	 */
2044
	public function hasMany($component = null, $classOnly = true) {
2045
		if($component) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $component of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2046
			Deprecation::notice(
2047
				'4.0',
2048
				'Please use DataObject::hasManyComponent() instead of passing a component name to hasMany()',
2049
				Deprecation::SCOPE_GLOBAL
2050
			);
2051
			return $this->hasManyComponent($component, $classOnly);
2052
		}
2053
2054
		$hasMany = (array)Config::inst()->get($this->class, 'has_many', Config::INHERITED);
2055
		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...
2056
			return preg_replace('/(.+)?\..+/', '$1', $hasMany);
2057
		} else {
2058
			return $hasMany ? $hasMany : array();
2059
		}
2060
	}
2061
2062
	/**
2063
	 * Return data for a specific has_many component.
2064
	 * @param string $component
2065
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2066
	 *        the field data stripped off. It defaults to TRUE.
2067
	 * @return string|null
2068
	 */
2069
	public function hasManyComponent($component, $classOnly = true) {
2070
		$hasMany = (array)Config::inst()->get($this->class, 'has_many', Config::INHERITED);
2071
2072
		if($hasMany && array_key_exists($component, $hasMany)) {
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...
2073
			$hasMany = $hasMany[$component];
2074
		} else {
2075
			return null;
2076
		}
2077
2078
		return ($classOnly) ? preg_replace('/(.+)?\..+/', '$1', $hasMany) : $hasMany;
2079
	}
2080
2081
	/**
2082
	 * Return the many-to-many extra fields specification.
2083
	 *
2084
	 * If you don't specify a component name, it returns all
2085
	 * extra fields for all components available.
2086
	 *
2087
	 * @return array|null
2088
	 */
2089
	public function manyManyExtraFields() {
2090
		return Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED);
2091
	}
2092
2093
	/**
2094
	 * Return the many-to-many extra fields specification for a specific component.
2095
	 * @param string $component
2096
	 * @return array|null
2097
	 */
2098
	public function manyManyExtraFieldsForComponent($component) {
2099
		// Get all many_many_extraFields defined in this class or parent classes
2100
		$extraFields = (array)Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED);
2101
		// Extra fields are immediately available
2102
		if(isset($extraFields[$component])) {
2103
			return $extraFields[$component];
2104
		}
2105
2106
		// Check this class' belongs_many_manys to see if any of their reverse associations contain extra fields
2107
		$manyMany = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED);
2108
		$candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null;
2109
		if($candidate) {
2110
			$relationName = null;
2111
			// Extract class and relation name from dot-notation
2112
			if(strpos($candidate, '.') !== false) {
2113
				list($candidate, $relationName) = explode('.', $candidate, 2);
2114
			}
2115
2116
			// If we've not already found the relation name from dot notation, we need to find a relation that points
2117
			// back to this class. As there's no dot-notation, there can only be one relation pointing to this class,
2118
			// so it's safe to assume that it's the correct one
2119
			if(!$relationName) {
2120
				$candidateManyManys = (array)Config::inst()->get($candidate, 'many_many', Config::UNINHERITED);
2121
2122
				foreach($candidateManyManys as $relation => $relatedClass) {
2123
					if (is_a($this, $relatedClass)) {
2124
						$relationName = $relation;
2125
					}
2126
				}
2127
			}
2128
2129
			// If we've found a matching relation on the target class, see if we can find extra fields for it
2130
			$extraFields = (array)Config::inst()->get($candidate, 'many_many_extraFields', Config::UNINHERITED);
2131
			if(isset($extraFields[$relationName])) {
2132
				return $extraFields[$relationName];
2133
			}
2134
		}
2135
2136
		return isset($items) ? $items : null;
0 ignored issues
show
Bug introduced by
The variable $items seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
2137
	}
2138
2139
	/**
2140
	 * Return information about a many-to-many component.
2141
	 * The return value is an array of (parentclass, childclass).  If $component is null, then all many-many
2142
	 * components are returned.
2143
	 *
2144
	 * @see DataObject::manyManyComponent()
2145
	 * @return array|null An array of (parentclass, childclass), or an array of all many-many components
2146
	 */
2147
	public function manyMany() {
2148
		$manyManys = (array)Config::inst()->get($this->class, 'many_many', Config::INHERITED);
2149
		$belongsManyManys = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED);
2150
		$items = array_merge($manyManys, $belongsManyManys);
2151
		return $items;
2152
	}
2153
2154
	/**
2155
	 * Return information about a specific many_many component. Returns a numeric array of:
2156
	 * array(
2157
	 * 	<classname>,		The class that relation is defined in e.g. "Product"
2158
	 * 	<candidateName>,	The target class of the relation e.g. "Category"
2159
	 * 	<parentField>,		The field name pointing to <classname>'s table e.g. "ProductID"
2160
	 * 	<childField>,		The field name pointing to <candidatename>'s table e.g. "CategoryID"
2161
	 * 	<joinTable>			The join table between the two classes e.g. "Product_Categories"
2162
	 * )
2163
	 * @param string $component The component name
2164
	 * @return array|null
2165
	 */
2166
	public function manyManyComponent($component) {
2167
		$classes = $this->getClassAncestry();
2168
		foreach($classes as $class) {
2169
			$manyMany = Config::inst()->get($class, 'many_many', Config::UNINHERITED);
2170
			// Check if the component is defined in many_many on this class
2171
			$candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null;
2172
			if($candidate) {
2173
				$parentField = $class . "ID";
2174
				$childField = ($class == $candidate) ? "ChildID" : $candidate . "ID";
2175
				return array($class, $candidate, $parentField, $childField, "{$class}_$component");
2176
			}
2177
2178
			// Check if the component is defined in belongs_many_many on this class
2179
			$belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED);
2180
			$candidate = (isset($belongsManyMany[$component])) ? $belongsManyMany[$component] : null;
2181
			if($candidate) {
2182
				// Extract class and relation name from dot-notation
2183
				if(strpos($candidate, '.') !== false) {
2184
					list($candidate, $relationName) = explode('.', $candidate, 2);
2185
				}
2186
2187
				$childField = $candidate . "ID";
2188
2189
				// We need to find the inverse component name
2190
				$otherManyMany = Config::inst()->get($candidate, 'many_many', Config::UNINHERITED);
2191
				if(!$otherManyMany) {
2192
					throw new LogicException("Inverse component of $candidate not found ({$this->class})");
2193
				}
2194
2195
				// If we've got a relation name (extracted from dot-notation), we can already work out
2196
				// the join table and candidate class name...
2197
				if(isset($relationName) && isset($otherManyMany[$relationName])) {
2198
					$candidateClass = $otherManyMany[$relationName];
2199
					$joinTable = "{$candidate}_{$relationName}";
2200
				} else {
2201
					// ... otherwise, we need to loop over the many_manys and find a relation that
2202
					// matches up to this class
2203
					foreach($otherManyMany as $inverseComponentName => $candidateClass) {
0 ignored issues
show
Bug introduced by
The expression $otherManyMany of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2204
						if($candidateClass == $class || is_subclass_of($class, $candidateClass)) {
2205
							$joinTable = "{$candidate}_{$inverseComponentName}";
2206
							break;
2207
						}
2208
					}
2209
				}
2210
2211
				// If we could work out the join table, we've got all the info we need
2212
				if(isset($joinTable)) {
2213
					$parentField = ($class == $candidate) ? "ChildID" : $candidateClass . "ID";
0 ignored issues
show
Bug introduced by
The variable $candidateClass does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
2214
					return array($class, $candidate, $parentField, $childField, $joinTable);
2215
				}
2216
2217
				throw new LogicException("Orphaned \$belongs_many_many value for $this->class.$component");
2218
			}
2219
		}
2220
	}
2221
2222
	/**
2223
	 * This returns an array (if it exists) describing the database extensions that are required, or false if none
2224
	 *
2225
	 * This is experimental, and is currently only a Postgres-specific enhancement.
2226
	 *
2227
	 * @return array or false
2228
	 */
2229
	public function database_extensions($class){
2230
		$extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
2231
2232
		if($extensions)
2233
			return $extensions;
2234
		else
2235
			return false;
2236
	}
2237
2238
	/**
2239
	 * Generates a SearchContext to be used for building and processing
2240
	 * a generic search form for properties on this object.
2241
	 *
2242
	 * @return SearchContext
2243
	 */
2244
	public function getDefaultSearchContext() {
2245
		return new SearchContext(
2246
			$this->class,
2247
			$this->scaffoldSearchFields(),
2248
			$this->defaultSearchFilters()
2249
		);
2250
	}
2251
2252
	/**
2253
	 * Determine which properties on the DataObject are
2254
	 * searchable, and map them to their default {@link FormField}
2255
	 * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
2256
	 *
2257
	 * Some additional logic is included for switching field labels, based on
2258
	 * how generic or specific the field type is.
2259
	 *
2260
	 * Used by {@link SearchContext}.
2261
	 *
2262
	 * @param array $_params
2263
	 *   'fieldClasses': Associative array of field names as keys and FormField classes as values
2264
	 *   'restrictFields': Numeric array of a field name whitelist
2265
	 * @return FieldList
2266
	 */
2267
	public function scaffoldSearchFields($_params = null) {
2268
		$params = array_merge(
2269
			array(
2270
				'fieldClasses' => false,
2271
				'restrictFields' => false
2272
			),
2273
			(array)$_params
2274
		);
2275
		$fields = new FieldList();
2276
		foreach($this->searchableFields() as $fieldName => $spec) {
2277
			if($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) continue;
2278
2279
			// If a custom fieldclass is provided as a string, use it
2280
			if($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
2281
				$fieldClass = $params['fieldClasses'][$fieldName];
2282
				$field = new $fieldClass($fieldName);
2283
			// If we explicitly set a field, then construct that
2284
			} else if(isset($spec['field'])) {
2285
				// If it's a string, use it as a class name and construct
2286
				if(is_string($spec['field'])) {
2287
					$fieldClass = $spec['field'];
2288
					$field = new $fieldClass($fieldName);
2289
2290
				// If it's a FormField object, then just use that object directly.
2291
				} else if($spec['field'] instanceof FormField) {
2292
					$field = $spec['field'];
2293
2294
				// Otherwise we have a bug
2295
				} else {
2296
					user_error("Bad value for searchable_fields, 'field' value: "
2297
						. var_export($spec['field'], true), E_USER_WARNING);
2298
				}
2299
2300
			// Otherwise, use the database field's scaffolder
2301
			} else {
2302
				$field = $this->relObject($fieldName)->scaffoldSearchField();
2303
			}
2304
2305
			// Allow fields to opt out of search
2306
			if(!$field) {
0 ignored issues
show
Bug introduced by
The variable $field does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
2307
				continue;
2308
			}
2309
2310
			if (strstr($fieldName, '.')) {
2311
				$field->setName(str_replace('.', '__', $fieldName));
2312
			}
2313
			$field->setTitle($spec['title']);
2314
2315
			$fields->push($field);
2316
		}
2317
		return $fields;
2318
	}
2319
2320
	/**
2321
	 * Scaffold a simple edit form for all properties on this dataobject,
2322
	 * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
2323
	 * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
2324
	 *
2325
	 * @uses FormScaffolder
2326
	 *
2327
	 * @param array $_params Associative array passing through properties to {@link FormScaffolder}.
2328
	 * @return FieldList
2329
	 */
2330
	public function scaffoldFormFields($_params = null) {
2331
		$params = array_merge(
2332
			array(
2333
				'tabbed' => false,
2334
				'includeRelations' => false,
2335
				'restrictFields' => false,
2336
				'fieldClasses' => false,
2337
				'ajaxSafe' => false
2338
			),
2339
			(array)$_params
2340
		);
2341
2342
		$fs = new FormScaffolder($this);
2343
		$fs->tabbed = $params['tabbed'];
2344
		$fs->includeRelations = $params['includeRelations'];
2345
		$fs->restrictFields = $params['restrictFields'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $params['restrictFields'] of type false is incompatible with the declared type array of property $restrictFields.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
2346
		$fs->fieldClasses = $params['fieldClasses'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $params['fieldClasses'] of type false is incompatible with the declared type array of property $fieldClasses.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
2347
		$fs->ajaxSafe = $params['ajaxSafe'];
2348
2349
		return $fs->getFieldList();
2350
	}
2351
2352
	/**
2353
	 * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
2354
	 * being called on extensions
2355
	 *
2356
	 * @param callable $callback The callback to execute
2357
	 */
2358
	protected function beforeUpdateCMSFields($callback) {
2359
		$this->beforeExtending('updateCMSFields', $callback);
2360
	}
2361
2362
	/**
2363
	 * Centerpiece of every data administration interface in Silverstripe,
2364
	 * which returns a {@link FieldList} suitable for a {@link Form} object.
2365
	 * If not overloaded, we're using {@link scaffoldFormFields()} to automatically
2366
	 * generate this set. To customize, overload this method in a subclass
2367
	 * or extended onto it by using {@link DataExtension->updateCMSFields()}.
2368
	 *
2369
	 * <code>
2370
	 * class MyCustomClass extends DataObject {
2371
	 *  static $db = array('CustomProperty'=>'Boolean');
2372
	 *
2373
	 *  function getCMSFields() {
2374
	 *    $fields = parent::getCMSFields();
2375
	 *    $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
2376
	 *    return $fields;
2377
	 *  }
2378
	 * }
2379
	 * </code>
2380
	 *
2381
	 * @see Good example of complex FormField building: SiteTree::getCMSFields()
2382
	 *
2383
	 * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.
2384
	 */
2385
	public function getCMSFields() {
2386
		$tabbedFields = $this->scaffoldFormFields(array(
2387
			// Don't allow has_many/many_many relationship editing before the record is first saved
2388
			'includeRelations' => ($this->ID > 0),
2389
			'tabbed' => true,
2390
			'ajaxSafe' => true
2391
		));
2392
2393
		$this->extend('updateCMSFields', $tabbedFields);
2394
2395
		return $tabbedFields;
2396
	}
2397
2398
	/**
2399
	 * need to be overload by solid dataobject, so that the customised actions of that dataobject,
2400
	 * including that dataobject's extensions customised actions could be added to the EditForm.
2401
	 *
2402
	 * @return an Empty FieldList(); need to be overload by solid subclass
2403
	 */
2404
	public function getCMSActions() {
2405
		$actions = new FieldList();
2406
		$this->extend('updateCMSActions', $actions);
2407
		return $actions;
2408
	}
2409
2410
2411
	/**
2412
	 * Used for simple frontend forms without relation editing
2413
	 * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()}
2414
	 * by default. To customize, either overload this method in your
2415
	 * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.
2416
	 *
2417
	 * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API
2418
	 *
2419
	 * @param array $params See {@link scaffoldFormFields()}
2420
	 * @return FieldList Always returns a simple field collection without TabSet.
2421
	 */
2422
	public function getFrontEndFields($params = null) {
2423
		$untabbedFields = $this->scaffoldFormFields($params);
2424
		$this->extend('updateFrontEndFields', $untabbedFields);
2425
2426
		return $untabbedFields;
2427
	}
2428
2429
	/**
2430
	 * Gets the value of a field.
2431
	 * Called by {@link __get()} and any getFieldName() methods you might create.
2432
	 *
2433
	 * @param string $field The name of the field
2434
	 *
2435
	 * @return mixed The field value
2436
	 */
2437
	public function getField($field) {
2438
		// If we already have an object in $this->record, then we should just return that
2439
		if(isset($this->record[$field]) && is_object($this->record[$field])) {
2440
			return $this->record[$field];
2441
		}
2442
2443
		// Do we have a field that needs to be lazy loaded?
2444
		if(isset($this->record[$field.'_Lazy'])) {
2445
			$tableClass = $this->record[$field.'_Lazy'];
2446
			$this->loadLazyFields($tableClass);
2447
		}
2448
2449
		// In case of complex fields, return the DBField object
2450
		if(self::is_composite_field($this->class, $field)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::is_composite_field($this->class, $field) of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2451
			$this->record[$field] = $this->dbObject($field);
2452
		}
2453
2454
		return isset($this->record[$field]) ? $this->record[$field] : null;
2455
	}
2456
2457
	/**
2458
	 * Loads all the stub fields that an initial lazy load didn't load fully.
2459
	 *
2460
	 * @param string $tableClass Base table to load the values from. Others are joined as required.
2461
	 * Not specifying a tableClass will load all lazy fields from all tables.
2462
	 */
2463
	protected function loadLazyFields($tableClass = null) {
2464
		if (!$tableClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tableClass of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2465
			$loaded = array();
2466
2467
			foreach ($this->record as $key => $value) {
2468
				if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
2469
					$this->loadLazyFields($value);
2470
					$loaded[$value] = $value;
2471
				}
2472
			}
2473
2474
			return;
2475
		}
2476
2477
		$dataQuery = new DataQuery($tableClass);
2478
2479
		// Reset query parameter context to that of this DataObject
2480
		if($params = $this->getSourceQueryParams()) {
2481
			foreach($params as $key => $value) {
2482
				$dataQuery->setQueryParam($key, $value);
2483
			}
2484
		}
2485
2486
		// TableField sets the record ID to "new" on new row data, so don't try doing anything in that case
2487
		if(!is_numeric($this->record['ID'])) {
2488
			return;
2489
		}
2490
2491
		// Limit query to the current record, unless it has the Versioned extension,
2492
		// in which case it requires special handling through augmentLoadLazyFields()
2493
		$baseTable = ClassInfo::baseDataClass($this);
2494
		$dataQuery->where([
2495
			"\"{$baseTable}\".\"ID\"" => $this->record['ID']
2496
		])->limit(1);
2497
2498
		$columns = array();
2499
2500
		// Add SQL for fields, both simple & multi-value
2501
		// TODO: This is copy & pasted from buildSQL(), it could be moved into a method
2502
		$databaseFields = self::database_fields($tableClass);
2503
		if($databaseFields) foreach($databaseFields as $k => $v) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $databaseFields 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...
2504
			if(!isset($this->record[$k]) || $this->record[$k] === null) {
2505
				$columns[] = $k;
2506
			}
2507
		}
2508
2509
		if ($columns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $columns 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...
2510
			$query = $dataQuery->query();
2511
			$this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
2512
			$this->extend('augmentSQL', $query, $dataQuery);
2513
2514
			$dataQuery->setQueriedColumns($columns);
2515
			$newData = $dataQuery->execute()->record();
2516
2517
			// Load the data into record
2518
			if($newData) {
2519
				foreach($newData as $k => $v) {
2520
					if (in_array($k, $columns)) {
2521
						$this->record[$k] = $v;
2522
						$this->original[$k] = $v;
2523
						unset($this->record[$k . '_Lazy']);
2524
					}
2525
				}
2526
2527
			// No data means that the query returned nothing; assign 'null' to all the requested fields
2528
			} else {
2529
				foreach($columns as $k) {
2530
					$this->record[$k] = null;
2531
					$this->original[$k] = null;
2532
					unset($this->record[$k . '_Lazy']);
2533
				}
2534
			}
2535
		}
2536
	}
2537
2538
	/**
2539
	 * Return the fields that have changed.
2540
	 *
2541
	 * The change level affects what the functions defines as "changed":
2542
	 * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
2543
	 * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
2544
	 *   for example a change from 0 to null would not be included.
2545
	 *
2546
	 * Example return:
2547
	 * <code>
2548
	 * array(
2549
	 *   'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
2550
	 * )
2551
	 * </code>
2552
	 *
2553
	 * @param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true
2554
	 * to return all database fields, or an array for an explicit filter. false returns all fields.
2555
	 * @param int $changeLevel The strictness of what is defined as change. Defaults to strict
2556
	 * @return array
2557
	 */
2558
	public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT) {
2559
		$changedFields = array();
2560
2561
		// Update the changed array with references to changed obj-fields
2562
		foreach($this->record as $k => $v) {
2563
			// Prevents DBComposite infinite looping on isChanged
2564
			if(is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) {
2565
				continue;
2566
			}
2567
			if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
2568
				$this->changed[$k] = self::CHANGE_VALUE;
2569
			}
2570
		}
2571
2572
		if(is_array($databaseFieldsOnly)) {
2573
			$fields = array_intersect_key((array)$this->changed, array_flip($databaseFieldsOnly));
2574
		} elseif($databaseFieldsOnly) {
2575
			$fields = array_intersect_key((array)$this->changed, $this->db());
2576
		} else {
2577
			$fields = $this->changed;
2578
		}
2579
2580
		// Filter the list to those of a certain change level
2581
		if($changeLevel > self::CHANGE_STRICT) {
2582
			if($fields) foreach($fields as $name => $level) {
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...
2583
				if($level < $changeLevel) {
2584
					unset($fields[$name]);
2585
				}
2586
			}
2587
		}
2588
2589
		if($fields) foreach($fields as $name => $level) {
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...
2590
			$changedFields[$name] = array(
2591
				'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
2592
				'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
2593
				'level' => $level
2594
			);
2595
		}
2596
2597
		return $changedFields;
2598
	}
2599
2600
	/**
2601
	 * Uses {@link getChangedFields()} to determine if fields have been changed
2602
	 * since loading them from the database.
2603
	 *
2604
	 * @param string $fieldName Name of the database field to check, will check for any if not given
2605
	 * @param int $changeLevel See {@link getChangedFields()}
2606
	 * @return boolean
2607
	 */
2608
	public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT) {
2609
		$fields = $fieldName ? array($fieldName) : false;
2610
		$changed = $this->getChangedFields($fields, $changeLevel);
2611
		if(!isset($fieldName)) {
2612
			return !empty($changed);
2613
		}
2614
		else {
2615
			return array_key_exists($fieldName, $changed);
2616
		}
2617
	}
2618
2619
	/**
2620
	 * Set the value of the field
2621
	 * Called by {@link __set()} and any setFieldName() methods you might create.
2622
	 *
2623
	 * @param string $fieldName Name of the field
2624
	 * @param mixed $val New field value
2625
	 * @return DataObject $this
2626
	 */
2627
	public function setField($fieldName, $val) {
2628
		//if it's a has_one component, destroy the cache
2629
		if (substr($fieldName, -2) == 'ID') {
2630
			unset($this->components[substr($fieldName, 0, -2)]);
2631
		}
2632
2633
		// If we've just lazy-loaded the column, then we need to populate the $original array
2634
		if(isset($this->record[$fieldName.'_Lazy'])) {
2635
			$tableClass = $this->record[$fieldName.'_Lazy'];
2636
			$this->loadLazyFields($tableClass);
2637
		}
2638
2639
		// Situation 1: Passing an DBField
2640
		if($val instanceof DBField) {
2641
			$val->setName($fieldName);
2642
			$val->saveInto($this);
2643
2644
			// Situation 1a: Composite fields should remain bound in case they are
2645
			// later referenced to update the parent dataobject
2646
			if($val instanceof DBComposite) {
2647
				$val->bindTo($this);
2648
				$this->record[$fieldName] = $val;
2649
			}
2650
		// Situation 2: Passing a literal or non-DBField object
2651
		} else {
2652
			// If this is a proper database field, we shouldn't be getting non-DBField objects
2653
			if(is_object($val) && $this->db($fieldName)) {
2654
				user_error('DataObject::setField: passed an object that is not a DBField', E_USER_WARNING);
2655
			}
2656
2657
			// if a field is not existing or has strictly changed
2658
			if(!isset($this->record[$fieldName]) || $this->record[$fieldName] !== $val) {
2659
				// TODO Add check for php-level defaults which are not set in the db
2660
				// TODO Add check for hidden input-fields (readonly) which are not set in the db
2661
				// At the very least, the type has changed
2662
				$this->changed[$fieldName] = self::CHANGE_STRICT;
2663
2664
				if((!isset($this->record[$fieldName]) && $val) || (isset($this->record[$fieldName])
2665
						&& $this->record[$fieldName] != $val)) {
2666
2667
					// Value has changed as well, not just the type
2668
					$this->changed[$fieldName] = self::CHANGE_VALUE;
2669
				}
2670
2671
				// Value is always saved back when strict check succeeds.
2672
				$this->record[$fieldName] = $val;
2673
			}
2674
		}
2675
		return $this;
2676
	}
2677
2678
	/**
2679
	 * Set the value of the field, using a casting object.
2680
	 * This is useful when you aren't sure that a date is in SQL format, for example.
2681
	 * setCastedField() can also be used, by forms, to set related data.  For example, uploaded images
2682
	 * can be saved into the Image table.
2683
	 *
2684
	 * @param string $fieldName Name of the field
2685
	 * @param mixed $value New field value
2686
	 * @return $this
2687
	 */
2688
	public function setCastedField($fieldName, $value) {
2689
		if(!$fieldName) {
2690
			user_error("DataObject::setCastedField: Called without a fieldName", E_USER_ERROR);
2691
		}
2692
		$fieldObj = $this->dbObject($fieldName);
2693
		if($fieldObj) {
2694
			$fieldObj->setValue($value);
2695
			$fieldObj->saveInto($this);
2696
		} else {
2697
			$this->$fieldName = $value;
2698
		}
2699
		return $this;
2700
	}
2701
2702
	public function castingHelper($field) {
2703
		// Allows db to act as implicit casting override
2704
		if($fieldSpec = $this->db($field)) {
2705
			return $fieldSpec;
2706
		}
2707
		return parent::castingHelper($field);
2708
	}
2709
2710
	/**
2711
	 * Returns true if the given field exists in a database column on any of
2712
	 * the objects tables and optionally look up a dynamic getter with
2713
	 * get<fieldName>().
2714
	 *
2715
	 * @param string $field Name of the field
2716
	 * @return boolean True if the given field exists
2717
	 */
2718
	public function hasField($field) {
2719
		return (
2720
			array_key_exists($field, $this->record)
2721
			|| $this->db($field)
2722
			|| (substr($field,-2) == 'ID') && $this->hasOneComponent(substr($field,0, -2))
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->hasOneComponent(substr($field, 0, -2)) of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2723
			|| $this->hasMethod("get{$field}")
2724
		);
2725
	}
2726
2727
	/**
2728
	 * Returns true if the given field exists as a database column
2729
	 *
2730
	 * @param string $field Name of the field
2731
	 *
2732
	 * @return boolean
2733
	 */
2734
	public function hasDatabaseField($field) {
2735
		return $this->db($field)
2736
			&& ! self::is_composite_field(get_class($this), $field);
0 ignored issues
show
Bug Best Practice introduced by
The expression self::is_composite_field(get_class($this), $field) of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2737
	}
2738
2739
	/**
2740
	 * Returns the field type of the given field, if it belongs to this class, and not a parent.
2741
	 * Note that the field type will not include constructor arguments in round brackets, only the classname.
2742
	 *
2743
	 * @param string $field Name of the field
2744
	 * @return string The field type of the given field
2745
	 */
2746
	public function hasOwnTableDatabaseField($field) {
2747
		return self::has_own_table_database_field($this->class, $field);
2748
	}
2749
2750
	/**
2751
	 * Returns the field type of the given field, if it belongs to this class, and not a parent.
2752
	 * Note that the field type will not include constructor arguments in round brackets, only the classname.
2753
	 *
2754
	 * @param string $class Class name to check
2755
	 * @param string $field Name of the field
2756
	 * @return string The field type of the given field
2757
	 */
2758
	public static function has_own_table_database_field($class, $field) {
2759
		$fieldMap = self::database_fields($class);
2760
2761
		// Remove string-based "constructor-arguments" from the DBField definition
2762
		if(isset($fieldMap[$field])) {
2763
			$spec = $fieldMap[$field];
2764
			if(is_string($spec)) return strtok($spec,'(');
2765
			else return $spec['type'];
2766
		}
2767
	}
2768
2769
	/**
2770
	 * Returns true if given class has its own table. Uses the rules for whether the table should exist rather than
2771
	 * actually looking in the database.
2772
	 *
2773
	 * @param string $dataClass
2774
	 * @return bool
2775
	 */
2776
	public static function has_own_table($dataClass) {
2777
		if(!is_subclass_of($dataClass,'DataObject')) return false;
2778
2779
		$dataClass = ClassInfo::class_name($dataClass);
2780
		if(!isset(self::$_cache_has_own_table[$dataClass])) {
2781
			if(get_parent_class($dataClass) == 'DataObject') {
2782
				self::$_cache_has_own_table[$dataClass] = true;
2783
			} else {
2784
				self::$_cache_has_own_table[$dataClass]
2785
					= Config::inst()->get($dataClass, 'db', Config::UNINHERITED)
2786
					|| Config::inst()->get($dataClass, 'has_one', Config::UNINHERITED);
2787
			}
2788
		}
2789
		return self::$_cache_has_own_table[$dataClass];
2790
	}
2791
2792
	/**
2793
	 * Returns true if the member is allowed to do the given action.
2794
	 * See {@link extendedCan()} for a more versatile tri-state permission control.
2795
	 *
2796
	 * @param string $perm The permission to be checked, such as 'View'.
2797
	 * @param Member $member The member whose permissions need checking.  Defaults to the currently logged
2798
	 * in user.
2799
	 *
2800
	 * @return boolean True if the the member is allowed to do the given action
2801
	 */
2802
	public function can($perm, $member = null) {
2803
		if(!isset($member)) {
2804
			$member = Member::currentUser();
2805
		}
2806
		if(Permission::checkMember($member, "ADMIN")) return true;
2807
2808
		if($this->manyManyComponent('Can' . $perm)) {
2809
			if($this->ParentID && $this->SecurityType == 'Inherit') {
2810
				if(!($p = $this->Parent)) {
0 ignored issues
show
Documentation introduced by
The property Parent does not exist on object<DataObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2811
					return false;
2812
				}
2813
				return $this->Parent->can($perm, $member);
2814
2815
			} else {
2816
				$permissionCache = $this->uninherited('permissionCache');
2817
				$memberID = $member ? $member->ID : 'none';
2818
2819
				if(!isset($permissionCache[$memberID][$perm])) {
2820
					if($member->ID) {
2821
						$groups = $member->Groups();
2822
					}
2823
2824
					$groupList = implode(', ', $groups->column("ID"));
0 ignored issues
show
Bug introduced by
The variable $groups does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
2825
2826
					// TODO Fix relation table hardcoding
2827
					$query = new SQLSelect(
2828
						"\"Page_Can$perm\".PageID",
2829
					array("\"Page_Can$perm\""),
2830
						"GroupID IN ($groupList)");
2831
2832
					$permissionCache[$memberID][$perm] = $query->execute()->column();
2833
2834
					if($perm == "View") {
2835
						// TODO Fix relation table hardcoding
2836
						$query = new SQLSelect("\"SiteTree\".\"ID\"", array(
2837
							"\"SiteTree\"",
2838
							"LEFT JOIN \"Page_CanView\" ON \"Page_CanView\".\"PageID\" = \"SiteTree\".\"ID\""
2839
							), "\"Page_CanView\".\"PageID\" IS NULL");
2840
2841
							$unsecuredPages = $query->execute()->column();
2842
							if($permissionCache[$memberID][$perm]) {
2843
								$permissionCache[$memberID][$perm]
2844
									= array_merge($permissionCache[$memberID][$perm], $unsecuredPages);
2845
							} else {
2846
								$permissionCache[$memberID][$perm] = $unsecuredPages;
2847
							}
2848
					}
2849
2850
					Config::inst()->update($this->class, 'permissionCache', $permissionCache);
2851
				}
2852
2853
				if($permissionCache[$memberID][$perm]) {
2854
					return in_array($this->ID, $permissionCache[$memberID][$perm]);
2855
				}
2856
			}
2857
		} else {
2858
			return parent::can($perm, $member);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ViewableData as the method can() does only exist in the following sub-classes of ViewableData: AdminRootController, AssetControlExtensionTest_ArchivedObject, AssetControlExtensionTest_Object, AssetControlExtensionTest_VersionedObject, AssetFieldTest_Controller, AssetFieldTest_Object, BasicAuthTest_ControllerSecuredWithPermission, BasicAuthTest_ControllerSecuredWithoutPermission, CMSMenuTest_LeftAndMainController, CMSProfileController, CMSSecurity, CheckboxFieldTest_Article, CheckboxSetFieldTest_Article, CheckboxSetFieldTest_Tag, ClassInfoTest_BaseClass, ClassInfoTest_BaseDataClass, ClassInfoTest_ChildClass, ClassInfoTest_GrandChildClass, ClassInfoTest_HasFields, ClassInfoTest_NoFields, ClassInfoTest_WithRelation, CliController, ComponentSetTest_Player, ComponentSetTest_Team, Controller, ControllerTest_AccessBaseController, ControllerTest_AccessSecuredController, ControllerTest_AccessWildcardSecuredController, ControllerTest_ContainerController, ControllerTest_Controller, ControllerTest_HasAction, ControllerTest_HasAction_Unsecured, ControllerTest_IndexSecuredController, ControllerTest_SubController, ControllerTest_UnsecuredController, CsvBulkLoaderTest_Player, CsvBulkLoaderTest_PlayerContract, CsvBulkLoaderTest_Team, DBClassNameTest_CustomDefault, DBClassNameTest_CustomDefaultSubclass, DBClassNameTest_Object, DBClassNameTest_ObjectSubClass, DBClassNameTest_ObjectSubSubClass, DBClassNameTest_OtherClass, DBCompositeTest_DataObject, DBFileTest_ImageOnly, DBFileTest_Object, DBFileTest_Subclass, DataDifferencerTest_HasOneRelationObject, DataDifferencerTest_Object, DataExtensionTest_CMSFieldsBase, DataExtensionTest_CMSFieldsChild, DataExtensionTest_CMSFieldsGrandchild, DataExtensionTest_Member, DataExtensionTest_MyObject, DataExtensionTest_Player, DataExtensionTest_RelatedObject, DataObject, DataObjectDuplicateTestClass1, DataObjectDuplicateTestClass2, DataObjectDuplicateTestClass3, DataObjectSchemaGenerationTest_DO, DataObjectSchemaGenerationTest_IndexDO, DataObjectTest\NamespacedClass, DataObjectTest\RelationClass, DataObjectTest_Bogey, DataObjectTest_CEO, DataObjectTest_Company, DataObjectTest_EquipmentCompany, DataObjectTest_ExtendedTeamComment, DataObjectTest_Fan, DataObjectTest_FieldlessSubTable, DataObjectTest_FieldlessTable, DataObjectTest_Fixture, DataObjectTest_Play, DataObjectTest_Player, DataObjectTest_Ploy, DataObjectTest_Staff, DataObjectTest_SubEquipmentCompany, DataObjectTest_SubTeam, DataObjectTest_Team, DataObjectTest_TeamComment, DataObjectTest_ValidatedObject, DataQueryTest_A, DataQueryTest_B, DataQueryTest_C, DataQueryTest_D, DataQueryTest_E, DataQueryTest_F, DatabaseAdmin, DatabaseTest_MyObject, DatetimeFieldTest_Model, DecimalTest_DataObject, DevAdminControllerTest_Controller1, DevBuildController, DevelopmentAdmin, DirectorTestRequest_Controller, EmailFieldTest_Controller, FakeController, File, FileTest_MyCustomFile, FixtureBlueprintTest_Article, FixtureBlueprintTest_Page, FixtureBlueprintTest_SiteTree, FixtureFactoryTest_DataObject, FixtureFactoryTest_DataObjectRelation, Folder, FormScaffolderTest_Article, FormScaffolderTest_Author, FormScaffolderTest_Tag, FormTest_Controller, FormTest_ControllerWithSecurityToken, FormTest_ControllerWithStrictPostCheck, FormTest_Player, FormTest_Team, FulltextFilterTest_DataObject, GridFieldAction_Delete_Team, GridFieldAction_Edit_Team, GridFieldAddExistingAutocompleterTest_Controller, GridFieldDetailFormTest_Category, GridFieldDetailFormTest_CategoryController, GridFieldDetailFormTest_Controller, GridFieldDetailFormTest_GroupController, GridFieldDetailFormTest_PeopleGroup, GridFieldDetailFormTest_Person, GridFieldExportButtonTest_NoView, GridFieldExportButtonTest_Team, GridFieldPrintButtonTest_DO, GridFieldSortableHeaderTest_Cheerleader, GridFieldSortableHeaderTest_CheerleaderHat, GridFieldSortableHeaderTest_Mom, GridFieldSortableHeaderTest_Team, GridFieldSortableHeaderTest_TeamGroup, GridFieldTest_Cheerleader, GridFieldTest_Permissions, GridFieldTest_Player, GridFieldTest_Team, GridField_URLHandlerTest_Controller, Group, GroupTest_Member, HierarchyTest_Object, HtmlEditorFieldTest_Object, Image, InstallerTest, LeftAndMain, LeftAndMainTest_Controller, LeftAndMainTest_Object, ListboxFieldTest_Article, ListboxFieldTest_DataObject, ListboxFieldTest_Tag, LoginAttempt, ManyManyListTest_ExtraFields, ManyManyListTest_IndirectPrimary, ManyManyListTest_Secondary, ManyManyListTest_SecondarySub, Member, MemberDatetimeOptionsetFieldTest_Controller, MemberPassword, ModelAdmin, ModelAdminTest_Admin, ModelAdminTest_Contact, ModelAdminTest_Player, ModelAdminTest_PlayerAdmin, MoneyFieldTest_CustomSetter_Object, MoneyFieldTest_Object, MoneyTest_DataObject, MoneyTest_SubClass, MySQLDatabaseTest_Data, NumericFieldTest_Object, OtherSubclassWithSameField, Permission, PermissionRole, PermissionRoleCode, RememberLoginHash, RequestHandlingFieldTest_Controller, RequestHandlingTest_AllowedController, RequestHandlingTest_Controller, RequestHandlingTest_Cont...rFormWithAllowedActions, RequestHandlingTest_FormActionController, RestfulServiceTest_Controller, SQLInsertTestBase, SQLSelectTestBase, SQLSelectTestChild, SQLSelectTest_DO, SQLUpdateChild, SQLUpdateTestBase, SSViewerCacheBlockTest_Model, SSViewerCacheBlockTest_VersionedModel, SSViewerTest_Controller, SSViewerTest_Object, SapphireInfo, SapphireREPL, SearchContextTest_Action, SearchContextTest_AllFilterTypes, SearchContextTest_Book, SearchContextTest_Company, SearchContextTest_Deadline, SearchContextTest_Person, SearchContextTest_Project, SearchFilterApplyRelationTest_DO, SearchFilterApplyRelationTest_HasManyChild, SearchFilterApplyRelationTest_HasManyGrantChild, SearchFilterApplyRelationTest_HasManyParent, SearchFilterApplyRelationTest_HasOneChild, SearchFilterApplyRelationTest_HasOneGrantChild, SearchFilterApplyRelationTest_HasOneParent, SearchFilterApplyRelationTest_ManyManyChild, SearchFilterApplyRelationTest_ManyManyGrantChild, SearchFilterApplyRelationTest_ManyManyParent, Security, SecurityAdmin, SecurityTest_NullController, SecurityTest_SecuredController, SilverStripe\Filesystem\...ProtectedFileController, SilverStripe\Framework\Tests\ClassI, SubclassedDBFieldObject, TaskRunner, TransactionTest_Object, UnsavedRelationListTest_DataObject, Upload, UploadFieldTest_Controller, UploadFieldTest_ExtendedFile, UploadFieldTest_Record, VersionableExtensionsTest_DataObject, VersionedLazySub_DataObject, VersionedLazy_DataObject, VersionedOwnershipTest_Attachment, VersionedOwnershipTest_Banner, VersionedOwnershipTest_CustomRelation, VersionedOwnershipTest_Image, VersionedOwnershipTest_Object, VersionedOwnershipTest_Page, VersionedOwnershipTest_Related, VersionedOwnershipTest_RelatedMany, VersionedOwnershipTest_Subclass, VersionedTest_AnotherSubclass, VersionedTest_DataObject, VersionedTest_PublicStage, VersionedTest_PublicViaExtension, VersionedTest_RelatedWithoutVersion, VersionedTest_SingleStage, VersionedTest_Subclass, VersionedTest_UnversionedWithField, VersionedTest_WithIndexes, XMLDataFormatterTest_DataObject, YamlFixtureTest_DataObject, YamlFixtureTest_DataObjectRelation, i18nTestModule, i18nTest_DataObject, i18nTextCollectorTestMyObject, i18nTextCollectorTestMySubObject. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
2859
		}
2860
	}
2861
2862
	/**
2863
	 * Process tri-state responses from permission-alterting extensions.  The extensions are
2864
	 * expected to return one of three values:
2865
	 *
2866
	 *  - false: Disallow this permission, regardless of what other extensions say
2867
	 *  - true: Allow this permission, as long as no other extensions return false
2868
	 *  - NULL: Don't affect the outcome
2869
	 *
2870
	 * This method itself returns a tri-state value, and is designed to be used like this:
2871
	 *
2872
	 * <code>
2873
	 * $extended = $this->extendedCan('canDoSomething', $member);
2874
	 * if($extended !== null) return $extended;
2875
	 * else return $normalValue;
2876
	 * </code>
2877
	 *
2878
	 * @param string $methodName Method on the same object, e.g. {@link canEdit()}
2879
	 * @param Member|int $member
2880
	 * @param array $context Optional context
2881
	 * @return boolean|null
2882
	 */
2883
	public function extendedCan($methodName, $member, $context = array()) {
2884
		$results = $this->extend($methodName, $member, $context);
2885
		if($results && is_array($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...
2886
			// Remove NULLs
2887
			$results = array_filter($results, function($v) {return !is_null($v);});
2888
			// If there are any non-NULL responses, then return the lowest one of them.
2889
			// If any explicitly deny the permission, then we don't get access
2890
			if($results) return min($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...
2891
		}
2892
		return null;
2893
	}
2894
2895
	/**
2896
	 * @param Member $member
2897
	 * @return boolean
2898
	 */
2899
	public function canView($member = null) {
2900
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2899 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
2901
		if($extended !== null) {
2902
			return $extended;
2903
		}
2904
		return Permission::check('ADMIN', 'any', $member);
2905
	}
2906
2907
	/**
2908
	 * @param Member $member
2909
	 * @return boolean
2910
	 */
2911
	public function canEdit($member = null) {
2912
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2911 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
2913
		if($extended !== null) {
2914
			return $extended;
2915
		}
2916
		return Permission::check('ADMIN', 'any', $member);
2917
	}
2918
2919
	/**
2920
	 * @param Member $member
2921
	 * @return boolean
2922
	 */
2923
	public function canDelete($member = null) {
2924
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2923 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
2925
		if($extended !== null) {
2926
			return $extended;
2927
		}
2928
		return Permission::check('ADMIN', 'any', $member);
2929
	}
2930
2931
	/**
2932
	 * @param Member $member
2933
	 * @param array $context Additional context-specific data which might
2934
	 * affect whether (or where) this object could be created.
2935
	 * @return boolean
2936
	 */
2937
	public function canCreate($member = null, $context = array()) {
2938
		$extended = $this->extendedCan(__FUNCTION__, $member, $context);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2937 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
2939
		if($extended !== null) {
2940
			return $extended;
2941
		}
2942
		return Permission::check('ADMIN', 'any', $member);
2943
	}
2944
2945
	/**
2946
	 * Debugging used by Debug::show()
2947
	 *
2948
	 * @return string HTML data representing this object
2949
	 */
2950
	public function debug() {
2951
		$val = "<h3>Database record: $this->class</h3>\n<ul>\n";
2952
		if($this->record) foreach($this->record as $fieldName => $fieldVal) {
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...
2953
			$val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
2954
		}
2955
		$val .= "</ul>\n";
2956
		return $val;
2957
	}
2958
2959
	/**
2960
	 * Return the DBField object that represents the given field.
2961
	 * This works similarly to obj() with 2 key differences:
2962
	 *   - it still returns an object even when the field has no value.
2963
	 *   - it only matches fields and not methods
2964
	 *   - it matches foreign keys generated by has_one relationships, eg, "ParentID"
2965
	 *
2966
	 * @param string $fieldName Name of the field
2967
	 * @return DBField The field as a DBField object
2968
	 */
2969
	public function dbObject($fieldName) {
2970
		$value = isset($this->record[$fieldName])
2971
			? $this->record[$fieldName]
2972
			: null;
2973
2974
		// If we have a DBField object in $this->record, then return that
2975
		if(is_object($value)) {
2976
			return $value;
2977
		}
2978
2979
		// Build and populate new field otherwise
2980
		$helper = $this->db($fieldName, true);
2981
		if($helper) {
2982
			list($table, $spec) = explode('.', $helper);
2983
			$obj = Object::create_from_string($spec, $fieldName);
2984
			$obj->setTable($table);
2985
			$obj->setValue($value, $this, false);
2986
			return $obj;
2987
		}
2988
	}
2989
2990
	/**
2991
	 * Traverses to a DBField referenced by relationships between data objects.
2992
	 *
2993
	 * The path to the related field is specified with dot separated syntax
2994
	 * (eg: Parent.Child.Child.FieldName).
2995
	 *
2996
	 * @param string $fieldPath
2997
	 *
2998
	 * @return mixed DBField of the field on the object or a DataList instance.
2999
	 */
3000
	public function relObject($fieldPath) {
3001
		$object = null;
3002
3003
		if(strpos($fieldPath, '.') !== false) {
3004
			$parts = explode('.', $fieldPath);
3005
			$fieldName = array_pop($parts);
3006
3007
			// Traverse dot syntax
3008
			$component = $this;
3009
3010
			foreach($parts as $relation) {
3011
				if($component instanceof SS_List) {
3012
					if(method_exists($component,$relation)) {
3013
						$component = $component->$relation();
3014
					} else {
3015
						$component = $component->relation($relation);
3016
					}
3017
				} else {
3018
					$component = $component->$relation();
3019
				}
3020
			}
3021
3022
			$object = $component->dbObject($fieldName);
3023
3024
		} else {
3025
			$object = $this->dbObject($fieldPath);
3026
		}
3027
3028
		return $object;
3029
	}
3030
3031
	/**
3032
	 * Traverses to a field referenced by relationships between data objects, returning the value
3033
	 * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)
3034
	 *
3035
	 * @param $fieldName string
3036
	 * @return string | null - will return null on a missing value
3037
	 */
3038
	public function relField($fieldName) {
3039
		$component = $this;
3040
3041
		// We're dealing with relations here so we traverse the dot syntax
3042
		if(strpos($fieldName, '.') !== false) {
3043
			$relations = explode('.', $fieldName);
3044
			$fieldName = array_pop($relations);
3045
			foreach($relations as $relation) {
3046
				// Inspect $component for element $relation
3047
				if($component->hasMethod($relation)) {
3048
					// Check nested method
3049
					$component = $component->$relation();
3050
				} elseif($component instanceof SS_List) {
3051
					// Select adjacent relation from DataList
3052
					$component = $component->relation($relation);
3053
				} elseif($component instanceof DataObject
3054
					&& ($dbObject = $component->dbObject($relation))
3055
				) {
3056
					// Select db object
3057
					$component = $dbObject;
3058
				} else {
3059
					user_error("$relation is not a relation/field on ".get_class($component), E_USER_ERROR);
3060
				}
3061
			}
3062
		}
3063
3064
		// Bail if the component is null
3065
		if(!$component) {
3066
			return null;
3067
		}
3068
		if($component->hasMethod($fieldName)) {
3069
			return $component->$fieldName();
3070
		}
3071
		return $component->$fieldName;
3072
	}
3073
3074
	/**
3075
	 * Temporary hack to return an association name, based on class, to get around the mangle
3076
	 * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
3077
	 *
3078
	 * @return String
3079
	 */
3080
	public function getReverseAssociation($className) {
3081
		if (is_array($this->manyMany())) {
3082
			$many_many = array_flip($this->manyMany());
3083
			if (array_key_exists($className, $many_many)) return $many_many[$className];
3084
		}
3085
		if (is_array($this->hasMany())) {
3086
			$has_many = array_flip($this->hasMany());
3087
			if (array_key_exists($className, $has_many)) return $has_many[$className];
3088
		}
3089
		if (is_array($this->hasOne())) {
3090
			$has_one = array_flip($this->hasOne());
3091
			if (array_key_exists($className, $has_one)) return $has_one[$className];
3092
		}
3093
3094
		return false;
3095
	}
3096
3097
	/**
3098
	 * Return all objects matching the filter
3099
	 * sub-classes are automatically selected and included
3100
	 *
3101
	 * @param string $callerClass The class of objects to be returned
3102
	 * @param string|array $filter A filter to be inserted into the WHERE clause.
3103
	 * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
3104
	 * @param string|array $sort A sort expression to be inserted into the ORDER
3105
	 * BY clause.  If omitted, self::$default_sort will be used.
3106
	 * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
3107
	 * @param string|array $limit A limit expression to be inserted into the LIMIT clause.
3108
	 * @param string $containerClass The container class to return the results in.
3109
	 *
3110
	 * @todo $containerClass is Ignored, why?
3111
	 *
3112
	 * @return DataList The objects matching the filter, in the class specified by $containerClass
3113
	 */
3114
	public static function get($callerClass = null, $filter = "", $sort = "", $join = "", $limit = null,
3115
			$containerClass = 'DataList') {
3116
3117
		if($callerClass == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $callerClass of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
3118
			$callerClass = get_called_class();
3119
			if($callerClass == 'DataObject') {
3120
				throw new \InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
3121
			}
3122
3123
			if($filter || $sort || $join || $limit || ($containerClass != 'DataList')) {
3124
				throw new \InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
3125
					. ' arguments');
3126
			}
3127
3128
			$result = DataList::create(get_called_class());
3129
			$result->setDataModel(DataModel::inst());
3130
			return $result;
3131
		}
3132
3133
		if($join) {
3134
			throw new \InvalidArgumentException(
3135
				'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
3136
			);
3137
		}
3138
3139
		$result = DataList::create($callerClass)->where($filter)->sort($sort);
3140
3141
		if($limit && strpos($limit, ',') !== false) {
3142
			$limitArguments = explode(',', $limit);
3143
			$result = $result->limit($limitArguments[1],$limitArguments[0]);
3144
		} elseif($limit) {
3145
			$result = $result->limit($limit);
3146
		}
3147
3148
		$result->setDataModel(DataModel::inst());
3149
		return $result;
3150
	}
3151
3152
3153
	/**
3154
	 * Return the first item matching the given query.
3155
	 * All calls to get_one() are cached.
3156
	 *
3157
	 * @param string $callerClass The class of objects to be returned
3158
	 * @param string|array $filter A filter to be inserted into the WHERE clause.
3159
	 * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.
3160
	 * @param boolean $cache Use caching
3161
	 * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
3162
	 *
3163
	 * @return DataObject The first item matching the query
3164
	 */
3165
	public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "") {
3166
		$SNG = singleton($callerClass);
3167
3168
		$cacheComponents = array($filter, $orderby, $SNG->extend('cacheKeyComponent'));
3169
		$cacheKey = md5(var_export($cacheComponents, true));
3170
3171
		// Flush destroyed items out of the cache
3172
		if($cache && isset(self::$_cache_get_one[$callerClass][$cacheKey])
3173
				&& self::$_cache_get_one[$callerClass][$cacheKey] instanceof DataObject
3174
				&& self::$_cache_get_one[$callerClass][$cacheKey]->destroyed) {
3175
3176
			self::$_cache_get_one[$callerClass][$cacheKey] = false;
3177
		}
3178
		if(!$cache || !isset(self::$_cache_get_one[$callerClass][$cacheKey])) {
3179
			$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...
3180
			$item = $dl->First();
3181
3182
			if($cache) {
3183
				self::$_cache_get_one[$callerClass][$cacheKey] = $item;
3184
				if(!self::$_cache_get_one[$callerClass][$cacheKey]) {
3185
					self::$_cache_get_one[$callerClass][$cacheKey] = false;
3186
				}
3187
			}
3188
		}
3189
		return $cache ? self::$_cache_get_one[$callerClass][$cacheKey] : $item;
0 ignored issues
show
Bug introduced by
The variable $item does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
3190
	}
3191
3192
	/**
3193
	 * Flush the cached results for all relations (has_one, has_many, many_many)
3194
	 * Also clears any cached aggregate data.
3195
	 *
3196
	 * @param boolean $persistent When true will also clear persistent data stored in the Cache system.
3197
	 *                            When false will just clear session-local cached data
3198
	 * @return DataObject $this
3199
	 */
3200
	public function flushCache($persistent = true) {
0 ignored issues
show
Unused Code introduced by
The parameter $persistent is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
3201
		if($this->class == 'DataObject') {
3202
			self::$_cache_get_one = array();
3203
			return $this;
3204
		}
3205
3206
		$classes = ClassInfo::ancestry($this->class);
3207
		foreach($classes as $class) {
3208
			if(isset(self::$_cache_get_one[$class])) unset(self::$_cache_get_one[$class]);
3209
		}
3210
3211
		$this->extend('flushCache');
3212
3213
		$this->components = array();
3214
		return $this;
3215
	}
3216
3217
	/**
3218
	 * Flush the get_one global cache and destroy associated objects.
3219
	 */
3220
	public static function flush_and_destroy_cache() {
3221
		if(self::$_cache_get_one) foreach(self::$_cache_get_one as $class => $items) {
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...
3222
			if(is_array($items)) foreach($items as $item) {
3223
				if($item) $item->destroy();
3224
			}
3225
		}
3226
		self::$_cache_get_one = array();
3227
	}
3228
3229
	/**
3230
	 * Reset all global caches associated with DataObject.
3231
	 */
3232
	public static function reset() {
3233
		DBClassName::clear_classname_cache();
3234
		self::$_cache_has_own_table = array();
3235
		self::$_cache_get_one = array();
3236
		self::$_cache_composite_fields = array();
3237
		self::$_cache_database_fields = array();
3238
		self::$_cache_get_class_ancestry = array();
3239
		self::$_cache_field_labels = array();
3240
	}
3241
3242
	/**
3243
	 * Return the given element, searching by ID
3244
	 *
3245
	 * @param string $callerClass The class of the object to be returned
3246
	 * @param int $id The id of the element
3247
	 * @param boolean $cache See {@link get_one()}
3248
	 *
3249
	 * @return DataObject The element
3250
	 */
3251
	public static function get_by_id($callerClass, $id, $cache = true) {
3252
		if(!is_numeric($id)) {
3253
			user_error("DataObject::get_by_id passed a non-numeric ID #$id", E_USER_WARNING);
3254
		}
3255
3256
		// Check filter column
3257
		if(is_subclass_of($callerClass, 'DataObject')) {
3258
			$baseClass = ClassInfo::baseDataClass($callerClass);
3259
			$column = "\"$baseClass\".\"ID\"";
3260
		} else{
3261
			// This simpler code will be used by non-DataObject classes that implement DataObjectInterface
3262
			$column = '"ID"';
3263
		}
3264
3265
		// Relegate to get_one
3266
		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...
3267
	}
3268
3269
	/**
3270
	 * Get the name of the base table for this object
3271
	 */
3272
	public function baseTable() {
3273
		$tableClasses = ClassInfo::dataClassesFor($this->class);
3274
		return array_shift($tableClasses);
3275
	}
3276
3277
	/**
3278
	 * @var Array Parameters used in the query that built this object.
3279
	 * This can be used by decorators (e.g. lazy loading) to
3280
	 * run additional queries using the same context.
3281
	 */
3282
	protected $sourceQueryParams;
3283
3284
	/**
3285
	 * @see $sourceQueryParams
3286
	 * @return array
3287
	 */
3288
	public function getSourceQueryParams() {
3289
		return $this->sourceQueryParams;
3290
	}
3291
3292
	/**
3293
	 * Get list of parameters that should be inherited to relations on this object
3294
	 *
3295
	 * @return array
3296
	 */
3297
	public function getInheritableQueryParams() {
3298
		$params = $this->getSourceQueryParams();
3299
		$this->extend('updateInheritableQueryParams', $params);
3300
		return $params;
3301
	}
3302
3303
	/**
3304
	 * @see $sourceQueryParams
3305
	 * @param array
3306
	 */
3307
	public function setSourceQueryParams($array) {
3308
		$this->sourceQueryParams = $array;
3309
	}
3310
3311
	/**
3312
	 * @see $sourceQueryParams
3313
	 * @param array
3314
	 */
3315
	public function setSourceQueryParam($key, $value) {
3316
		$this->sourceQueryParams[$key] = $value;
3317
	}
3318
3319
	/**
3320
	 * @see $sourceQueryParams
3321
	 * @return Mixed
3322
	 */
3323
	public function getSourceQueryParam($key) {
3324
		if(isset($this->sourceQueryParams[$key])) return $this->sourceQueryParams[$key];
3325
		else return null;
3326
	}
3327
3328
	//-------------------------------------------------------------------------------------------//
3329
3330
	/**
3331
	 * Return the database indexes on this table.
3332
	 * This array is indexed by the name of the field with the index, and
3333
	 * the value is the type of index.
3334
	 */
3335
	public function databaseIndexes() {
3336
		$has_one = $this->uninherited('has_one',true);
0 ignored issues
show
Unused Code introduced by
The call to DataObject::uninherited() has too many arguments starting with true.

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3337
		$classIndexes = $this->uninherited('indexes',true);
0 ignored issues
show
Unused Code introduced by
The call to DataObject::uninherited() has too many arguments starting with true.

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3338
		//$fileIndexes = $this->uninherited('fileIndexes', true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
3339
3340
		$indexes = array();
3341
3342
		if($has_one) {
3343
			foreach($has_one as $relationshipName => $fieldType) {
0 ignored issues
show
Bug introduced by
The expression $has_one of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3344
				$indexes[$relationshipName . 'ID'] = true;
3345
			}
3346
		}
3347
3348
		if($classIndexes) {
3349
			foreach($classIndexes as $indexName => $indexType) {
0 ignored issues
show
Bug introduced by
The expression $classIndexes of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3350
				$indexes[$indexName] = $indexType;
3351
			}
3352
		}
3353
3354
		if(get_parent_class($this) == "DataObject") {
3355
			$indexes['ClassName'] = true;
3356
		}
3357
3358
		return $indexes;
3359
	}
3360
3361
	/**
3362
	 * Check the database schema and update it as necessary.
3363
	 *
3364
	 * @uses DataExtension->augmentDatabase()
3365
	 */
3366
	public function requireTable() {
3367
		// Only build the table if we've actually got fields
3368
		$fields = self::database_fields($this->class);
3369
		$extensions = self::database_extensions($this->class);
3370
3371
		$indexes = $this->databaseIndexes();
3372
3373
		// Validate relationship configuration
3374
		$this->validateModelDefinitions();
3375
3376
		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...
3377
			$hasAutoIncPK = ($this->class == ClassInfo::baseDataClass($this->class));
3378
			DB::require_table($this->class, $fields, $indexes, $hasAutoIncPK, $this->stat('create_table_options'),
3379
				$extensions);
3380
		} else {
3381
			DB::dont_require_table($this->class);
3382
		}
3383
3384
		// Build any child tables for many_many items
3385
		if($manyMany = $this->uninherited('many_many', true)) {
0 ignored issues
show
Unused Code introduced by
The call to DataObject::uninherited() has too many arguments starting with true.

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3386
			$extras = $this->uninherited('many_many_extraFields', true);
0 ignored issues
show
Unused Code introduced by
The call to DataObject::uninherited() has too many arguments starting with true.

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3387
			foreach($manyMany as $relationship => $childClass) {
0 ignored issues
show
Bug introduced by
The expression $manyMany of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3388
				// Build field list
3389
				$manymanyFields = array(
3390
					"{$this->class}ID" => "Int",
3391
				(($this->class == $childClass) ? "ChildID" : "{$childClass}ID") => "Int",
3392
				);
3393
				if(isset($extras[$relationship])) {
3394
					$manymanyFields = array_merge($manymanyFields, $extras[$relationship]);
3395
				}
3396
3397
				// Build index list
3398
				$manymanyIndexes = array(
3399
					"{$this->class}ID" => true,
3400
				(($this->class == $childClass) ? "ChildID" : "{$childClass}ID") => true,
3401
				);
3402
3403
				DB::require_table("{$this->class}_$relationship", $manymanyFields, $manymanyIndexes, true, null,
3404
					$extensions);
3405
			}
3406
		}
3407
3408
		// Let any extentions make their own database fields
3409
		$this->extend('augmentDatabase', $dummy);
3410
	}
3411
3412
	/**
3413
	 * Validate that the configured relations for this class use the correct syntaxes
3414
	 * @throws LogicException
3415
	 */
3416
	protected function validateModelDefinitions() {
3417
		$modelDefinitions = array(
3418
			'db' => Config::inst()->get($this->class, 'db', Config::UNINHERITED),
3419
			'has_one' => Config::inst()->get($this->class, 'has_one', Config::UNINHERITED),
3420
			'has_many' => Config::inst()->get($this->class, 'has_many', Config::UNINHERITED),
3421
			'belongs_to' => Config::inst()->get($this->class, 'belongs_to', Config::UNINHERITED),
3422
			'many_many' => Config::inst()->get($this->class, 'many_many', Config::UNINHERITED),
3423
			'belongs_many_many' => Config::inst()->get($this->class, 'belongs_many_many', Config::UNINHERITED),
3424
			'many_many_extraFields' => Config::inst()->get($this->class, 'many_many_extraFields', Config::UNINHERITED)
3425
		);
3426
3427
		foreach($modelDefinitions as $defType => $relations) {
3428
			if( ! $relations) continue;
3429
3430
			foreach($relations as $k => $v) {
0 ignored issues
show
Bug introduced by
The expression $relations of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3431
				if($defType === 'many_many_extraFields') {
3432
					if(!is_array($v)) {
3433
						throw new LogicException("$this->class::\$many_many_extraFields has a bad entry: "
3434
							. var_export($k, true) . " => " . var_export($v, true)
3435
							. ". Each many_many_extraFields entry should map to a field specification array.");
3436
					}
3437
				} else {
3438
					if(!is_string($k) || is_numeric($k) || !is_string($v)) {
3439
						throw new LogicException("$this->class::$defType has a bad entry: "
3440
							. var_export($k, true). " => " . var_export($v, true) . ".  Each map key should be a
3441
							 relationship name, and the map value should be the data class to join to.");
3442
					}
3443
				}
3444
			}
3445
		}
3446
	}
3447
3448
	/**
3449
	 * Add default records to database. This function is called whenever the
3450
	 * database is built, after the database tables have all been created. Overload
3451
	 * this to add default records when the database is built, but make sure you
3452
	 * call parent::requireDefaultRecords().
3453
	 *
3454
	 * @uses DataExtension->requireDefaultRecords()
3455
	 */
3456
	public function requireDefaultRecords() {
3457
		$defaultRecords = $this->stat('default_records');
3458
3459
		if(!empty($defaultRecords)) {
3460
			$hasData = DataObject::get_one($this->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...
3461
			if(!$hasData) {
3462
				$className = $this->class;
3463
				foreach($defaultRecords as $record) {
0 ignored issues
show
Bug introduced by
The expression $defaultRecords of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3464
					$obj = $this->model->$className->newObject($record);
3465
					$obj->write();
3466
				}
3467
				DB::alteration_message("Added default records to $className table","created");
3468
			}
3469
		}
3470
3471
		// Let any extentions make their own database default data
3472
		$this->extend('requireDefaultRecords', $dummy);
3473
	}
3474
3475
	/**
3476
	 * Get the default searchable fields for this object, as defined in the
3477
	 * $searchable_fields list. If searchable fields are not defined on the
3478
	 * data object, uses a default selection of summary fields.
3479
	 *
3480
	 * @return array
3481
	 */
3482
	public function searchableFields() {
3483
		// can have mixed format, need to make consistent in most verbose form
3484
		$fields = $this->stat('searchable_fields');
3485
		$labels = $this->fieldLabels();
3486
3487
		// fallback to summary fields (unless empty array is explicitly specified)
3488
		if( ! $fields && ! is_array($fields)) {
3489
			$summaryFields = array_keys($this->summaryFields());
3490
			$fields = array();
3491
3492
			// remove the custom getters as the search should not include them
3493
			if($summaryFields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $summaryFields of type array<integer|string> 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...
3494
				foreach($summaryFields as $key => $name) {
3495
					$spec = $name;
3496
3497
					// Extract field name in case this is a method called on a field (e.g. "Date.Nice")
3498
					if(($fieldPos = strpos($name, '.')) !== false) {
3499
						$name = substr($name, 0, $fieldPos);
3500
					}
3501
3502
					if($this->hasDatabaseField($name)) {
3503
						$fields[] = $name;
3504
					} elseif($this->relObject($spec)) {
3505
						$fields[] = $spec;
3506
					}
3507
				}
3508
			}
3509
		}
3510
3511
		// we need to make sure the format is unified before
3512
		// augmenting fields, so extensions can apply consistent checks
3513
		// but also after augmenting fields, because the extension
3514
		// might use the shorthand notation as well
3515
3516
		// rewrite array, if it is using shorthand syntax
3517
		$rewrite = array();
3518
		foreach($fields as $name => $specOrName) {
0 ignored issues
show
Bug introduced by
The expression $fields of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3519
			$identifer = (is_int($name)) ? $specOrName : $name;
3520
3521
			if(is_int($name)) {
3522
				// 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...
3523
				$rewrite[$identifer] = array();
3524
			} elseif(is_array($specOrName)) {
3525
				// 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...
3526
				//   'filter => 'ExactMatchFilter',
3527
				//   '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...
3528
				//   '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...
3529
				// ))
3530
				$rewrite[$identifer] = array_merge(
3531
					array('filter' => $this->relObject($identifer)->stat('default_search_filter_class')),
3532
					(array)$specOrName
3533
				);
3534
			} else {
3535
				// 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...
3536
				$rewrite[$identifer] = array(
3537
					'filter' => $specOrName,
3538
				);
3539
			}
3540
			if(!isset($rewrite[$identifer]['title'])) {
3541
				$rewrite[$identifer]['title'] = (isset($labels[$identifer]))
3542
					? $labels[$identifer] : FormField::name_to_label($identifer);
3543
			}
3544
			if(!isset($rewrite[$identifer]['filter'])) {
3545
				$rewrite[$identifer]['filter'] = 'PartialMatchFilter';
3546
			}
3547
		}
3548
3549
		$fields = $rewrite;
3550
3551
		// apply DataExtensions if present
3552
		$this->extend('updateSearchableFields', $fields);
3553
3554
		return $fields;
3555
	}
3556
3557
	/**
3558
	 * Get any user defined searchable fields labels that
3559
	 * exist. Allows overriding of default field names in the form
3560
	 * interface actually presented to the user.
3561
	 *
3562
	 * The reason for keeping this separate from searchable_fields,
3563
	 * which would be a logical place for this functionality, is to
3564
	 * avoid bloating and complicating the configuration array. Currently
3565
	 * much of this system is based on sensible defaults, and this property
3566
	 * would generally only be set in the case of more complex relationships
3567
	 * between data object being required in the search interface.
3568
	 *
3569
	 * Generates labels based on name of the field itself, if no static property
3570
	 * {@link self::field_labels} exists.
3571
	 *
3572
	 * @uses $field_labels
3573
	 * @uses FormField::name_to_label()
3574
	 *
3575
	 * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
3576
	 *
3577
	 * @return array|string Array of all element labels if no argument given, otherwise the label of the field
3578
	 */
3579
	public function fieldLabels($includerelations = true) {
3580
		$cacheKey = $this->class . '_' . $includerelations;
3581
3582
		if(!isset(self::$_cache_field_labels[$cacheKey])) {
3583
			$customLabels = $this->stat('field_labels');
3584
			$autoLabels = array();
3585
3586
			// get all translated static properties as defined in i18nCollectStatics()
3587
			$ancestry = ClassInfo::ancestry($this->class);
3588
			$ancestry = array_reverse($ancestry);
3589
			if($ancestry) foreach($ancestry as $ancestorClass) {
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...
3590
				if($ancestorClass == 'ViewableData') break;
3591
				$types = array(
3592
					'db'        => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
3593
				);
3594
				if($includerelations){
3595
					$types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
3596
					$types['has_many'] = (array)Config::inst()->get($ancestorClass, 'has_many', Config::UNINHERITED);
3597
					$types['many_many'] = (array)Config::inst()->get($ancestorClass, 'many_many', Config::UNINHERITED);
3598
					$types['belongs_many_many'] = (array)Config::inst()->get($ancestorClass, 'belongs_many_many', Config::UNINHERITED);
3599
				}
3600
				foreach($types as $type => $attrs) {
3601
					foreach($attrs as $name => $spec) {
3602
						$autoLabels[$name] = _t("{$ancestorClass}.{$type}_{$name}",FormField::name_to_label($name));
3603
					}
3604
				}
3605
			}
3606
3607
			$labels = array_merge((array)$autoLabels, (array)$customLabels);
3608
			$this->extend('updateFieldLabels', $labels);
3609
			self::$_cache_field_labels[$cacheKey] = $labels;
3610
		}
3611
3612
		return self::$_cache_field_labels[$cacheKey];
3613
	}
3614
3615
	/**
3616
	 * Get a human-readable label for a single field,
3617
	 * see {@link fieldLabels()} for more details.
3618
	 *
3619
	 * @uses fieldLabels()
3620
	 * @uses FormField::name_to_label()
3621
	 *
3622
	 * @param string $name Name of the field
3623
	 * @return string Label of the field
3624
	 */
3625
	public function fieldLabel($name) {
3626
		$labels = $this->fieldLabels();
3627
		return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name);
3628
	}
3629
3630
	/**
3631
	 * Get the default summary fields for this object.
3632
	 *
3633
	 * @todo use the translation apparatus to return a default field selection for the language
3634
	 *
3635
	 * @return array
3636
	 */
3637
	public function summaryFields() {
3638
		$fields = $this->stat('summary_fields');
3639
3640
		// if fields were passed in numeric array,
3641
		// convert to an associative array
3642
		if($fields && array_key_exists(0, $fields)) {
3643
			$fields = array_combine(array_values($fields), array_values($fields));
3644
		}
3645
3646
		if (!$fields) {
3647
			$fields = array();
3648
			// try to scaffold a couple of usual suspects
3649
			if ($this->hasField('Name')) $fields['Name'] = 'Name';
3650
			if ($this->hasDataBaseField('Title')) $fields['Title'] = 'Title';
3651
			if ($this->hasField('Description')) $fields['Description'] = 'Description';
3652
			if ($this->hasField('FirstName')) $fields['FirstName'] = 'First Name';
3653
		}
3654
		$this->extend("updateSummaryFields", $fields);
3655
3656
		// Final fail-over, just list ID field
3657
		if(!$fields) $fields['ID'] = 'ID';
3658
3659
		// Localize fields (if possible)
3660
		foreach($this->fieldLabels(false) as $name => $label) {
0 ignored issues
show
Bug introduced by
The expression $this->fieldLabels(false) of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3661
			// only attempt to localize if the label definition is the same as the field name.
3662
			// this will preserve any custom labels set in the summary_fields configuration
3663
			if(isset($fields[$name]) && $name === $fields[$name]) {
3664
				$fields[$name] = $label;
3665
			}
3666
		}
3667
3668
		return $fields;
3669
	}
3670
3671
	/**
3672
	 * Defines a default list of filters for the search context.
3673
	 *
3674
	 * If a filter class mapping is defined on the data object,
3675
	 * it is constructed here. Otherwise, the default filter specified in
3676
	 * {@link DBField} is used.
3677
	 *
3678
	 * @todo error handling/type checking for valid FormField and SearchFilter subclasses?
3679
	 *
3680
	 * @return array
3681
	 */
3682
	public function defaultSearchFilters() {
3683
		$filters = array();
3684
3685
		foreach($this->searchableFields() as $name => $spec) {
3686
			$filterClass = $spec['filter'];
3687
3688
			if($spec['filter'] instanceof SearchFilter) {
3689
				$filters[$name] = $spec['filter'];
3690
			} else {
3691
				$class = $spec['filter'];
3692
3693
				if(!is_subclass_of($spec['filter'], 'SearchFilter')) {
3694
					$class = 'PartialMatchFilter';
3695
				}
3696
3697
				$filters[$name] = new $class($name);
3698
			}
3699
		}
3700
3701
		return $filters;
3702
	}
3703
3704
	/**
3705
	 * @return boolean True if the object is in the database
3706
	 */
3707
	public function isInDB() {
3708
		return is_numeric( $this->ID ) && $this->ID > 0;
3709
	}
3710
3711
	/*
3712
	 * @ignore
3713
	 */
3714
	private static $subclass_access = true;
3715
3716
	/**
3717
	 * Temporarily disable subclass access in data object qeur
3718
	 */
3719
	public static function disable_subclass_access() {
3720
		self::$subclass_access = false;
3721
	}
3722
	public static function enable_subclass_access() {
3723
		self::$subclass_access = true;
3724
	}
3725
3726
	//-------------------------------------------------------------------------------------------//
3727
3728
	/**
3729
	 * Database field definitions.
3730
	 * This is a map from field names to field type. The field
3731
	 * type should be a class that extends .
3732
	 * @var array
3733
	 * @config
3734
	 */
3735
	private static $db = null;
3736
3737
	/**
3738
	 * Use a casting object for a field. This is a map from
3739
	 * field name to class name of the casting object.
3740
	 *
3741
	 * @var array
3742
	 */
3743
	private static $casting = array(
3744
		"Title" => 'Text',
3745
	);
3746
3747
	/**
3748
	 * Specify custom options for a CREATE TABLE call.
3749
	 * Can be used to specify a custom storage engine for specific database table.
3750
	 * All options have to be keyed for a specific database implementation,
3751
	 * identified by their class name (extending from {@link SS_Database}).
3752
	 *
3753
	 * <code>
3754
	 * array(
3755
	 *  'MySQLDatabase' => 'ENGINE=MyISAM'
3756
	 * )
3757
	 * </code>
3758
	 *
3759
	 * Caution: This API is experimental, and might not be
3760
	 * included in the next major release. Please use with care.
3761
	 *
3762
	 * @var array
3763
	 * @config
3764
	 */
3765
	private static $create_table_options = array(
3766
		'MySQLDatabase' => 'ENGINE=InnoDB'
3767
	);
3768
3769
	/**
3770
	 * If a field is in this array, then create a database index
3771
	 * on that field. This is a map from fieldname to index type.
3772
	 * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
3773
	 *
3774
	 * @var array
3775
	 * @config
3776
	 */
3777
	private static $indexes = null;
3778
3779
	/**
3780
	 * Inserts standard column-values when a DataObject
3781
	 * is instanciated. Does not insert default records {@see $default_records}.
3782
	 * This is a map from fieldname to default value.
3783
	 *
3784
	 *  - If you would like to change a default value in a sub-class, just specify it.
3785
	 *  - If you would like to disable the default value given by a parent class, set the default value to 0,'',
3786
	 *    or false in your subclass.  Setting it to null won't work.
3787
	 *
3788
	 * @var array
3789
	 * @config
3790
	 */
3791
	private static $defaults = null;
3792
3793
	/**
3794
	 * Multidimensional array which inserts default data into the database
3795
	 * on a db/build-call as long as the database-table is empty. Please use this only
3796
	 * for simple constructs, not for SiteTree-Objects etc. which need special
3797
	 * behaviour such as publishing and ParentNodes.
3798
	 *
3799
	 * Example:
3800
	 * array(
3801
	 *  array('Title' => "DefaultPage1", 'PageTitle' => 'page1'),
3802
	 *  array('Title' => "DefaultPage2")
3803
	 * ).
3804
	 *
3805
	 * @var array
3806
	 * @config
3807
	 */
3808
	private static $default_records = null;
3809
3810
	/**
3811
	 * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a
3812
	 * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class.
3813
	 *
3814
	 * Note that you cannot have a has_one and belongs_to relationship with the same name.
3815
	 *
3816
	 *	@var array
3817
	 * @config
3818
	 */
3819
	private static $has_one = null;
3820
3821
	/**
3822
	 * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.
3823
	 *
3824
	 * This does not actually create any data structures, but allows you to query the other object in a one-to-one
3825
	 * relationship from the child object. If you have multiple belongs_to links to another object you can use the
3826
	 * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use.
3827
	 *
3828
	 * Note that you cannot have a has_one and belongs_to relationship with the same name.
3829
	 *
3830
	 * @var array
3831
	 * @config
3832
	 */
3833
	private static $belongs_to;
3834
3835
	/**
3836
	 * This defines a one-to-many relationship. It is a map of component name to the remote data class.
3837
	 *
3838
	 * This relationship type does not actually create a data structure itself - you need to define a matching $has_one
3839
	 * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this
3840
	 * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show
3841
	 * which foreign key to use.
3842
	 *
3843
	 * @var array
3844
	 * @config
3845
	 */
3846
	private static $has_many = null;
3847
3848
	/**
3849
	 * many-many relationship definitions.
3850
	 * This is a map from component name to data type.
3851
	 * @var array
3852
	 * @config
3853
	 */
3854
	private static $many_many = null;
3855
3856
	/**
3857
	 * Extra fields to include on the connecting many-many table.
3858
	 * This is a map from field name to field type.
3859
	 *
3860
	 * Example code:
3861
	 * <code>
3862
	 * public static $many_many_extraFields = array(
3863
	 *  'Members' => array(
3864
	 *			'Role' => 'Varchar(100)'
3865
	 *		)
3866
	 * );
3867
	 * </code>
3868
	 *
3869
	 * @var array
3870
	 * @config
3871
	 */
3872
	private static $many_many_extraFields = null;
3873
3874
	/**
3875
	 * The inverse side of a many-many relationship.
3876
	 * This is a map from component name to data type.
3877
	 * @var array
3878
	 * @config
3879
	 */
3880
	private static $belongs_many_many = null;
3881
3882
	/**
3883
	 * The default sort expression. This will be inserted in the ORDER BY
3884
	 * clause of a SQL query if no other sort expression is provided.
3885
	 * @var string
3886
	 * @config
3887
	 */
3888
	private static $default_sort = null;
3889
3890
	/**
3891
	 * Default list of fields that can be scaffolded by the ModelAdmin
3892
	 * search interface.
3893
	 *
3894
	 * Overriding the default filter, with a custom defined filter:
3895
	 * <code>
3896
	 *  static $searchable_fields = array(
3897
	 *     "Name" => "PartialMatchFilter"
3898
	 *  );
3899
	 * </code>
3900
	 *
3901
	 * Overriding the default form fields, with a custom defined field.
3902
	 * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}.
3903
	 * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}.
3904
	 * <code>
3905
	 *  static $searchable_fields = array(
3906
	 *    "Name" => array(
3907
	 *      "field" => "TextField"
3908
	 *    )
3909
	 *  );
3910
	 * </code>
3911
	 *
3912
	 * Overriding the default form field, filter and title:
3913
	 * <code>
3914
	 *  static $searchable_fields = array(
3915
	 *    "Organisation.ZipCode" => array(
3916
	 *      "field" => "TextField",
3917
	 *      "filter" => "PartialMatchFilter",
3918
	 *      "title" => 'Organisation ZIP'
3919
	 *    )
3920
	 *  );
3921
	 * </code>
3922
	 * @config
3923
	 */
3924
	private static $searchable_fields = null;
3925
3926
	/**
3927
	 * User defined labels for searchable_fields, used to override
3928
	 * default display in the search form.
3929
	 * @config
3930
	 */
3931
	private static $field_labels = null;
3932
3933
	/**
3934
	 * Provides a default list of fields to be used by a 'summary'
3935
	 * view of this object.
3936
	 * @config
3937
	 */
3938
	private static $summary_fields = null;
3939
3940
	/**
3941
	 * Collect all static properties on the object
3942
	 * which contain natural language, and need to be translated.
3943
	 * The full entity name is composed from the class name and a custom identifier.
3944
	 *
3945
	 * @return array A numerical array which contains one or more entities in array-form.
3946
	 * Each numeric entity array contains the "arguments" for a _t() call as array values:
3947
	 * $entity, $string, $priority, $context.
3948
	 */
3949
	public function provideI18nEntities() {
3950
		$entities = array();
3951
3952
		$entities["{$this->class}.SINGULARNAME"] = array(
3953
			$this->singular_name(),
3954
3955
			'Singular name of the object, used in dropdowns and to generally identify a single object in the interface'
3956
		);
3957
3958
		$entities["{$this->class}.PLURALNAME"] = array(
3959
			$this->plural_name(),
3960
3961
			'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the'
3962
			. ' interface'
3963
		);
3964
3965
		return $entities;
3966
	}
3967
3968
	/**
3969
	 * Returns true if the given method/parameter has a value
3970
	 * (Uses the DBField::hasValue if the parameter is a database field)
3971
	 *
3972
	 * @param string $field The field name
3973
	 * @param array $arguments
3974
	 * @param bool $cache
3975
	 * @return boolean
3976
	 */
3977
	public function hasValue($field, $arguments = null, $cache = true) {
3978
		// has_one fields should not use dbObject to check if a value is given
3979
		if(!$this->hasOneComponent($field) && ($obj = $this->dbObject($field))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->hasOneComponent($field) of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
3980
			return $obj->exists();
3981
		} else {
3982
			return parent::hasValue($field, $arguments, $cache);
3983
		}
3984
	}
3985
3986
}
3987