Completed
Push — 3 ( eecbe0...aac828 )
by Loz
35s
created

DataObject::parseSortColumn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * A single database record & abstract class for the data-access-model.
4
 *
5
 * <h2>Extensions</h2>
6
 *
7
 * See {@link Extension} and {@link DataExtension}.
8
 *
9
 * <h2>Permission Control</h2>
10
 *
11
 * Object-level access control by {@link Permission}. Permission codes are arbitrary
12
 * strings which can be selected on a group-by-group basis.
13
 *
14
 * <code>
15
 * class Article extends DataObject implements PermissionProvider {
16
 *  static $api_access = true;
17
 *
18
 *  function canView($member = false) {
19
 *    return Permission::check('ARTICLE_VIEW');
20
 *  }
21
 *  function canEdit($member = false) {
22
 *    return Permission::check('ARTICLE_EDIT');
23
 *  }
24
 *  function canDelete() {
25
 *    return Permission::check('ARTICLE_DELETE');
26
 *  }
27
 *  function canCreate() {
28
 *    return Permission::check('ARTICLE_CREATE');
29
 *  }
30
 *  function providePermissions() {
31
 *    return array(
32
 *      'ARTICLE_VIEW' => 'Read an article object',
33
 *      'ARTICLE_EDIT' => 'Edit an article object',
34
 *      'ARTICLE_DELETE' => 'Delete an article object',
35
 *      'ARTICLE_CREATE' => 'Create an article object',
36
 *    );
37
 *  }
38
 * }
39
 * </code>
40
 *
41
 * Object-level access control by {@link Group} membership:
42
 * <code>
43
 * class Article extends DataObject {
44
 *   static $api_access = true;
45
 *
46
 *   function canView($member = false) {
47
 *     if(!$member) $member = Member::currentUser();
48
 *     return $member->inGroup('Subscribers');
49
 *   }
50
 *   function canEdit($member = false) {
51
 *     if(!$member) $member = Member::currentUser();
52
 *     return $member->inGroup('Editors');
53
 *   }
54
 *
55
 *   // ...
56
 * }
57
 * </code>
58
 *
59
 * If any public method on this class is prefixed with an underscore,
60
 * the results are cached in memory through {@link cachedCall()}.
61
 *
62
 *
63
 * @todo Add instance specific removeExtension() which undos loadExtraStatics()
64
 *  and defineMethods()
65
 *
66
 * @package framework
67
 * @subpackage model
68
 *
69
 * @property integer ID ID of the DataObject, 0 if the DataObject doesn't exist in database.
70
 * @property string ClassName Class name of the DataObject
71
 * @property string LastEdited Date and time of DataObject's last modification.
72
 * @property string Created Date and time of DataObject creation.
73
 */
74
class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider {
75
76
	/**
77
	 * Human-readable singular name.
78
	 * @var string
79
	 * @config
80
	 */
81
	private static $singular_name = null;
82
83
	/**
84
	 * Human-readable plural name
85
	 * @var string
86
	 * @config
87
	 */
88
	private static $plural_name = null;
89
90
	/**
91
	 * Allow API access to this object?
92
	 * @todo Define the options that can be set here
93
	 * @config
94
	 */
95
	private static $api_access = false;
96
97
	/**
98
	 * True if this DataObject has been destroyed.
99
	 * @var boolean
100
	 */
101
	public $destroyed = false;
102
103
	/**
104
	 * The DataModel from this this object comes
105
	 */
106
	protected $model;
107
108
	/**
109
	 * Data stored in this objects database record. An array indexed by fieldname.
110
	 *
111
	 * Use {@link toMap()} if you want an array representation
112
	 * of this object, as the $record array might contain lazy loaded field aliases.
113
	 *
114
	 * @var array
115
	 */
116
	protected $record;
117
118
	/**
119
	 * Represents a field that hasn't changed (before === after, thus before == after)
120
	 */
121
	const CHANGE_NONE = 0;
122
123
	/**
124
	 * Represents a field that has changed type, although not the loosely defined value.
125
	 * (before !== after && before == after)
126
	 * E.g. change 1 to true or "true" to true, but not true to 0.
127
	 * Value changes are by nature also considered strict changes.
128
	 */
129
	const CHANGE_STRICT = 1;
130
131
	/**
132
	 * Represents a field that has changed the loosely defined value
133
	 * (before != after, thus, before !== after))
134
	 * E.g. change false to true, but not false to 0
135
	 */
136
	const CHANGE_VALUE = 2;
137
138
	/**
139
	 * An array indexed by fieldname, true if the field has been changed.
140
	 * Use {@link getChangedFields()} and {@link isChanged()} to inspect
141
	 * the changed state.
142
	 *
143
	 * @var array
144
	 */
145
	private $changed;
146
147
	/**
148
	 * The database record (in the same format as $record), before
149
	 * any changes.
150
	 * @var array
151
	 */
152
	protected $original;
153
154
	/**
155
	 * Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete()
156
	 * @var boolean
157
	 */
158
	protected $brokenOnDelete = false;
159
160
	/**
161
	 * Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite()
162
	 * @var boolean
163
	 */
164
	protected $brokenOnWrite = false;
165
166
	/**
167
	 * @config
168
	 * @var boolean Should dataobjects be validated before they are written?
169
	 * Caution: Validation can contain safeguards against invalid/malicious data,
170
	 * and check permission levels (e.g. on {@link Group}). Therefore it is recommended
171
	 * to only disable validation for very specific use cases.
172
	 */
173
	private static $validation_enabled = true;
174
175
	/**
176
	 * Static caches used by relevant functions.
177
	 */
178
	public static $cache_has_own_table = array();
179
	protected static $_cache_db = array();
180
	protected static $_cache_get_one;
181
	protected static $_cache_get_class_ancestry;
182
	protected static $_cache_composite_fields = array();
183
	protected static $_cache_is_composite_field = array();
184
	protected static $_cache_custom_database_fields = array();
185
	protected static $_cache_field_labels = array();
186
187
	// base fields which are not defined in static $db
188
	private static $fixed_fields = array(
189
		'ID' => 'Int',
190
		'ClassName' => 'Enum',
191
		'LastEdited' => 'SS_Datetime',
192
		'Created' => 'SS_Datetime',
193
	);
194
195
	/**
196
	 * Non-static relationship cache, indexed by component name.
197
	 */
198
	protected $components;
199
200
	/**
201
	 * Non-static cache of has_many and many_many relations that can't be written until this object is saved.
202
	 */
203
	protected $unsavedRelations;
204
205
	/**
206
	 * Returns when validation on DataObjects is enabled.
207
	 *
208
	 * @deprecated 3.2 Use the "DataObject.validation_enabled" config setting instead
209
	 * @return bool
210
	 */
211
	public static function get_validation_enabled() {
212
		Deprecation::notice('3.2', 'Use the "DataObject.validation_enabled" config setting instead');
213
		return Config::inst()->get('DataObject', 'validation_enabled');
214
	}
215
216
	/**
217
	 * Set whether DataObjects should be validated before they are written.
218
	 *
219
	 * Caution: Validation can contain safeguards against invalid/malicious data,
220
	 * and check permission levels (e.g. on {@link Group}). Therefore it is recommended
221
	 * to only disable validation for very specific use cases.
222
	 *
223
	 * @param $enable bool
224
	 * @see DataObject::validate()
225
	 * @deprecated 3.2 Use the "DataObject.validation_enabled" config setting instead
226
	 */
227
	public static function set_validation_enabled($enable) {
228
		Deprecation::notice('3.2', 'Use the "DataObject.validation_enabled" config setting instead');
229
		Config::inst()->update('DataObject', 'validation_enabled', (bool)$enable);
230
	}
231
232
	/**
233
	 * @var [string] - class => ClassName field definition cache for self::database_fields
234
	 */
235
	private static $classname_spec_cache = array();
236
237
	/**
238
	 * Clear all cached classname specs. It's necessary to clear all cached subclassed names
239
	 * for any classes if a new class manifest is generated.
240
	 */
241
	public static function clear_classname_spec_cache() {
242
		self::$classname_spec_cache = array();
243
		PolymorphicForeignKey::clear_classname_spec_cache();
244
	}
245
246
	/**
247
	 * Determines the specification for the ClassName field for the given class
248
	 *
249
	 * @param string $class
250
	 * @param boolean $queryDB Determine if the DB may be queried for additional information
251
	 * @return string Resulting ClassName spec. If $queryDB is true this will include all
252
	 * legacy types that no longer have concrete classes in PHP
253
	 */
254
	public static function get_classname_spec($class, $queryDB = true) {
255
		// Check cache
256
		if(!empty(self::$classname_spec_cache[$class])) return self::$classname_spec_cache[$class];
257
258
		// Build known class names
259
		$classNames = ClassInfo::subclassesFor($class);
260
261
		// Enhance with existing classes in order to prevent legacy details being lost
262
		if($queryDB && DB::get_schema()->hasField($class, 'ClassName')) {
263
			$existing = DB::query("SELECT DISTINCT \"ClassName\" FROM \"{$class}\"")->column();
264
			$classNames = array_unique(array_merge($classNames, $existing));
265
		}
266
		$spec = "Enum('" . implode(', ', $classNames) . "')";
267
268
		// Only cache full information if queried
269
		if($queryDB) self::$classname_spec_cache[$class] = $spec;
270
		return $spec;
271
	}
272
273
	/**
274
	 * Return the complete map of fields on this object, including "Created", "LastEdited" and "ClassName".
275
	 * See {@link custom_database_fields()} for a getter that excludes these "base fields".
276
	 *
277
	 * @param string $class
278
	 * @param boolean $queryDB Determine if the DB may be queried for additional information
279
	 * @return array
280
	 */
281
	public static function database_fields($class, $queryDB = true) {
282
		if(get_parent_class($class) == 'DataObject') {
283
			// Merge fixed with ClassName spec and custom db fields
284
			$fixed = self::$fixed_fields;
285
			unset($fixed['ID']);
286
			return array_merge(
287
				$fixed,
288
				array('ClassName' => self::get_classname_spec($class, $queryDB)),
289
				self::custom_database_fields($class)
290
			);
291
		}
292
293
		return self::custom_database_fields($class);
294
	}
295
296
	/**
297
	 * Get all database columns explicitly defined on a class in {@link DataObject::$db}
298
	 * and {@link DataObject::$has_one}. Resolves instances of {@link CompositeDBField}
299
	 * into the actual database fields, rather than the name of the field which
300
	 * might not equate a database column.
301
	 *
302
	 * Does not include "base fields" like "ID", "ClassName", "Created", "LastEdited",
303
	 * see {@link database_fields()}.
304
	 *
305
	 * @uses CompositeDBField->compositeDatabaseFields()
306
	 *
307
	 * @param string $class
308
	 * @return array Map of fieldname to specification, similiar to {@link DataObject::$db}.
309
	 */
310
	public static function custom_database_fields($class) {
311
		if(isset(self::$_cache_custom_database_fields[$class])) {
312
			return self::$_cache_custom_database_fields[$class];
313
		}
314
315
		$fields = Config::inst()->get($class, 'db', Config::UNINHERITED);
316
317
		foreach(self::composite_fields($class, false) as $fieldName => $fieldClass) {
318
			// Remove the original fieldname, it's not an actual database column
319
			unset($fields[$fieldName]);
320
321
			// Add all composite columns
322
			$compositeFields = singleton($fieldClass)->compositeDatabaseFields();
323
			if($compositeFields) foreach($compositeFields as $compositeName => $spec) {
324
				$fields["{$fieldName}{$compositeName}"] = $spec;
325
			}
326
		}
327
328
		// Add has_one relationships
329
		$hasOne = Config::inst()->get($class, 'has_one', Config::UNINHERITED);
330
		if($hasOne) foreach(array_keys($hasOne) as $field) {
331
332
			// Check if this is a polymorphic relation, in which case the relation
333
			// is a composite field
334
			if($hasOne[$field] === 'DataObject') {
335
				$relationField = DBField::create_field('PolymorphicForeignKey', null, $field);
336
				$relationField->setTable($class);
337
				if($compositeFields = $relationField->compositeDatabaseFields()) {
338
					foreach($compositeFields as $compositeName => $spec) {
339
						$fields["{$field}{$compositeName}"] = $spec;
340
					}
341
				}
342
			} else {
343
				$fields[$field . 'ID'] = 'ForeignKey';
344
			}
345
		}
346
347
		$output = (array) $fields;
348
349
		self::$_cache_custom_database_fields[$class] = $output;
350
351
		return $output;
352
	}
353
354
	/**
355
	 * Returns the field class if the given db field on the class is a composite field.
356
	 * Will check all applicable ancestor classes and aggregate results.
357
	 *
358
	 * @param string $class Class to check
359
	 * @param string $name Field to check
360
	 * @param boolean $aggregated True if parent classes should be checked, or false to limit to this class
361
	 * @return string Class name of composite field if it exists
362
	 */
363
	public static function is_composite_field($class, $name, $aggregated = true) {
364
		$key = $class . '_' . $name . '_' . (string)$aggregated;
365
366
		if(!isset(DataObject::$_cache_is_composite_field[$key])) {
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...
367
			$isComposite = null;
368
369
			if(!isset(DataObject::$_cache_composite_fields[$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...
370
				self::cache_composite_fields($class);
371
			}
372
373
			if(isset(DataObject::$_cache_composite_fields[$class][$name])) {
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...
374
				$isComposite = DataObject::$_cache_composite_fields[$class][$name];
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...
375
			} elseif($aggregated && $class != 'DataObject' && ($parentClass=get_parent_class($class)) != 'DataObject') {
376
				$isComposite = self::is_composite_field($parentClass, $name);
377
			}
378
379
			DataObject::$_cache_is_composite_field[$key] = ($isComposite) ? $isComposite : false;
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...
380
		}
381
382
		return DataObject::$_cache_is_composite_field[$key] ?: null;
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...
383
	}
384
385
	/**
386
	 * Returns a list of all the composite if the given db field on the class is a composite field.
387
	 * Will check all applicable ancestor classes and aggregate results.
388
	 */
389
	public static function composite_fields($class, $aggregated = true) {
390
		if(!isset(DataObject::$_cache_composite_fields[$class])) self::cache_composite_fields($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...
391
392
		$compositeFields = DataObject::$_cache_composite_fields[$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...
393
394
		if($aggregated && $class != 'DataObject' && ($parentClass=get_parent_class($class)) != 'DataObject') {
395
			$compositeFields = array_merge($compositeFields,
396
				self::composite_fields($parentClass));
397
		}
398
399
		return $compositeFields;
400
	}
401
402
	/**
403
	 * Internal cacher for the composite field information
404
	 */
405
	private static function cache_composite_fields($class) {
406
		$compositeFields = array();
407
408
		$fields = Config::inst()->get($class, 'db', Config::UNINHERITED);
409
		if($fields) foreach($fields as $fieldName => $fieldClass) {
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...
410
			if(!is_string($fieldClass)) continue;
411
412
			// Strip off any parameters
413
			$bPos = strpos($fieldClass, '(');
414
			if($bPos !== FALSE) $fieldClass = substr($fieldClass, 0, $bPos);
415
416
			// Test to see if it implements CompositeDBField
417
			if(ClassInfo::classImplements($fieldClass, 'CompositeDBField')) {
418
				$compositeFields[$fieldName] = $fieldClass;
419
			}
420
		}
421
422
		DataObject::$_cache_composite_fields[$class] = $compositeFields;
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...
423
	}
424
425
	/**
426
	 * Construct a new DataObject.
427
	 *
428
	 * @param array|null $record Used internally for rehydrating an object from database content.
429
	 *                           Bypasses setters on this class, and hence should not be used
430
	 *                           for populating data on new records.
431
	 * @param boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods.
432
	 *                             Singletons don't have their defaults set.
433
	 */
434
	public function __construct($record = null, $isSingleton = false, $model = null) {
435
		parent::__construct();
436
437
		// Set the fields data.
438
		if(!$record) {
439
			$record = array(
440
				'ID' => 0,
441
				'ClassName' => get_class($this),
442
				'RecordClassName' => get_class($this)
443
			);
444
		}
445
446
		if(!is_array($record) && !is_a($record, "stdClass")) {
447
			if(is_object($record)) $passed = "an object of type '$record->class'";
448
			else $passed = "The value '$record'";
449
450
			user_error("DataObject::__construct passed $passed.  It's supposed to be passed an array,"
451
				. " taken straight from the database.  Perhaps you should use DataList::create()->First(); instead?",
452
				E_USER_WARNING);
453
			$record = null;
454
		}
455
456
		if(is_a($record, "stdClass")) {
457
			$record = (array)$record;
458
		}
459
460
		// Set $this->record to $record, but ignore NULLs
461
		$this->record = array();
462
		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...
463
			// Ensure that ID is stored as a number and not a string
464
			// To do: this kind of clean-up should be done on all numeric fields, in some relatively
465
			// performant manner
466
			if($v !== null) {
467
				if($k == 'ID' && is_numeric($v)) $this->record[$k] = (int)$v;
468
				else $this->record[$k] = $v;
469
			}
470
		}
471
472
		// Identify fields that should be lazy loaded, but only on existing records
473
		if(!empty($record['ID'])) {
474
			$currentObj = get_class($this);
475
			while($currentObj != 'DataObject') {
476
				$fields = self::custom_database_fields($currentObj);
477
				foreach($fields as $field => $type) {
478
					if(!array_key_exists($field, $record)) $this->record[$field.'_Lazy'] = $currentObj;
479
				}
480
				$currentObj = get_parent_class($currentObj);
481
			}
482
		}
483
484
		$this->original = $this->record;
485
486
		// Keep track of the modification date of all the data sourced to make this page
487
		// From this we create a Last-Modified HTTP header
488
		if(isset($record['LastEdited'])) {
489
			HTTP::register_modification_date($record['LastEdited']);
490
		}
491
492
		// this must be called before populateDefaults(), as field getters on a DataObject
493
		// may call getComponent() and others, which rely on $this->model being set.
494
		$this->model = $model ? $model : DataModel::inst();
495
496
		// Must be called after parent constructor
497
		if(!$isSingleton && (!isset($this->record['ID']) || !$this->record['ID'])) {
498
			$this->populateDefaults();
499
		}
500
501
		// prevent populateDefaults() and setField() from marking overwritten defaults as changed
502
		$this->changed = array();
503
	}
504
505
	/**
506
	 * Set the DataModel
507
	 * @param DataModel $model
508
	 * @return DataObject $this
509
	 */
510
	public function setDataModel(DataModel $model) {
511
		$this->model = $model;
512
		return $this;
513
	}
514
515
	/**
516
	 * Destroy all of this objects dependant objects and local caches.
517
	 * You'll need to call this to get the memory of an object that has components or extensions freed.
518
	 */
519
	public function destroy() {
520
		//$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...
521
		gc_collect_cycles();
522
		$this->flushCache(false);
523
	}
524
525
	/**
526
	 * Create a duplicate of this node.
527
	 * Note: now also duplicates relations.
528
	 *
529
	 * @param $doWrite Perform a write() operation before returning the object.  If this is true, it will create the
530
	 *                 duplicate in the database.
531
	 * @return DataObject A duplicate of this node. The exact type will be the type of this node.
532
	 */
533
	public function duplicate($doWrite = true) {
534
		$className = $this->class;
535
		$map = $this->toMap();
536
		unset($map['Created']);
537
		$clone = new $className( $map, false, $this->model );
538
		$clone->ID = 0;
539
540
		$clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite);
541
		if($doWrite) {
542
			$clone->write();
543
			$this->duplicateManyManyRelations($this, $clone);
544
		}
545
		$clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite);
546
547
		return $clone;
548
	}
549
550
	/**
551
	 * Copies the many_many and belongs_many_many relations from one object to another instance of the name of object
552
	 * The destinationObject must be written to the database already and have an ID. Writing is performed
553
	 * automatically when adding the new relations.
554
	 *
555
	 * @param $sourceObject the source object to duplicate from
556
	 * @param $destinationObject the destination object to populate with the duplicated relations
557
	 * @return DataObject with the new many_many relations copied in
558
	 */
559
	protected function duplicateManyManyRelations($sourceObject, $destinationObject) {
560
		if (!$destinationObject || $destinationObject->ID < 1) {
561
			user_error("Can't duplicate relations for an object that has not been written to the database",
562
				E_USER_ERROR);
563
		}
564
565
		//duplicate complex relations
566
		// DO NOT copy has_many relations, because copying the relation would result in us changing the has_one
567
		// relation on the other side of this relation to point at the copy and no longer the original (being a
568
		// has_one, it can only point at one thing at a time). So, all relations except has_many can and are copied
569
		if ($sourceObject->hasOne()) foreach($sourceObject->hasOne() as $name => $type) {
570
			$this->duplicateRelations($sourceObject, $destinationObject, $name);
571
		}
572
		if ($sourceObject->manyMany()) foreach($sourceObject->manyMany() as $name => $type) {
573
			//many_many include belongs_many_many
574
			$this->duplicateRelations($sourceObject, $destinationObject, $name);
575
		}
576
577
		return $destinationObject;
578
	}
579
580
	/**
581
	 * Helper function to duplicate relations from one object to another
582
	 * @param $sourceObject the source object to duplicate from
583
	 * @param $destinationObject the destination object to populate with the duplicated relations
584
	 * @param $name the name of the relation to duplicate (e.g. members)
585
	 */
586
	private function duplicateRelations($sourceObject, $destinationObject, $name) {
587
		$relations = $sourceObject->$name();
588
		if ($relations) {
589
			if ($relations instanceOf RelationList) {   //many-to-something relation
590
				if ($relations->Count() > 0) {  //with more than one thing it is related to
591
					foreach($relations as $relation) {
592
						$destinationObject->$name()->add($relation);
593
					}
594
				}
595
			} else {    //one-to-one relation
596
				$destinationObject->{"{$name}ID"} = $relations->ID;
597
			}
598
		}
599
	}
600
601
	public function getObsoleteClassName() {
602
		$className = $this->getField("ClassName");
603
		if (!ClassInfo::exists($className)) return $className;
604
	}
605
606
	public function getClassName() {
607
		$className = $this->getField("ClassName");
608
		if (!ClassInfo::exists($className)) return get_class($this);
609
		return $className;
610
	}
611
612
	/**
613
	 * Set the ClassName attribute. {@link $class} is also updated.
614
	 * Warning: This will produce an inconsistent record, as the object
615
	 * instance will not automatically switch to the new subclass.
616
	 * Please use {@link newClassInstance()} for this purpose,
617
	 * or destroy and reinstanciate the record.
618
	 *
619
	 * @param string $className The new ClassName attribute (a subclass of {@link DataObject})
620
	 * @return DataObject $this
621
	 */
622
	public function setClassName($className) {
623
		$className = trim($className);
624
		if(!$className || !is_subclass_of($className, 'DataObject')) return;
625
626
		$this->class = $className;
627
		$this->setField("ClassName", $className);
628
		return $this;
629
	}
630
631
	/**
632
	 * Create a new instance of a different class from this object's record.
633
	 * This is useful when dynamically changing the type of an instance. Specifically,
634
	 * it ensures that the instance of the class is a match for the className of the
635
	 * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName}
636
	 * property manually before calling this method, as it will confuse change detection.
637
	 *
638
	 * If the new class is different to the original class, defaults are populated again
639
	 * because this will only occur automatically on instantiation of a DataObject if
640
	 * there is no record, or the record has no ID. In this case, we do have an ID but
641
	 * we still need to repopulate the defaults.
642
	 *
643
	 * @param string $newClassName The name of the new class
644
	 *
645
	 * @return DataObject The new instance of the new class, The exact type will be of the class name provided.
646
	 */
647
	public function newClassInstance($newClassName) {
648
		$originalClass = $this->ClassName;
649
		$newInstance = new $newClassName(array_merge(
650
			$this->record,
651
			array(
652
				'ClassName' => $originalClass,
653
				'RecordClassName' => $originalClass,
654
			)
655
		), false, $this->model);
656
657
		if($newClassName != $originalClass) {
658
			$newInstance->setClassName($newClassName);
659
			$newInstance->populateDefaults();
660
			$newInstance->forceChange();
661
		}
662
663
		return $newInstance;
664
	}
665
666
	/**
667
	 * Adds methods from the extensions.
668
	 * Called by Object::__construct() once per class.
669
	 */
670
	public function defineMethods() {
671
		parent::defineMethods();
672
673
		// Define the extra db fields - this is only necessary for extensions added in the
674
		// class definition.  Object::add_extension() will call this at definition time for
675
		// those objects, which is a better mechanism.  Perhaps extensions defined inside the
676
		// class def can somehow be applied at definiton time also?
677
		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 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...
678
			if(!$instance->class) {
679
				$class = get_class($instance);
680
				user_error("DataObject::defineMethods(): Please ensure {$class}::__construct() calls"
681
					. " parent::__construct()", E_USER_ERROR);
682
			}
683
		}
684
685
		if($this->class == 'DataObject') return;
686
687
		// Set up accessors for joined items
688
		if($manyMany = $this->manyMany()) {
689
			foreach($manyMany as $relationship => $class) {
690
				$this->addWrapperMethod($relationship, 'getManyManyComponents');
691
			}
692
		}
693
		if($hasMany = $this->hasMany()) {
694
695
			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...
696
				$this->addWrapperMethod($relationship, 'getComponents');
697
			}
698
699
		}
700
		if($hasOne = $this->hasOne()) {
701
			foreach($hasOne as $relationship => $class) {
0 ignored issues
show
Bug introduced by
The expression $hasOne 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...
702
				$this->addWrapperMethod($relationship, 'getComponent');
703
			}
704
		}
705
		if($belongsTo = $this->belongsTo()) foreach(array_keys($belongsTo) as $relationship) {
706
			$this->addWrapperMethod($relationship, 'getComponent');
707
		}
708
	}
709
710
	/**
711
	 * Returns true if this object "exists", i.e., has a sensible value.
712
	 * The default behaviour for a DataObject is to return true if
713
	 * the object exists in the database, you can override this in subclasses.
714
	 *
715
	 * @return boolean true if this object exists
716
	 */
717
	public function exists() {
718
		return (isset($this->record['ID']) && $this->record['ID'] > 0);
719
	}
720
721
	/**
722
	 * Returns TRUE if all values (other than "ID") are
723
	 * considered empty (by weak boolean comparison).
724
	 * Only checks for fields listed in {@link custom_database_fields()}
725
	 *
726
	 * @todo Use DBField->hasValue()
727
	 *
728
	 * @return boolean
729
	 */
730
	public function isEmpty(){
731
		$isEmpty = true;
732
		$customFields = self::custom_database_fields(get_class($this));
733
		if($map = $this->toMap()){
734
			foreach($map as $k=>$v){
735
				// only look at custom fields
736
				if(!array_key_exists($k, $customFields)) continue;
737
738
				$dbObj = ($v instanceof DBField) ? $v : $this->dbObject($k);
739
				$isEmpty = ($isEmpty && !$dbObj->exists());
740
			}
741
		}
742
		return $isEmpty;
743
	}
744
745
	/**
746
	 * Get the user friendly singular name of this DataObject.
747
	 * If the name is not defined (by redefining $singular_name in the subclass),
748
	 * this returns the class name.
749
	 *
750
	 * @return string User friendly singular name of this DataObject
751
	 */
752
	public function singular_name() {
753
		if(!$name = $this->stat('singular_name')) {
754
			$name = ucwords(trim(strtolower(preg_replace('/_?([A-Z])/', ' $1', $this->class))));
755
		}
756
757
		return $name;
758
	}
759
760
	/**
761
	 * Get the translated user friendly singular name of this DataObject
762
	 * same as singular_name() but runs it through the translating function
763
	 *
764
	 * Translating string is in the form:
765
	 *     $this->class.SINGULARNAME
766
	 * Example:
767
	 *     Page.SINGULARNAME
768
	 *
769
	 * @return string User friendly translated singular name of this DataObject
770
	 */
771
	public function i18n_singular_name() {
772
		return _t($this->class.'.SINGULARNAME', $this->singular_name());
773
	}
774
775
	/**
776
	 * Get the user friendly plural name of this DataObject
777
	 * If the name is not defined (by renaming $plural_name in the subclass),
778
	 * this returns a pluralised version of the class name.
779
	 *
780
	 * @return string User friendly plural name of this DataObject
781
	 */
782
	public function plural_name() {
783
		if($name = $this->stat('plural_name')) {
784
			return $name;
785
		} else {
786
			$name = $this->singular_name();
787
			//if the penultimate character is not a vowel, replace "y" with "ies"
788
			if (preg_match('/[^aeiou]y$/i', $name)) {
789
				$name = substr($name,0,-1) . 'ie';
790
			}
791
			return ucfirst($name . 's');
792
		}
793
	}
794
795
	/**
796
	 * Get the translated user friendly plural name of this DataObject
797
	 * Same as plural_name but runs it through the translation function
798
	 * Translation string is in the form:
799
	 *      $this->class.PLURALNAME
800
	 * Example:
801
	 *      Page.PLURALNAME
802
	 *
803
	 * @return string User friendly translated plural name of this DataObject
804
	 */
805
	public function i18n_plural_name()
806
	{
807
		$name = $this->plural_name();
808
		return _t($this->class.'.PLURALNAME', $name);
809
	}
810
811
	/**
812
	 * Standard implementation of a title/label for a specific
813
	 * record. Tries to find properties 'Title' or 'Name',
814
	 * and falls back to the 'ID'. Useful to provide
815
	 * user-friendly identification of a record, e.g. in errormessages
816
	 * or UI-selections.
817
	 *
818
	 * Overload this method to have a more specialized implementation,
819
	 * e.g. for an Address record this could be:
820
	 * <code>
821
	 * function getTitle() {
822
	 *   return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
823
	 * }
824
	 * </code>
825
	 *
826
	 * @return string
827
	 */
828
	public function getTitle() {
829
		if($this->hasDatabaseField('Title')) return $this->getField('Title');
830
		if($this->hasDatabaseField('Name')) return $this->getField('Name');
831
832
		return "#{$this->ID}";
833
	}
834
835
	/**
836
	 * Returns the associated database record - in this case, the object itself.
837
	 * This is included so that you can call $dataOrController->data() and get a DataObject all the time.
838
	 *
839
	 * @return DataObject Associated database record
840
	 */
841
	public function data() {
842
		return $this;
843
	}
844
845
	/**
846
	 * Convert this object to a map.
847
	 *
848
	 * @return array The data as a map.
849
	 */
850
	public function toMap() {
851
		$this->loadLazyFields();
852
		return $this->record;
853
	}
854
855
	/**
856
	 * Return all currently fetched database fields.
857
	 *
858
	 * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
859
	 * Obviously, this makes it a lot faster.
860
	 *
861
	 * @return array The data as a map.
862
	 */
863
	public function getQueriedDatabaseFields() {
864
		return $this->record;
865
	}
866
867
	/**
868
	 * Update a number of fields on this object, given a map of the desired changes.
869
	 *
870
	 * The field names can be simple names, or you can use a dot syntax to access $has_one relations.
871
	 * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
872
	 *
873
	 * update() doesn't write the main object, but if you use the dot syntax, it will write()
874
	 * the related objects that it alters.
875
	 *
876
	 * @param array $data A map of field name to data values to update.
877
	 * @return DataObject $this
878
	 */
879
	public function update($data) {
880
		foreach($data as $k => $v) {
881
			// Implement dot syntax for updates
882
			if(strpos($k,'.') !== false) {
883
				$relations = explode('.', $k);
884
				$fieldName = array_pop($relations);
885
				$relObj = $this;
886
				foreach($relations as $i=>$relation) {
887
					// no support for has_many or many_many relationships,
888
					// as the updater wouldn't know which object to write to (or create)
889
					if($relObj->$relation() instanceof DataObject) {
890
						$parentObj = $relObj;
891
						$relObj = $relObj->$relation();
892
						// If the intermediate relationship objects have been created, then write them
893
						if($i<sizeof($relation)-1 && !$relObj->ID || (!$relObj->ID && $parentObj != $this)) {
894
							$relObj->write();
895
							$relatedFieldName = $relation."ID";
896
							$parentObj->$relatedFieldName = $relObj->ID;
897
							$parentObj->write();
898
						}
899
					} else {
900
						user_error(
901
							"DataObject::update(): Can't traverse relationship '$relation'," .
902
							"it has to be a has_one relationship or return a single DataObject",
903
							E_USER_NOTICE
904
						);
905
						// unset relation object so we don't write properties to the wrong object
906
						unset($relObj);
907
						break;
908
					}
909
				}
910
911
				if($relObj) {
912
					$relObj->$fieldName = $v;
913
					$relObj->write();
914
					$relatedFieldName = $relation."ID";
0 ignored issues
show
Bug introduced by
The variable $relation seems to be defined by a foreach iteration on line 886. 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...
915
					$this->$relatedFieldName = $relObj->ID;
916
					$relObj->flushCache();
917
				} else {
918
					user_error("Couldn't follow dot syntax '$k' on '$this->class' object", E_USER_WARNING);
919
				}
920
			} else {
921
				$this->$k = $v;
922
			}
923
		}
924
		return $this;
925
	}
926
927
	/**
928
	 * Pass changes as a map, and try to
929
	 * get automatic casting for these fields.
930
	 * Doesn't write to the database. To write the data,
931
	 * use the write() method.
932
	 *
933
	 * @param array $data A map of field name to data values to update.
934
	 * @return DataObject $this
935
	 */
936
	public function castedUpdate($data) {
937
		foreach($data as $k => $v) {
938
			$this->setCastedField($k,$v);
939
		}
940
		return $this;
941
	}
942
943
	/**
944
	 * Merges data and relations from another object of same class,
945
	 * without conflict resolution. Allows to specify which
946
	 * dataset takes priority in case its not empty.
947
	 * has_one-relations are just transferred with priority 'right'.
948
	 * has_many and many_many-relations are added regardless of priority.
949
	 *
950
	 * Caution: has_many/many_many relations are moved rather than duplicated,
951
	 * meaning they are not connected to the merged object any longer.
952
	 * Caution: Just saves updated has_many/many_many relations to the database,
953
	 * doesn't write the updated object itself (just writes the object-properties).
954
	 * Caution: Does not delete the merged object.
955
	 * Caution: Does now overwrite Created date on the original object.
956
	 *
957
	 * @param $obj DataObject
958
	 * @param $priority String left|right Determines who wins in case of a conflict (optional)
959
	 * @param $includeRelations Boolean Merge any existing relations (optional)
960
	 * @param $overwriteWithEmpty Boolean Overwrite existing left values with empty right values.
961
	 *                            Only applicable with $priority='right'. (optional)
962
	 * @return Boolean
963
	 */
964
	public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false) {
965
		$leftObj = $this;
966
967
		if($leftObj->ClassName != $rightObj->ClassName) {
968
			// we can't merge similiar subclasses because they might have additional relations
969
			user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
970
			(expected '{$leftObj->ClassName}').", E_USER_WARNING);
971
			return false;
972
		}
973
974
		if(!$rightObj->ID) {
975
			user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
976
				to make sure all relations are transferred properly.').", E_USER_WARNING);
977
			return false;
978
		}
979
980
		// makes sure we don't merge data like ID or ClassName
981
		$leftData = $leftObj->inheritedDatabaseFields();
982
		$rightData = $rightObj->inheritedDatabaseFields();
983
984
		foreach($rightData as $key=>$rightVal) {
985
			// don't merge conflicting values if priority is 'left'
986
			if($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) continue;
987
988
			// don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
989
			if($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) continue;
990
991
			// TODO remove redundant merge of has_one fields
992
			$leftObj->{$key} = $rightObj->{$key};
993
		}
994
995
		// merge relations
996
		if($includeRelations) {
997
			if($manyMany = $this->manyMany()) {
998
				foreach($manyMany as $relationship => $class) {
999
					$leftComponents = $leftObj->getManyManyComponents($relationship);
1000
					$rightComponents = $rightObj->getManyManyComponents($relationship);
1001
					if($rightComponents && $rightComponents->exists()) {
1002
						$leftComponents->addMany($rightComponents->column('ID'));
1003
					}
1004
					$leftComponents->write();
1005
				}
1006
			}
1007
1008
			if($hasMany = $this->hasMany()) {
1009
				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...
1010
					$leftComponents = $leftObj->getComponents($relationship);
1011
					$rightComponents = $rightObj->getComponents($relationship);
1012
					if($rightComponents && $rightComponents->exists()) {
1013
						$leftComponents->addMany($rightComponents->column('ID'));
1014
					}
1015
					$leftComponents->write();
1016
				}
1017
1018
			}
1019
1020
			if($hasOne = $this->hasOne()) {
1021
				foreach($hasOne as $relationship => $class) {
0 ignored issues
show
Bug introduced by
The expression $hasOne 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...
1022
					$leftComponent = $leftObj->getComponent($relationship);
1023
					$rightComponent = $rightObj->getComponent($relationship);
1024
					if($leftComponent->exists() && $rightComponent->exists() && $priority == 'right') {
1025
						$leftObj->{$relationship . 'ID'} = $rightObj->{$relationship . 'ID'};
1026
					}
1027
				}
1028
			}
1029
		}
1030
1031
		return true;
1032
	}
1033
1034
	/**
1035
	 * Forces the record to think that all its data has changed.
1036
	 * Doesn't write to the database. Only sets fields as changed
1037
	 * if they are not already marked as changed.
1038
	 *
1039
	 * @return $this
1040
	 */
1041
	public function forceChange() {
1042
		// Ensure lazy fields loaded
1043
		$this->loadLazyFields();
1044
1045
		// $this->record might not contain the blank values so we loop on $this->inheritedDatabaseFields() as well
1046
		$fieldNames = array_unique(array_merge(
1047
			array_keys($this->record),
1048
			array_keys($this->inheritedDatabaseFields())
1049
		));
1050
1051
		foreach($fieldNames as $fieldName) {
1052
			if(!isset($this->changed[$fieldName])) $this->changed[$fieldName] = self::CHANGE_STRICT;
1053
			// Populate the null values in record so that they actually get written
1054
			if(!isset($this->record[$fieldName])) $this->record[$fieldName] = null;
1055
		}
1056
1057
		// @todo Find better way to allow versioned to write a new version after forceChange
1058
		if($this->isChanged('Version')) unset($this->changed['Version']);
1059
		return $this;
1060
	}
1061
1062
	/**
1063
	 * Validate the current object.
1064
	 *
1065
	 * By default, there is no validation - objects are always valid!  However, you can overload this method in your
1066
	 * DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
1067
	 *
1068
	 * Invalid objects won't be able to be written - a warning will be thrown and no write will occur.  onBeforeWrite()
1069
	 * and onAfterWrite() won't get called either.
1070
	 *
1071
	 * It is expected that you call validate() in your own application to test that an object is valid before
1072
	 * attempting a write, and respond appropriately if it isn't.
1073
	 *
1074
	 * @see {@link ValidationResult}
1075
	 * @return ValidationResult
1076
	 */
1077
	protected function validate() {
1078
		$result = ValidationResult::create();
1079
		$this->extend('validate', $result);
1080
		return $result;
1081
	}
1082
1083
	/**
1084
	 * Public accessor for {@see DataObject::validate()}
1085
	 *
1086
	 * @return ValidationResult
1087
	 */
1088
	public function doValidate() {
1089
		// validate will be public in 4.0
1090
		return $this->validate();
1091
	}
1092
1093
	/**
1094
	 * Event handler called before writing to the database.
1095
	 * You can overload this to clean up or otherwise process data before writing it to the
1096
	 * database.  Don't forget to call parent::onBeforeWrite(), though!
1097
	 *
1098
	 * This called after {@link $this->validate()}, so you can be sure that your data is valid.
1099
	 *
1100
	 * @uses DataExtension->onBeforeWrite()
1101
	 */
1102
	protected function onBeforeWrite() {
1103
		$this->brokenOnWrite = false;
1104
1105
		$dummy = null;
1106
		$this->extend('onBeforeWrite', $dummy);
1107
	}
1108
1109
	/**
1110
	 * Event handler called after writing to the database.
1111
	 * You can overload this to act upon changes made to the data after it is written.
1112
	 * $this->changed will have a record
1113
	 * database.  Don't forget to call parent::onAfterWrite(), though!
1114
	 *
1115
	 * @uses DataExtension->onAfterWrite()
1116
	 */
1117
	protected function onAfterWrite() {
1118
		$dummy = null;
1119
		$this->extend('onAfterWrite', $dummy);
1120
	}
1121
1122
	/**
1123
	 * Event handler called before deleting from the database.
1124
	 * You can overload this to clean up or otherwise process data before delete this
1125
	 * record.  Don't forget to call parent::onBeforeDelete(), though!
1126
	 *
1127
	 * @uses DataExtension->onBeforeDelete()
1128
	 */
1129
	protected function onBeforeDelete() {
1130
		$this->brokenOnDelete = false;
1131
1132
		$dummy = null;
1133
		$this->extend('onBeforeDelete', $dummy);
1134
	}
1135
1136
	protected function onAfterDelete() {
1137
		$this->extend('onAfterDelete');
1138
	}
1139
1140
	/**
1141
	 * Load the default values in from the self::$defaults array.
1142
	 * Will traverse the defaults of the current class and all its parent classes.
1143
	 * Called by the constructor when creating new records.
1144
	 *
1145
	 * @uses DataExtension->populateDefaults()
1146
	 * @return DataObject $this
1147
	 */
1148
	public function populateDefaults() {
1149
		$classes = array_reverse(ClassInfo::ancestry($this));
1150
1151
		foreach($classes as $class) {
1152
			$defaults = Config::inst()->get($class, 'defaults', Config::UNINHERITED);
1153
1154
			if($defaults && !is_array($defaults)) {
1155
				user_error("Bad '$this->class' defaults given: " . var_export($defaults, true),
1156
					E_USER_WARNING);
1157
				$defaults = null;
1158
			}
1159
1160
			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...
1161
				// SRM 2007-03-06: Stricter check
1162
				if(!isset($this->$fieldName) || $this->$fieldName === null) {
1163
					$this->$fieldName = $fieldValue;
1164
				}
1165
				// Set many-many defaults with an array of ids
1166
				if(is_array($fieldValue) && $this->manyManyComponent($fieldName)) {
1167
					$manyManyJoin = $this->$fieldName();
1168
					$manyManyJoin->setByIdList($fieldValue);
1169
				}
1170
			}
1171
			if($class == 'DataObject') {
1172
				break;
1173
			}
1174
		}
1175
1176
		$this->extend('populateDefaults');
1177
		return $this;
1178
	}
1179
1180
	/**
1181
	 * Determine validation of this object prior to write
1182
	 *
1183
	 * @return ValidationException Exception generated by this write, or null if valid
1184
	 */
1185
	protected function validateWrite() {
1186
		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...
1187
			return new ValidationException(
1188
				"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...
1189
				"you need to change the ClassName before you can write it",
1190
				E_USER_WARNING
1191
			);
1192
		}
1193
1194
		if(Config::inst()->get('DataObject', 'validation_enabled')) {
1195
			$result = $this->validate();
1196
			if (!$result->valid()) {
1197
				return new ValidationException(
1198
					$result,
1199
					$result->message(),
1200
					E_USER_WARNING
1201
				);
1202
			}
1203
		}
1204
	}
1205
1206
	/**
1207
	 * Prepare an object prior to write
1208
	 *
1209
	 * @throws ValidationException
1210
	 */
1211
	protected function preWrite() {
1212
		// Validate this object
1213
		if($writeException = $this->validateWrite()) {
1214
			// Used by DODs to clean up after themselves, eg, Versioned
1215
			$this->invokeWithExtensions('onAfterSkippedWrite');
1216
			throw $writeException;
1217
		}
1218
1219
		// Check onBeforeWrite
1220
		$this->brokenOnWrite = true;
1221
		$this->onBeforeWrite();
1222
		if($this->brokenOnWrite) {
1223
			user_error("$this->class has a broken onBeforeWrite() function."
1224
				. " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
1225
		}
1226
	}
1227
1228
	/**
1229
	 * Detects and updates all changes made to this object
1230
	 *
1231
	 * @param bool $forceChanges If set to true, force all fields to be treated as changed
1232
	 * @return bool True if any changes are detected
1233
	 */
1234
	protected function updateChanges($forceChanges = false)
1235
	{
1236
		if($forceChanges) {
1237
			// Force changes, but only for loaded fields
1238
			foreach($this->record as $field => $value) {
1239
				$this->changed[$field] = static::CHANGE_VALUE;
1240
			}
1241
			return true;
1242
		}
1243
		return $this->isChanged();
1244
	}
1245
1246
	/**
1247
	 * Writes a subset of changes for a specific table to the given manipulation
1248
	 *
1249
	 * @param string $baseTable Base table
1250
	 * @param string $now Timestamp to use for the current time
1251
	 * @param bool $isNewRecord Whether this should be treated as a new record write
1252
	 * @param array $manipulation Manipulation to write to
1253
	 * @param string $class Table and Class to select and write to
1254
	 */
1255
	protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class) {
1256
		$manipulation[$class] = array();
1257
1258
		// Extract records for this table
1259
		foreach($this->record as $fieldName => $fieldValue) {
1260
1261
			// Check if this record pertains to this table, and
1262
			// we're not attempting to reset the BaseTable->ID
1263
			if(	empty($this->changed[$fieldName])
1264
				|| ($class === $baseTable && $fieldName === 'ID')
1265
				|| (!self::has_own_table_database_field($class, $fieldName)
1266
					&& !self::is_composite_field($class, $fieldName, false))
1267
			) {
1268
				continue;
1269
			}
1270
1271
1272
			// if database column doesn't correlate to a DBField instance...
1273
			$fieldObj = $this->dbObject($fieldName);
1274
			if(!$fieldObj) {
1275
				$fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
1276
			}
1277
1278
			// Ensure DBField is repopulated and written to the manipulation
1279
			$fieldObj->setValue($fieldValue, $this->record);
1280
			$fieldObj->writeToManipulation($manipulation[$class]);
1281
		}
1282
1283
		// Ensure update of Created and LastEdited columns
1284
		if($baseTable === $class) {
1285
			$manipulation[$class]['fields']['LastEdited'] = $now;
1286
			if($isNewRecord) {
1287
				$manipulation[$class]['fields']['Created']
1288
					= empty($this->record['Created'])
1289
						? $now
1290
						: $this->record['Created'];
1291
				$manipulation[$class]['fields']['ClassName'] = $this->class;
1292
			}
1293
		}
1294
1295
		// Inserts done one the base table are performed in another step, so the manipulation should instead
1296
		// attempt an update, as though it were a normal update.
1297
		$manipulation[$class]['command'] = $isNewRecord ? 'insert' : 'update';
1298
		$manipulation[$class]['id'] = $this->record['ID'];
1299
	}
1300
1301
	/**
1302
	 * Ensures that a blank base record exists with the basic fixed fields for this dataobject
1303
	 *
1304
	 * Does nothing if an ID is already assigned for this record
1305
	 *
1306
	 * @param string $baseTable Base table
1307
	 * @param string $now Timestamp to use for the current time
1308
	 */
1309
	protected function writeBaseRecord($baseTable, $now) {
1310
		// Generate new ID if not specified
1311
		if($this->isInDB()) return;
1312
1313
		// Perform an insert on the base table
1314
		$insert = new SQLInsert('"'.$baseTable.'"');
1315
		$insert
1316
			->assign('"Created"', $now)
1317
			->execute();
1318
		$this->changed['ID'] = self::CHANGE_VALUE;
1319
		$this->record['ID'] = DB::get_generated_id($baseTable);
1320
	}
1321
1322
	/**
1323
	 * Generate and write the database manipulation for all changed fields
1324
	 *
1325
	 * @param string $baseTable Base table
1326
	 * @param string $now Timestamp to use for the current time
1327
	 * @param bool $isNewRecord If this is a new record
1328
	 */
1329
	protected function writeManipulation($baseTable, $now, $isNewRecord) {
1330
		// Generate database manipulations for each class
1331
		$manipulation = array();
1332
		foreach($this->getClassAncestry() as $class) {
1333
			if(self::has_own_table($class)) {
1334
				$this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
1335
			}
1336
		}
1337
1338
		// Allow extensions to extend this manipulation
1339
		$this->extend('augmentWrite', $manipulation);
1340
1341
		// New records have their insert into the base data table done first, so that they can pass the
1342
		// generated ID on to the rest of the manipulation
1343
		if($isNewRecord) {
1344
			$manipulation[$baseTable]['command'] = 'update';
1345
		}
1346
1347
		// Perform the manipulation
1348
		DB::manipulate($manipulation);
1349
	}
1350
1351
	/**
1352
	 * Writes all changes to this object to the database.
1353
	 *  - It will insert a record whenever ID isn't set, otherwise update.
1354
	 *  - All relevant tables will be updated.
1355
	 *  - $this->onBeforeWrite() gets called beforehand.
1356
	 *  - Extensions such as Versioned will ammend the database-write to ensure that a version is saved.
1357
	 *
1358
	 *  @uses DataExtension->augmentWrite()
1359
	 *
1360
	 * @param boolean $showDebug Show debugging information
1361
	 * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
1362
	 * @param boolean $forceWrite Write to database even if there are no changes
1363
	 * @param boolean $writeComponents Call write() on all associated component instances which were previously
1364
	 *                                 retrieved through {@link getComponent()}, {@link getComponents()} or
1365
	 *                                 {@link getManyManyComponents()} (Default: false)
1366
	 * @return int The ID of the record
1367
	 * @throws ValidationException Exception that can be caught and handled by the calling function
1368
	 */
1369
	public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
1370
		$now = SS_Datetime::now()->Rfc2822();
1371
1372
		// Execute pre-write tasks
1373
		$this->preWrite();
1374
1375
		// Check if we are doing an update or an insert
1376
		$isNewRecord = !$this->isInDB() || $forceInsert;
1377
1378
		// Check changes exist, abort if there are none
1379
		$hasChanges = $this->updateChanges($isNewRecord);
1380
		if($hasChanges || $forceWrite || $isNewRecord) {
1381
1382
			// Ensure Created and LastEdited are populated
1383
			if(!isset($this->record['Created'])) {
1384
				$this->record['Created'] = $now;
1385
			}
1386
			$this->record['LastEdited'] = $now;
1387
			// New records have their insert into the base data table done first, so that they can pass the
1388
			// generated primary key on to the rest of the manipulation
1389
			$baseTable = ClassInfo::baseDataClass($this->class);
1390
			$this->writeBaseRecord($baseTable, $now);
1391
1392
			// Write the DB manipulation for all changed fields
1393
			$this->writeManipulation($baseTable, $now, $isNewRecord);
1394
1395
			// If there's any relations that couldn't be saved before, save them now (we have an ID here)
1396
			$this->writeRelations();
1397
			$this->onAfterWrite();
1398
			$this->changed = array();
1399
		} else {
1400
			if($showDebug) Debug::message("no changes for DataObject");
1401
1402
			// Used by DODs to clean up after themselves, eg, Versioned
1403
			$this->invokeWithExtensions('onAfterSkippedWrite');
1404
		}
1405
1406
		// Write relations as necessary
1407
		if($writeComponents) $this->writeComponents(true);
1408
1409
		// Clears the cache for this object so get_one returns the correct object.
1410
		$this->flushCache();
1411
1412
		return $this->record['ID'];
1413
	}
1414
1415
	/**
1416
	 * Writes cached relation lists to the database, if possible
1417
	 */
1418
	public function writeRelations() {
1419
		if(!$this->isInDB()) return;
1420
1421
		// If there's any relations that couldn't be saved before, save them now (we have an ID here)
1422
		if($this->unsavedRelations) {
1423
			foreach($this->unsavedRelations as $name => $list) {
1424
				$list->changeToList($this->$name());
1425
			}
1426
			$this->unsavedRelations = array();
1427
		}
1428
	}
1429
1430
	/**
1431
	 * Write the cached components to the database. Cached components could refer to two different instances of the
1432
	 * same record.
1433
	 *
1434
	 * @param $recursive Recursively write components
1435
	 * @return DataObject $this
1436
	 */
1437
	public function writeComponents($recursive = false) {
1438
		if(!$this->components) return $this;
1439
1440
		foreach($this->components as $component) {
1441
			$component->write(false, false, false, $recursive);
1442
		}
1443
		return $this;
1444
	}
1445
1446
	/**
1447
	 * Delete this data object.
1448
	 * $this->onBeforeDelete() gets called.
1449
	 * Note that in Versioned objects, both Stage and Live will be deleted.
1450
	 *  @uses DataExtension->augmentSQL()
1451
	 */
1452
	public function delete() {
1453
		$this->brokenOnDelete = true;
1454
		$this->onBeforeDelete();
1455
		if($this->brokenOnDelete) {
1456
			user_error("$this->class has a broken onBeforeDelete() function."
1457
				. " Make sure that you call parent::onBeforeDelete().", E_USER_ERROR);
1458
		}
1459
1460
		// Deleting a record without an ID shouldn't do anything
1461
		if(!$this->ID) throw new LogicException("DataObject::delete() called on a DataObject without an ID");
1462
1463
		// TODO: This is quite ugly.  To improve:
1464
		//  - move the details of the delete code in the DataQuery system
1465
		//  - update the code to just delete the base table, and rely on cascading deletes in the DB to do the rest
1466
		//    obviously, that means getting requireTable() to configure cascading deletes ;-)
1467
		$srcQuery = DataList::create($this->class, $this->model)->where("ID = $this->ID")->dataQuery()->query();
1468
		foreach($srcQuery->queriedTables() as $table) {
1469
			$delete = new SQLDelete("\"$table\"", array('"ID"' => $this->ID));
1470
			$delete->execute();
1471
		}
1472
		// Remove this item out of any caches
1473
		$this->flushCache();
1474
1475
		$this->onAfterDelete();
1476
1477
		$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...
1478
		$this->ID = 0;
1479
	}
1480
1481
	/**
1482
	 * Delete the record with the given ID.
1483
	 *
1484
	 * @param string $className The class name of the record to be deleted
1485
	 * @param int $id ID of record to be deleted
1486
	 */
1487
	public static function delete_by_id($className, $id) {
1488
		$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...
1489
		if($obj) {
1490
			$obj->delete();
1491
		} else {
1492
			user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
1493
		}
1494
	}
1495
1496
	/**
1497
	 * Get the class ancestry, including the current class name.
1498
	 * The ancestry will be returned as an array of class names, where the 0th element
1499
	 * will be the class that inherits directly from DataObject, and the last element
1500
	 * will be the current class.
1501
	 *
1502
	 * @return array Class ancestry
1503
	 */
1504
	public function getClassAncestry() {
1505
		if(!isset(DataObject::$_cache_get_class_ancestry[$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...
1506
			DataObject::$_cache_get_class_ancestry[$this->class] = array($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...
1507
			while(($class=get_parent_class(DataObject::$_cache_get_class_ancestry[$this->class][0])) != "DataObject") {
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...
1508
				array_unshift(DataObject::$_cache_get_class_ancestry[$this->class], $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...
1509
			}
1510
		}
1511
		return DataObject::$_cache_get_class_ancestry[$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...
1512
	}
1513
1514
	/**
1515
	 * Return a component object from a one to one relationship, as a DataObject.
1516
	 * If no component is available, an 'empty component' will be returned for
1517
	 * non-polymorphic relations, or for polymorphic relations with a class set.
1518
	 *
1519
	 * @param string $componentName Name of the component
1520
	 *
1521
	 * @return DataObject The component object. It's exact type will be that of the component.
1522
	 */
1523
	public function getComponent($componentName) {
1524
		if(isset($this->components[$componentName])) {
1525
			return $this->components[$componentName];
1526
		}
1527
1528
		if($class = $this->hasOneComponent($componentName)) {
1529
			$joinField = $componentName . 'ID';
1530
			$joinID    = $this->getField($joinField);
1531
1532
			// Extract class name for polymorphic relations
1533
			if($class === 'DataObject') {
1534
				$class = $this->getField($componentName . 'Class');
1535
				if(empty($class)) return null;
1536
			}
1537
1538
			if($joinID) {
1539
				$component = DataObject::get_by_id($class, $joinID);
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...
1540
			}
1541
1542
			if(empty($component)) {
1543
				$component = $this->model->$class->newObject();
1544
			}
1545
		} elseif($class = $this->belongsToComponent($componentName)) {
1546
1547
			$joinField = $this->getRemoteJoinField($componentName, 'belongs_to', $polymorphic);
1548
			$joinID    = $this->ID;
1549
1550
			if($joinID) {
1551
1552
				$filter = $polymorphic
1553
					? array(
1554
						"{$joinField}ID" => $joinID,
1555
						"{$joinField}Class" => $this->class
1556
					)
1557
					: array(
1558
						$joinField => $joinID
1559
					);
1560
				$component = DataObject::get($class)->filter($filter)->first();
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...
1561
			}
1562
1563
			if(empty($component)) {
1564
				$component = $this->model->$class->newObject();
1565
				if($polymorphic) {
1566
					$component->{$joinField.'ID'} = $this->ID;
1567
					$component->{$joinField.'Class'} = $this->class;
1568
				} else {
1569
					$component->$joinField = $this->ID;
1570
				}
1571
			}
1572
		} else {
1573
			throw new Exception("DataObject->getComponent(): Could not find component '$componentName'.");
1574
		}
1575
1576
		$this->components[$componentName] = $component;
1577
		return $component;
1578
	}
1579
1580
	/**
1581
	 * Returns a one-to-many relation as a HasManyList
1582
	 *
1583
	 * @param string $componentName Name of the component
1584
	 * @param string|null $filter Deprecated. A filter to be inserted into the WHERE clause
1585
	 * @param string|null|array $sort Deprecated. A sort expression to be inserted into the ORDER BY clause. If omitted,
1586
	 *                                the static field $default_sort on the component class will be used.
1587
	 * @param string $join Deprecated, use leftJoin($table, $joinClause) instead
1588
	 * @param string|null|array $limit Deprecated. A limit expression to be inserted into the LIMIT clause
1589
	 *
1590
	 * @return HasManyList The components of the one-to-many relationship.
1591
	 */
1592
	public function getComponents($componentName, $filter = null, $sort = null, $join = null, $limit = null) {
1593
		$result = null;
1594
1595
		if(!$componentClass = $this->hasManyComponent($componentName)) {
1596
			user_error("DataObject::getComponents(): Unknown 1-to-many component '$componentName'"
1597
				. " on class '$this->class'", E_USER_ERROR);
1598
		}
1599
1600
		if($join) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $join 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...
1601
			throw new \InvalidArgumentException(
1602
				'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
1603
			);
1604
		}
1605
1606
		if($filter !== null || $sort !== null || $limit !== null) {
1607
			Deprecation::notice('4.0', 'The $filter, $sort and $limit parameters for DataObject::getComponents()
1608
				have been deprecated. Please manipluate the returned list directly.', Deprecation::SCOPE_GLOBAL);
1609
		}
1610
1611
		// If we haven't been written yet, we can't save these relations, so use a list that handles this case
1612
		if(!$this->ID) {
1613
			if(!isset($this->unsavedRelations[$componentName])) {
1614
				$this->unsavedRelations[$componentName] =
1615
					new UnsavedRelationList($this->class, $componentName, $componentClass);
0 ignored issues
show
Security Bug introduced by
It seems like $componentClass defined by $this->hasManyComponent($componentName) on line 1595 can also be of type false; however, UnsavedRelationList::__construct() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1616
			}
1617
			return $this->unsavedRelations[$componentName];
1618
		}
1619
1620
		// Determine type and nature of foreign relation
1621
		$joinField = $this->getRemoteJoinField($componentName, 'has_many', $polymorphic);
1622
		if($polymorphic) {
1623
			$result = PolymorphicHasManyList::create($componentClass, $joinField, $this->class);
1624
		} else {
1625
			$result = HasManyList::create($componentClass, $joinField);
1626
		}
1627
1628
		if($this->model) $result->setDataModel($this->model);
1629
1630
		return $result
1631
			->forForeignID($this->ID)
1632
			->where($filter)
1633
			->limit($limit)
1634
			->sort($sort);
1635
	}
1636
1637
	/**
1638
	 * @deprecated
1639
	 */
1640
	public function getComponentsQuery($componentName, $filter = "", $sort = "", $join = "", $limit = "") {
1641
		Deprecation::notice('4.0', "Use getComponents to get a filtered DataList for an object's relation");
1642
		return $this->getComponents($componentName, $filter, $sort, $join, $limit);
1643
	}
1644
1645
	/**
1646
	 * Find the foreign class of a relation on this DataObject, regardless of the relation type.
1647
	 *
1648
	 * @param $relationName Relation name.
1649
	 * @return string Class name, or null if not found.
1650
	 */
1651
	public function getRelationClass($relationName) {
1652
		// Go through all relationship configuration fields.
1653
		$candidates = array_merge(
1654
			($relations = Config::inst()->get($this->class, 'has_one')) ? $relations : array(),
1655
			($relations = Config::inst()->get($this->class, 'has_many')) ? $relations : array(),
1656
			($relations = Config::inst()->get($this->class, 'many_many')) ? $relations : array(),
1657
			($relations = Config::inst()->get($this->class, 'belongs_many_many')) ? $relations : array(),
1658
			($relations = Config::inst()->get($this->class, 'belongs_to')) ? $relations : array()
1659
		);
1660
1661
		if (isset($candidates[$relationName])) {
1662
			$remoteClass = $candidates[$relationName];
1663
1664
			// If dot notation is present, extract just the first part that contains the class.
1665
			if(($fieldPos = strpos($remoteClass, '.'))!==false) {
1666
				return substr($remoteClass, 0, $fieldPos);
1667
			}
1668
1669
			// Otherwise just return the class
1670
			return $remoteClass;
1671
		}
1672
1673
		return null;
1674
	}
1675
1676
	/**
1677
	 * Tries to find the database key on another object that is used to store a
1678
	 * relationship to this class. If no join field can be found it defaults to 'ParentID'.
1679
	 *
1680
	 * If the remote field is polymorphic then $polymorphic is set to true, and the return value
1681
	 * is in the form 'Relation' instead of 'RelationID', referencing the composite DBField.
1682
	 *
1683
	 * @param string $component Name of the relation on the current object pointing to the
1684
	 * remote object.
1685
	 * @param string $type the join type - either 'has_many' or 'belongs_to'
1686
	 * @param boolean $polymorphic Flag set to true if the remote join field is polymorphic.
1687
	 * @return string
1688
	 */
1689
	public function getRemoteJoinField($component, $type = 'has_many', &$polymorphic = false) {
1690
		// Extract relation from current object
1691
		if($type === 'has_many') {
1692
			$remoteClass = $this->hasManyComponent($component, false);
1693
		} else {
1694
			$remoteClass = $this->belongsToComponent($component, false);
1695
		}
1696
1697
		if(empty($remoteClass)) {
1698
			throw new Exception("Unknown $type component '$component' on class '$this->class'");
1699
		}
1700
		if(!ClassInfo::exists(strtok($remoteClass, '.'))) {
1701
			throw new Exception(
1702
				"Class '$remoteClass' not found, but used in $type component '$component' on class '$this->class'"
1703
			);
1704
		}
1705
1706
		// If presented with an explicit field name (using dot notation) then extract field name
1707
		$remoteField = null;
1708
		if(strpos($remoteClass, '.') !== false) {
1709
			list($remoteClass, $remoteField) = explode('.', $remoteClass);
1710
		}
1711
1712
		// Reference remote has_one to check against
1713
		$remoteRelations = Config::inst()->get($remoteClass, 'has_one');
1714
1715
		// Without an explicit field name, attempt to match the first remote field
1716
		// with the same type as the current class
1717
		if(empty($remoteField)) {
1718
			// look for remote has_one joins on this class or any parent classes
1719
			$remoteRelationsMap = array_flip($remoteRelations);
1720
			foreach(array_reverse(ClassInfo::ancestry($this)) as $class) {
1721
				if(array_key_exists($class, $remoteRelationsMap)) {
1722
					$remoteField = $remoteRelationsMap[$class];
1723
					break;
1724
				}
1725
			}
1726
		}
1727
1728
		// In case of an indeterminate remote field show an error
1729
		if(empty($remoteField)) {
1730
			$polymorphic = false;
1731
			$message = "No has_one found on class '$remoteClass'";
1732
			if($type == 'has_many') {
1733
				// include a hint for has_many that is missing a has_one
1734
				$message .= ", the has_many relation from '$this->class' to '$remoteClass'";
1735
				$message .= " requires a has_one on '$remoteClass'";
1736
			}
1737
			throw new Exception($message);
1738
		}
1739
1740
		// If given an explicit field name ensure the related class specifies this
1741
		if(empty($remoteRelations[$remoteField])) {
1742
			throw new Exception("Missing expected has_one named '$remoteField'
1743
				on class '$remoteClass' referenced by $type named '$component'
1744
				on class {$this->class}"
1745
			);
1746
		}
1747
1748
		// Inspect resulting found relation
1749
		if($remoteRelations[$remoteField] === 'DataObject') {
1750
			$polymorphic = true;
1751
			return $remoteField; // Composite polymorphic field does not include 'ID' suffix
1752
		} else {
1753
			$polymorphic = false;
1754
			return $remoteField . 'ID';
1755
		}
1756
	}
1757
1758
	/**
1759
	 * Returns a many-to-many component, as a ManyManyList.
1760
	 * @param string $componentName Name of the many-many component
1761
	 * @return ManyManyList The set of components
1762
	 *
1763
	 * @todo Implement query-params
1764
	 */
1765
	public function getManyManyComponents($componentName, $filter = null, $sort = null, $join = null, $limit = null) {
1766
		list($parentClass, $componentClass, $parentField, $componentField, $table)
1767
			= $this->manyManyComponent($componentName);
1768
1769
		if($filter !== null || $sort !== null || $join !== null || $limit !== null) {
1770
			Deprecation::notice('4.0', 'The $filter, $sort, $join and $limit parameters for
1771
				DataObject::getManyManyComponents() have been deprecated.
1772
				Please manipluate the returned list directly.', Deprecation::SCOPE_GLOBAL);
1773
		}
1774
1775
		// If we haven't been written yet, we can't save these relations, so use a list that handles this case
1776
		if(!$this->ID) {
1777
			if(!isset($this->unsavedRelations[$componentName])) {
1778
				$this->unsavedRelations[$componentName] =
1779
					new UnsavedRelationList($parentClass, $componentName, $componentClass);
1780
			}
1781
			return $this->unsavedRelations[$componentName];
1782
		}
1783
1784
		$extraFields = $this->manyManyExtraFieldsForComponent($componentName) ?: array();
1785
		$result = ManyManyList::create($componentClass, $table, $componentField, $parentField, $extraFields);
1786
1787
1788
		// Store component data in query meta-data
1789
		$result = $result->alterDataQuery(function($query) use ($extraFields) {
1790
			$query->setQueryParam('Component.ExtraFields', $extraFields);
1791
		});
1792
		
1793
		if($this->model) $result->setDataModel($this->model);
1794
1795
		$this->extend('updateManyManyComponents', $result);
1796
1797
		// If this is called on a singleton, then we return an 'orphaned relation' that can have the
1798
		// foreignID set elsewhere.
1799
		return $result
1800
			->forForeignID($this->ID)
1801
			->where($filter)
1802
			->sort($sort)
1803
			->limit($limit);
1804
	}
1805
1806
	/**
1807
	 * @deprecated 4.0 Method has been replaced by hasOne() and hasOneComponent()
1808
	 * @param string $component
1809
	 * @return array|null
1810
	 */
1811
	public function has_one($component = null) {
1812
		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...
1813
			Deprecation::notice('4.0', 'Please use hasOneComponent() instead');
1814
			return $this->hasOneComponent($component);
1815
		}
1816
1817
		Deprecation::notice('4.0', 'Please use hasOne() instead');
1818
		return $this->hasOne();
1819
	}
1820
1821
	/**
1822
	 * Return the class of a one-to-one component.  If $component is null, return all of the one-to-one components and
1823
	 * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.
1824
	 *
1825
	 * @param string $component Deprecated - Name of component
1826
	 * @return string|array The class of the one-to-one component, or an array of all one-to-one components and
1827
	 * 							their classes.
1828
	 */
1829
	public function hasOne($component = null) {
1830
		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...
1831
			Deprecation::notice(
1832
				'4.0',
1833
				'Please use DataObject::hasOneComponent() instead of passing a component name to hasOne()',
1834
				Deprecation::SCOPE_GLOBAL
1835
			);
1836
			return $this->hasOneComponent($component);
1837
		}
1838
1839
		return (array)Config::inst()->get($this->class, 'has_one', Config::INHERITED);
1840
	}
1841
1842
	/**
1843
	 * Return data for a specific has_one component.
1844
	 * @param string $component
1845
	 * @return string|null
1846
	 */
1847
	public function hasOneComponent($component) {
1848
		$hasOnes = (array)Config::inst()->get($this->class, 'has_one', Config::INHERITED);
1849
1850
		if(isset($hasOnes[$component])) {
1851
			return $hasOnes[$component];
1852
		}
1853
	}
1854
1855
	/**
1856
	 * @deprecated 4.0 Method has been replaced by belongsTo() and belongsToComponent()
1857
	 * @param string $component
1858
	 * @param bool $classOnly
1859
	 * @return array|null
1860
	 */
1861
	public function belongs_to($component = null, $classOnly = true) {
1862
		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...
1863
			Deprecation::notice('4.0', 'Please use belongsToComponent() instead');
1864
			return $this->belongsToComponent($component, $classOnly);
1865
		}
1866
1867
		Deprecation::notice('4.0', 'Please use belongsTo() instead');
1868
		return $this->belongsTo(null, $classOnly);
1869
	}
1870
1871
	/**
1872
	 * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
1873
	 * their class name will be returned.
1874
	 *
1875
	 * @param string $component - Name of component
1876
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1877
	 *        the field data stripped off. It defaults to TRUE.
1878
	 * @return string|array
1879
	 */
1880
	public function belongsTo($component = null, $classOnly = true) {
1881
		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...
1882
			Deprecation::notice(
1883
				'4.0',
1884
				'Please use DataObject::belongsToComponent() instead of passing a component name to belongsTo()',
1885
				Deprecation::SCOPE_GLOBAL
1886
			);
1887
			return $this->belongsToComponent($component, $classOnly);
1888
		}
1889
1890
		$belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED);
1891
		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...
1892
			return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
1893
		} else {
1894
			return $belongsTo ? $belongsTo : array();
1895
		}
1896
	}
1897
1898
	/**
1899
	 * Return data for a specific belongs_to component.
1900
	 * @param string $component
1901
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1902
	 *        the field data stripped off. It defaults to TRUE.
1903
	 * @return string|false
1904
	 */
1905
	public function belongsToComponent($component, $classOnly = true) {
1906
		$belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED);
1907
1908
		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...
1909
			$belongsTo = $belongsTo[$component];
1910
		} else {
1911
			return false;
1912
		}
1913
1914
		return ($classOnly) ? preg_replace('/(.+)?\..+/', '$1', $belongsTo) : $belongsTo;
1915
	}
1916
1917
	/**
1918
	 * Return all of the database fields defined in self::$db and all the parent classes.
1919
	 * Doesn't include any fields specified by self::$has_one.  Use $this->hasOne() to get these fields
1920
	 *
1921
	 * @param string $fieldName Limit the output to a specific field name
1922
	 * @return array The database fields
1923
	 */
1924
	public function db($fieldName = null) {
1925
		$classes = ClassInfo::ancestry($this, true);
1926
1927
		// If we're looking for a specific field, we want to hit subclasses first as they may override field types
1928
		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...
1929
			$classes = array_reverse($classes);
1930
		}
1931
1932
		$items = array();
1933
		foreach($classes as $class) {
1934
			if(isset(self::$_cache_db[$class])) {
1935
				$dbItems = self::$_cache_db[$class];
1936
			} else {
1937
				$dbItems = (array) Config::inst()->get($class, 'db', Config::UNINHERITED);
1938
				self::$_cache_db[$class] = $dbItems;
1939
			}
1940
1941
			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...
1942
				if(isset($dbItems[$fieldName])) {
1943
					return $dbItems[$fieldName];
1944
				}
1945
			} else {
1946
				$items = isset($items) ? array_merge((array) $items, $dbItems) : $dbItems;
1947
			}
1948
		}
1949
1950
		return $items;
1951
	}
1952
1953
	/**
1954
	 * @deprecated 4.0 Method has been replaced by hasMany() and hasManyComponent()
1955
	 * @param string $component
1956
	 * @param bool $classOnly
1957
	 * @return array|null
1958
	 */
1959
	public function has_many($component = null, $classOnly = true) {
1960
		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...
1961
			Deprecation::notice('4.0', 'Please use hasManyComponent() instead');
1962
			return $this->hasManyComponent($component, $classOnly);
1963
		}
1964
1965
		Deprecation::notice('4.0', 'Please use hasMany() instead');
1966
		return $this->hasMany(null, $classOnly);
1967
	}
1968
1969
	/**
1970
	 * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
1971
	 * relationships and their classes will be returned.
1972
	 *
1973
	 * @param string $component Deprecated - Name of component
1974
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1975
	 *        the field data stripped off. It defaults to TRUE.
1976
	 * @return string|array|false
1977
	 */
1978
	public function hasMany($component = null, $classOnly = true) {
1979
		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...
1980
			Deprecation::notice(
1981
				'4.0',
1982
				'Please use DataObject::hasManyComponent() instead of passing a component name to hasMany()',
1983
				Deprecation::SCOPE_GLOBAL
1984
			);
1985
			return $this->hasManyComponent($component, $classOnly);
1986
		}
1987
1988
		$hasMany = (array)Config::inst()->get($this->class, 'has_many', Config::INHERITED);
1989
		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...
1990
			return preg_replace('/(.+)?\..+/', '$1', $hasMany);
1991
		} else {
1992
			return $hasMany ? $hasMany : array();
1993
		}
1994
	}
1995
1996
	/**
1997
	 * Return data for a specific has_many component.
1998
	 * @param string $component
1999
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2000
	 *        the field data stripped off. It defaults to TRUE.
2001
	 * @return string|false
2002
	 */
2003
	public function hasManyComponent($component, $classOnly = true) {
2004
		$hasMany = (array)Config::inst()->get($this->class, 'has_many', Config::INHERITED);
2005
2006
		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...
2007
			$hasMany = $hasMany[$component];
2008
		} else {
2009
			return false;
2010
		}
2011
2012
		return ($classOnly) ? preg_replace('/(.+)?\..+/', '$1', $hasMany) : $hasMany;
2013
	}
2014
2015
	/**
2016
	 * @deprecated 4.0 Method has been replaced by manyManyExtraFields() and
2017
	 *                 manyManyExtraFieldsForComponent()
2018
	 * @param string $component
2019
	 * @return array
2020
	 */
2021
	public function many_many_extraFields($component = null) {
2022
		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...
2023
			Deprecation::notice('4.0', 'Please use manyManyExtraFieldsForComponent() instead');
2024
			return $this->manyManyExtraFieldsForComponent($component);
2025
		}
2026
2027
		Deprecation::notice('4.0', 'Please use manyManyExtraFields() instead');
2028
		return $this->manyManyExtraFields();
2029
	}
2030
2031
	/**
2032
	 * Return the many-to-many extra fields specification.
2033
	 *
2034
	 * If you don't specify a component name, it returns all
2035
	 * extra fields for all components available.
2036
	 *
2037
	 * @param string $component Deprecated - Name of component
2038
	 * @return array|null
2039
	 */
2040
	public function manyManyExtraFields($component = null) {
2041
		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...
2042
			Deprecation::notice(
2043
				'4.0',
2044
				'Please use DataObject::manyManyExtraFieldsForComponent() instead of passing a component name
2045
					to manyManyExtraFields()',
2046
				Deprecation::SCOPE_GLOBAL
2047
			);
2048
			return $this->manyManyExtraFieldsForComponent($component);
2049
		}
2050
2051
		return Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED);
2052
	}
2053
2054
	/**
2055
	 * Return the many-to-many extra fields specification for a specific component.
2056
	 * @param string $component
2057
	 * @return array|null
2058
	 */
2059
	public function manyManyExtraFieldsForComponent($component) {
2060
		// Get all many_many_extraFields defined in this class or parent classes
2061
		$extraFields = (array)Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED);
2062
		// Extra fields are immediately available
2063
		if(isset($extraFields[$component])) {
2064
			return $extraFields[$component];
2065
		}
2066
2067
		// Check this class' belongs_many_manys to see if any of their reverse associations contain extra fields
2068
		$manyMany = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED);
2069
		$candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null;
2070
		if($candidate) {
2071
			$relationName = null;
2072
			// Extract class and relation name from dot-notation
2073
			if(strpos($candidate, '.') !== false) {
2074
				list($candidate, $relationName) = explode('.', $candidate, 2);
2075
			}
2076
2077
			// If we've not already found the relation name from dot notation, we need to find a relation that points
2078
			// back to this class. As there's no dot-notation, there can only be one relation pointing to this class,
2079
			// so it's safe to assume that it's the correct one
2080
			if(!$relationName) {
2081
				$candidateManyManys = (array)Config::inst()->get($candidate, 'many_many', Config::UNINHERITED);
2082
2083
				foreach($candidateManyManys as $relation => $relatedClass) {
2084
					if (is_a($this, $relatedClass)) {
2085
						$relationName = $relation;
2086
					}
2087
				}
2088
			}
2089
2090
			// If we've found a matching relation on the target class, see if we can find extra fields for it
2091
			$extraFields = (array)Config::inst()->get($candidate, 'many_many_extraFields', Config::UNINHERITED);
2092
			if(isset($extraFields[$relationName])) {
2093
				return $extraFields[$relationName];
2094
			}
2095
		}
2096
2097
		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...
2098
	}
2099
2100
	/**
2101
	 * @deprecated 4.0 Method has been renamed to manyMany()
2102
	 * @param string $component
2103
	 * @return array|null
2104
	 */
2105
	public function many_many($component = null) {
2106
		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...
2107
			Deprecation::notice('4.0', 'Please use manyManyComponent() instead');
2108
			return $this->manyManyComponent($component);
2109
		}
2110
2111
		Deprecation::notice('4.0', 'Please use manyMany() instead');
2112
		return $this->manyMany();
2113
	}
2114
2115
	/**
2116
	 * Return information about a many-to-many component.
2117
	 * The return value is an array of (parentclass, childclass).  If $component is null, then all many-many
2118
	 * components are returned.
2119
	 *
2120
	 * @see DataObject::manyManyComponent()
2121
	 * @param string $component Deprecated - Name of component
2122
	 * @return array|null An array of (parentclass, childclass), or an array of all many-many components
2123
	 */
2124
	public function manyMany($component = null) {
2125
		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...
2126
			Deprecation::notice(
2127
				'4.0',
2128
				'Please use DataObject::manyManyComponent() instead of passing a component name to manyMany()',
2129
				Deprecation::SCOPE_GLOBAL
2130
			);
2131
			return $this->manyManyComponent($component);
2132
		}
2133
2134
		$manyManys = (array)Config::inst()->get($this->class, 'many_many', Config::INHERITED);
2135
		$belongsManyManys = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED);
2136
2137
		$items = array_merge($manyManys, $belongsManyManys);
2138
		return $items;
2139
	}
2140
2141
	/**
2142
	 * Return information about a specific many_many component. Returns a numeric array of:
2143
	 * array(
2144
	 * 	<classname>,		The class that relation is defined in e.g. "Product"
2145
	 * 	<candidateName>,	The target class of the relation e.g. "Category"
2146
	 * 	<parentField>,		The field name pointing to <classname>'s table e.g. "ProductID"
2147
	 * 	<childField>,		The field name pointing to <candidatename>'s table e.g. "CategoryID"
2148
	 * 	<joinTable>			The join table between the two classes e.g. "Product_Categories"
2149
	 * )
2150
	 * @param string $component The component name
2151
	 * @return array|null
2152
	 */
2153
	public function manyManyComponent($component) {
2154
		$classes = $this->getClassAncestry();
2155
		foreach($classes as $class) {
2156
			$manyMany = Config::inst()->get($class, 'many_many', Config::UNINHERITED);
2157
			// Check if the component is defined in many_many on this class
2158
			$candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null;
2159
			if($candidate) {
2160
				$parentField = $class . "ID";
2161
				$childField = ($class == $candidate) ? "ChildID" : $candidate . "ID";
2162
				return array($class, $candidate, $parentField, $childField, "{$class}_$component");
2163
			}
2164
2165
			// Check if the component is defined in belongs_many_many on this class
2166
			$belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED);
2167
			$candidate = (isset($belongsManyMany[$component])) ? $belongsManyMany[$component] : null;
2168
			if($candidate) {
2169
				// Extract class and relation name from dot-notation
2170
				if(strpos($candidate, '.') !== false) {
2171
					list($candidate, $relationName) = explode('.', $candidate, 2);
2172
				}
2173
2174
				$childField = $candidate . "ID";
2175
2176
				// We need to find the inverse component name
2177
				$otherManyMany = Config::inst()->get($candidate, 'many_many', Config::UNINHERITED);
2178
				if(!$otherManyMany) {
2179
					throw new LogicException("Inverse component of $candidate not found ({$this->class})");
2180
				}
2181
2182
				// If we've got a relation name (extracted from dot-notation), we can already work out
2183
				// the join table and candidate class name...
2184
				if(isset($relationName) && isset($otherManyMany[$relationName])) {
2185
					$candidateClass = $otherManyMany[$relationName];
2186
					$joinTable = "{$candidate}_{$relationName}";
2187
				} else {
2188
					// ... otherwise, we need to loop over the many_manys and find a relation that
2189
					// matches up to this class
2190
					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...
2191
						if($candidateClass == $class || is_subclass_of($class, $candidateClass)) {
2192
							$joinTable = "{$candidate}_{$inverseComponentName}";
2193
							break;
2194
						}
2195
					}
2196
				}
2197
2198
				// If we could work out the join table, we've got all the info we need
2199
				if(isset($joinTable)) {
2200
					$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...
2201
					return array($class, $candidate, $parentField, $childField, $joinTable);
2202
				}
2203
2204
				throw new LogicException("Orphaned \$belongs_many_many value for $this->class.$component");
2205
			}
2206
		}
2207
	}
2208
2209
	/**
2210
	 * This returns an array (if it exists) describing the database extensions that are required, or false if none
2211
	 *
2212
	 * This is experimental, and is currently only a Postgres-specific enhancement.
2213
	 *
2214
	 * @return array or false
2215
	 */
2216
	public function database_extensions($class){
2217
		$extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
2218
2219
		if($extensions)
2220
			return $extensions;
2221
		else
2222
			return false;
2223
	}
2224
2225
	/**
2226
	 * Generates a SearchContext to be used for building and processing
2227
	 * a generic search form for properties on this object.
2228
	 *
2229
	 * @return SearchContext
2230
	 */
2231
	public function getDefaultSearchContext() {
2232
		return new SearchContext(
2233
			$this->class,
2234
			$this->scaffoldSearchFields(),
2235
			$this->defaultSearchFilters()
2236
		);
2237
	}
2238
2239
	/**
2240
	 * Determine which properties on the DataObject are
2241
	 * searchable, and map them to their default {@link FormField}
2242
	 * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
2243
	 *
2244
	 * Some additional logic is included for switching field labels, based on
2245
	 * how generic or specific the field type is.
2246
	 *
2247
	 * Used by {@link SearchContext}.
2248
	 *
2249
	 * @param array $_params
2250
	 *   'fieldClasses': Associative array of field names as keys and FormField classes as values
2251
	 *   'restrictFields': Numeric array of a field name whitelist
2252
	 * @return FieldList
2253
	 */
2254
	public function scaffoldSearchFields($_params = null) {
2255
		$params = array_merge(
2256
			array(
2257
				'fieldClasses' => false,
2258
				'restrictFields' => false
2259
			),
2260
			(array)$_params
2261
		);
2262
		$fields = new FieldList();
2263
		foreach($this->searchableFields() as $fieldName => $spec) {
2264
			if($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) continue;
2265
2266
			// If a custom fieldclass is provided as a string, use it
2267
			if($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
2268
				$fieldClass = $params['fieldClasses'][$fieldName];
2269
				$field = new $fieldClass($fieldName);
2270
			// If we explicitly set a field, then construct that
2271
			} else if(isset($spec['field'])) {
2272
				// If it's a string, use it as a class name and construct
2273
				if(is_string($spec['field'])) {
2274
					$fieldClass = $spec['field'];
2275
					$field = new $fieldClass($fieldName);
2276
2277
				// If it's a FormField object, then just use that object directly.
2278
				} else if($spec['field'] instanceof FormField) {
2279
					$field = $spec['field'];
2280
2281
				// Otherwise we have a bug
2282
				} else {
2283
					user_error("Bad value for searchable_fields, 'field' value: "
2284
						. var_export($spec['field'], true), E_USER_WARNING);
2285
				}
2286
2287
			// Otherwise, use the database field's scaffolder
2288
			} else {
2289
				$field = $this->relObject($fieldName)->scaffoldSearchField();
2290
			}
2291
2292
			if (strstr($fieldName, '.')) {
2293
				$field->setName(str_replace('.', '__', $fieldName));
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...
2294
			}
2295
			$field->setTitle($spec['title']);
2296
2297
			$fields->push($field);
2298
		}
2299
		return $fields;
2300
	}
2301
2302
	/**
2303
	 * Scaffold a simple edit form for all properties on this dataobject,
2304
	 * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
2305
	 * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
2306
	 *
2307
	 * @uses FormScaffolder
2308
	 *
2309
	 * @param array $_params Associative array passing through properties to {@link FormScaffolder}.
2310
	 * @return FieldList
2311
	 */
2312
	public function scaffoldFormFields($_params = null) {
2313
		$params = array_merge(
2314
			array(
2315
				'tabbed' => false,
2316
				'includeRelations' => false,
2317
				'restrictFields' => false,
2318
				'fieldClasses' => false,
2319
				'ajaxSafe' => false
2320
			),
2321
			(array)$_params
2322
		);
2323
2324
		$fs = new FormScaffolder($this);
2325
		$fs->tabbed = $params['tabbed'];
2326
		$fs->includeRelations = $params['includeRelations'];
2327
		$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...
2328
		$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...
2329
		$fs->ajaxSafe = $params['ajaxSafe'];
2330
2331
		return $fs->getFieldList();
2332
	}
2333
2334
	/**
2335
	 * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
2336
	 * being called on extensions
2337
	 *
2338
	 * @param callable $callback The callback to execute
2339
	 */
2340
	protected function beforeUpdateCMSFields($callback) {
2341
		$this->beforeExtending('updateCMSFields', $callback);
2342
	}
2343
2344
	/**
2345
	 * Centerpiece of every data administration interface in Silverstripe,
2346
	 * which returns a {@link FieldList} suitable for a {@link Form} object.
2347
	 * If not overloaded, we're using {@link scaffoldFormFields()} to automatically
2348
	 * generate this set. To customize, overload this method in a subclass
2349
	 * or extended onto it by using {@link DataExtension->updateCMSFields()}.
2350
	 *
2351
	 * <code>
2352
	 * class MyCustomClass extends DataObject {
2353
	 *  static $db = array('CustomProperty'=>'Boolean');
2354
	 *
2355
	 *  function getCMSFields() {
2356
	 *    $fields = parent::getCMSFields();
2357
	 *    $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
2358
	 *    return $fields;
2359
	 *  }
2360
	 * }
2361
	 * </code>
2362
	 *
2363
	 * @see Good example of complex FormField building: SiteTree::getCMSFields()
2364
	 *
2365
	 * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.
2366
	 */
2367
	public function getCMSFields() {
2368
		$tabbedFields = $this->scaffoldFormFields(array(
2369
			// Don't allow has_many/many_many relationship editing before the record is first saved
2370
			'includeRelations' => ($this->ID > 0),
2371
			'tabbed' => true,
2372
			'ajaxSafe' => true
2373
		));
2374
2375
		$this->extend('updateCMSFields', $tabbedFields);
2376
2377
		return $tabbedFields;
2378
	}
2379
2380
	/**
2381
	 * need to be overload by solid dataobject, so that the customised actions of that dataobject,
2382
	 * including that dataobject's extensions customised actions could be added to the EditForm.
2383
	 *
2384
	 * @return an Empty FieldList(); need to be overload by solid subclass
2385
	 */
2386
	public function getCMSActions() {
2387
		$actions = new FieldList();
2388
		$this->extend('updateCMSActions', $actions);
2389
		return $actions;
2390
	}
2391
2392
2393
	/**
2394
	 * Used for simple frontend forms without relation editing
2395
	 * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()}
2396
	 * by default. To customize, either overload this method in your
2397
	 * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.
2398
	 *
2399
	 * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API
2400
	 *
2401
	 * @param array $params See {@link scaffoldFormFields()}
2402
	 * @return FieldList Always returns a simple field collection without TabSet.
2403
	 */
2404
	public function getFrontEndFields($params = null) {
2405
		$untabbedFields = $this->scaffoldFormFields($params);
2406
		$this->extend('updateFrontEndFields', $untabbedFields);
2407
2408
		return $untabbedFields;
2409
	}
2410
2411
	/**
2412
	 * Gets the value of a field.
2413
	 * Called by {@link __get()} and any getFieldName() methods you might create.
2414
	 *
2415
	 * @param string $field The name of the field
2416
	 *
2417
	 * @return mixed The field value
2418
	 */
2419
	public function getField($field) {
2420
		// If we already have an object in $this->record, then we should just return that
2421
		if(isset($this->record[$field]) && is_object($this->record[$field]))  return $this->record[$field];
2422
2423
		// Do we have a field that needs to be lazy loaded?
2424
		if(isset($this->record[$field.'_Lazy'])) {
2425
			$tableClass = $this->record[$field.'_Lazy'];
2426
			$this->loadLazyFields($tableClass);
2427
		}
2428
2429
		// Otherwise, we need to determine if this is a complex field
2430
		if(self::is_composite_field($this->class, $field)) {
2431
			$helper = $this->castingHelper($field);
2432
			$fieldObj = Object::create_from_string($helper, $field);
2433
2434
			$compositeFields = $fieldObj->compositeDatabaseFields();
2435
			foreach ($compositeFields as $compositeName => $compositeType) {
2436
				if(isset($this->record[$field.$compositeName.'_Lazy'])) {
2437
					$tableClass = $this->record[$field.$compositeName.'_Lazy'];
2438
					$this->loadLazyFields($tableClass);
2439
				}
2440
			}
2441
2442
			// write value only if either the field value exists,
2443
			// or a valid record has been loaded from the database
2444
			$value = (isset($this->record[$field])) ? $this->record[$field] : null;
2445
			if($value || $this->exists()) $fieldObj->setValue($value, $this->record, false);
2446
2447
			$this->record[$field] = $fieldObj;
2448
2449
			return $this->record[$field];
2450
		}
2451
2452
		return isset($this->record[$field]) ? $this->record[$field] : null;
2453
	}
2454
2455
	/**
2456
	 * Loads all the stub fields that an initial lazy load didn't load fully.
2457
	 *
2458
	 * @param string $tableClass Base table to load the values from. Others are joined as required.
2459
	 * Not specifying a tableClass will load all lazy fields from all tables.
2460
	 * @return bool Flag if lazy loading succeeded
2461
	 */
2462
	protected function loadLazyFields($tableClass = null) {
2463
		if(!$this->isInDB() || !is_numeric($this->ID)) {
2464
			return false;
2465
		}
2466
2467
		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...
2468
			$loaded = array();
2469
2470
			foreach ($this->record as $key => $value) {
2471
				if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
2472
					$this->loadLazyFields($value);
2473
					$loaded[$value] = $value;
2474
				}
2475
			}
2476
2477
			return false;
2478
		}
2479
2480
		$dataQuery = new DataQuery($tableClass);
2481
2482
		// Reset query parameter context to that of this DataObject
2483
		if($params = $this->getSourceQueryParams()) {
2484
			foreach($params as $key => $value) $dataQuery->setQueryParam($key, $value);
2485
		}
2486
2487
		// Limit query to the current record, unless it has the Versioned extension,
2488
		// in which case it requires special handling through augmentLoadLazyFields()
2489
		if(!$this->hasExtension('Versioned')) {
2490
			$dataQuery->where("\"$tableClass\".\"ID\" = {$this->record['ID']}")->limit(1);
2491
		}
2492
2493
		$columns = array();
2494
2495
		// Add SQL for fields, both simple & multi-value
2496
		// TODO: This is copy & pasted from buildSQL(), it could be moved into a method
2497
		$databaseFields = self::database_fields($tableClass, false);
2498
		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...
2499
			if(!isset($this->record[$k]) || $this->record[$k] === null) {
2500
				$columns[] = $k;
2501
			}
2502
		}
2503
2504
		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...
2505
			$query = $dataQuery->query();
2506
			$this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
2507
			$this->extend('augmentSQL', $query, $dataQuery);
2508
2509
			$dataQuery->setQueriedColumns($columns);
2510
			$newData = $dataQuery->execute()->record();
2511
2512
			// Load the data into record
2513
			if($newData) {
2514
				foreach($newData as $k => $v) {
2515
					if (in_array($k, $columns)) {
2516
						$this->record[$k] = $v;
2517
						$this->original[$k] = $v;
2518
						unset($this->record[$k . '_Lazy']);
2519
					}
2520
				}
2521
2522
			// No data means that the query returned nothing; assign 'null' to all the requested fields
2523
			} else {
2524
				foreach($columns as $k) {
2525
					$this->record[$k] = null;
2526
					$this->original[$k] = null;
2527
					unset($this->record[$k . '_Lazy']);
2528
				}
2529
			}
2530
		}
2531
		return true;
2532
	}
2533
2534
	/**
2535
	 * Return the fields that have changed.
2536
	 *
2537
	 * The change level affects what the functions defines as "changed":
2538
	 * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
2539
	 * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
2540
	 *   for example a change from 0 to null would not be included.
2541
	 *
2542
	 * Example return:
2543
	 * <code>
2544
	 * array(
2545
	 *   'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
2546
	 * )
2547
	 * </code>
2548
	 *
2549
	 * @param boolean $databaseFieldsOnly Get only database fields that have changed
2550
	 * @param int $changeLevel The strictness of what is defined as change. Defaults to strict
2551
	 * @return array
2552
	 */
2553
	public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT) {
2554
		$changedFields = array();
2555
2556
		// Update the changed array with references to changed obj-fields
2557
		foreach($this->record as $k => $v) {
2558
			if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
2559
				$this->changed[$k] = self::CHANGE_VALUE;
2560
			}
2561
		}
2562
2563
		if($databaseFieldsOnly) {
2564
			// Merge all DB fields together
2565
			$inheritedFields = $this->inheritedDatabaseFields();
2566
			$compositeFields = static::composite_fields(get_class($this));
2567
			$fixedFields = $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...
2568
			$databaseFields = array_merge(
2569
				$inheritedFields,
2570
				$fixedFields,
2571
				$compositeFields
2572
			);
2573
			$fields = array_intersect_key((array)$this->changed, $databaseFields);
2574
		} else {
2575
			$fields = $this->changed;
2576
		}
2577
2578
		// Filter the list to those of a certain change level
2579
		if($changeLevel > self::CHANGE_STRICT) {
2580
			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...
2581
				if($level < $changeLevel) {
2582
					unset($fields[$name]);
2583
				}
2584
			}
2585
		}
2586
2587
		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...
2588
			$changedFields[$name] = array(
2589
				'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
2590
				'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
2591
				'level' => $level
2592
			);
2593
		}
2594
2595
		return $changedFields;
2596
	}
2597
2598
	/**
2599
	 * Uses {@link getChangedFields()} to determine if fields have been changed
2600
	 * since loading them from the database.
2601
	 *
2602
	 * @param string $fieldName Name of the database field to check, will check for any if not given
2603
	 * @param int $changeLevel See {@link getChangedFields()}
2604
	 * @return boolean
2605
	 */
2606
	public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT) {
2607
		if (!$fieldName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldName 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...
2608
			// Limit "any changes" to db fields only
2609
			$changed = $this->getChangedFields(true, $changeLevel);
2610
			return !empty($changed);
2611
		} else {
2612
			// Given a field name, check all fields
2613
			$changed = $this->getChangedFields(false, $changeLevel);
2614
			return array_key_exists($fieldName, $changed);
2615
		}
2616
	}
2617
2618
	/**
2619
	 * Set the value of the field
2620
	 * Called by {@link __set()} and any setFieldName() methods you might create.
2621
	 *
2622
	 * @param string $fieldName Name of the field
2623
	 * @param mixed $val New field value
2624
	 * @return DataObject $this
2625
	 */
2626
	public function setField($fieldName, $val) {
2627
		//if it's a has_one component, destroy the cache
2628
		if (substr($fieldName, -2) == 'ID') {
2629
			unset($this->components[substr($fieldName, 0, -2)]);
2630
		}
2631
		// Situation 1: Passing an DBField
2632
		if($val instanceof DBField) {
2633
			$val->Name = $fieldName;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<DBField>. 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...
2634
2635
			// If we've just lazy-loaded the column, then we need to populate the $original array by
2636
			// called getField(). Too much overhead? Could this be done by a quicker method? Maybe only
2637
			// on a call to getChanged()?
2638
			$this->getField($fieldName);
2639
2640
			$this->record[$fieldName] = $val;
2641
		// Situation 2: Passing a literal or non-DBField object
2642
		} else {
2643
			// If this is a proper database field, we shouldn't be getting non-DBField objects
2644
			if(is_object($val) && $this->db($fieldName)) {
2645
				user_error('DataObject::setField: passed an object that is not a DBField', E_USER_WARNING);
2646
			}
2647
2648
			// if a field is not existing or has strictly changed
2649
			if(!isset($this->record[$fieldName]) || $this->record[$fieldName] !== $val) {
2650
				// TODO Add check for php-level defaults which are not set in the db
2651
				// TODO Add check for hidden input-fields (readonly) which are not set in the db
2652
				// At the very least, the type has changed
2653
				$this->changed[$fieldName] = self::CHANGE_STRICT;
2654
2655
				if((!isset($this->record[$fieldName]) && $val) || (isset($this->record[$fieldName])
2656
						&& $this->record[$fieldName] != $val)) {
2657
2658
					// Value has changed as well, not just the type
2659
					$this->changed[$fieldName] = self::CHANGE_VALUE;
2660
				}
2661
2662
				// If we've just lazy-loaded the column, then we need to populate the $original array by
2663
				// called getField(). Too much overhead? Could this be done by a quicker method? Maybe only
2664
				// on a call to getChanged()?
2665
				$this->getField($fieldName);
2666
2667
				// Value is always saved back when strict check succeeds.
2668
				$this->record[$fieldName] = $val;
2669
			}
2670
		}
2671
		return $this;
2672
	}
2673
2674
	/**
2675
	 * Set the value of the field, using a casting object.
2676
	 * This is useful when you aren't sure that a date is in SQL format, for example.
2677
	 * setCastedField() can also be used, by forms, to set related data.  For example, uploaded images
2678
	 * can be saved into the Image table.
2679
	 *
2680
	 * @param string $fieldName Name of the field
2681
	 * @param mixed $value New field value
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
2682
	 * @return DataObject $this
2683
	 */
2684
	public function setCastedField($fieldName, $val) {
2685
		if(!$fieldName) {
2686
			user_error("DataObject::setCastedField: Called without a fieldName", E_USER_ERROR);
2687
		}
2688
		$castingHelper = $this->castingHelper($fieldName);
2689
		if($castingHelper) {
2690
			$fieldObj = Object::create_from_string($castingHelper, $fieldName);
2691
			$fieldObj->setValue($val);
2692
			$fieldObj->saveInto($this);
2693
		} else {
2694
			$this->$fieldName = $val;
2695
		}
2696
		return $this;
2697
	}
2698
2699
	/**
2700
	 * {@inheritdoc}
2701
	 */
2702
	public function castingHelper($field) {
2703
		if ($fieldSpec = $this->db($field)) {
2704
			return $fieldSpec;
2705
		}
2706
2707
		// many_many_extraFields aren't presented by db(), so we check if the source query params
2708
		// provide us with meta-data for a many_many relation we can inspect for extra fields.
2709
		$queryParams = $this->getSourceQueryParams();
2710
		if (!empty($queryParams['Component.ExtraFields'])) {
2711
			$extraFields = $queryParams['Component.ExtraFields'];
2712
2713
			if (isset($extraFields[$field])) {
2714
				return $extraFields[$field];
2715
			}
2716
		}
2717
2718
		return parent::castingHelper($field);
2719
	}
2720
2721
	/**
2722
	 * Returns true if the given field exists in a database column on any of
2723
	 * the objects tables and optionally look up a dynamic getter with
2724
	 * get<fieldName>().
2725
	 *
2726
	 * @param string $field Name of the field
2727
	 * @return boolean True if the given field exists
2728
	 */
2729
	public function hasField($field) {
2730
		return (
2731
			array_key_exists($field, $this->record)
2732
			|| $this->db($field)
2733
			|| (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...
2734
			|| $this->hasMethod("get{$field}")
2735
		);
2736
	}
2737
2738
	/**
2739
	 * Returns true if the given field exists as a database column
2740
	 *
2741
	 * @param string $field Name of the field
2742
	 *
2743
	 * @return boolean
2744
	 */
2745
	public function hasDatabaseField($field) {
2746
		if(isset(self::$fixed_fields[$field])) return true;
2747
2748
		return array_key_exists($field, $this->inheritedDatabaseFields());
2749
	}
2750
2751
	/**
2752
	 * Returns the field type of the given field, if it belongs to this class, and not a parent.
2753
	 * Note that the field type will not include constructor arguments in round brackets, only the classname.
2754
	 *
2755
	 * @param string $field Name of the field
2756
	 * @return string The field type of the given field
2757
	 */
2758
	public function hasOwnTableDatabaseField($field) {
2759
		return self::has_own_table_database_field($this->class, $field);
2760
	}
2761
2762
	/**
2763
	 * Returns the field type of the given field, if it belongs to this class, and not a parent.
2764
	 * Note that the field type will not include constructor arguments in round brackets, only the classname.
2765
	 *
2766
	 * @param string $class Class name to check
2767
	 * @param string $field Name of the field
2768
	 * @return string The field type of the given field
2769
	 */
2770
	public static function has_own_table_database_field($class, $field) {
2771
		// Since database_fields omits 'ID'
2772
		if($field == "ID") return "Int";
2773
2774
		$fieldMap = self::database_fields($class, false);
2775
2776
		// Remove string-based "constructor-arguments" from the DBField definition
2777
		if(isset($fieldMap[$field])) {
2778
			$spec = $fieldMap[$field];
2779
			if(is_string($spec)) return strtok($spec,'(');
2780
			else return $spec['type'];
2781
		}
2782
	}
2783
2784
	/**
2785
	 * Returns true if given class has its own table. Uses the rules for whether the table should exist rather than
2786
	 * actually looking in the database.
2787
	 *
2788
	 * @param string $dataClass
2789
	 * @return bool
2790
	 */
2791
	public static function has_own_table($dataClass) {
2792
		if(!is_subclass_of($dataClass,'DataObject')) return false;
2793
2794
		$dataClass = ClassInfo::class_name($dataClass);
2795
		if(!isset(DataObject::$cache_has_own_table[$dataClass])) {
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...
2796
			if(get_parent_class($dataClass) == 'DataObject') {
2797
				DataObject::$cache_has_own_table[$dataClass] = true;
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...
2798
			} else {
2799
				DataObject::$cache_has_own_table[$dataClass]
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...
2800
					= Config::inst()->get($dataClass, 'db', Config::UNINHERITED)
2801
					|| Config::inst()->get($dataClass, 'has_one', Config::UNINHERITED);
2802
			}
2803
		}
2804
		return DataObject::$cache_has_own_table[$dataClass];
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...
2805
	}
2806
2807
	/**
2808
	 * Returns true if the member is allowed to do the given action.
2809
	 * See {@link extendedCan()} for a more versatile tri-state permission control.
2810
	 *
2811
	 * @param string $perm The permission to be checked, such as 'View'.
2812
	 * @param Member $member The member whose permissions need checking.  Defaults to the currently logged
2813
	 * in user.
2814
	 *
2815
	 * @return boolean True if the the member is allowed to do the given action
2816
	 */
2817
	public function can($perm, $member = null) {
2818
		if(!isset($member)) {
2819
			$member = Member::currentUser();
2820
		}
2821
		if(Permission::checkMember($member, "ADMIN")) return true;
2822
2823
		if($this->manyManyComponent('Can' . $perm)) {
2824
			if($this->ParentID && $this->SecurityType == 'Inherit') {
2825
				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...
2826
					return false;
2827
				}
2828
				return $this->Parent->can($perm, $member);
2829
2830
			} else {
2831
				$permissionCache = $this->uninherited('permissionCache');
2832
				$memberID = $member ? $member->ID : 'none';
2833
2834
				if(!isset($permissionCache[$memberID][$perm])) {
2835
					if($member->ID) {
2836
						$groups = $member->Groups();
2837
					}
2838
2839
					$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...
2840
2841
					// TODO Fix relation table hardcoding
2842
					$query = new SQLQuery(
0 ignored issues
show
Deprecated Code introduced by
The class SQLQuery has been deprecated with message: since version 4.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
2843
						"\"Page_Can$perm\".PageID",
2844
					array("\"Page_Can$perm\""),
2845
						"GroupID IN ($groupList)");
2846
2847
					$permissionCache[$memberID][$perm] = $query->execute()->column();
2848
2849
					if($perm == "View") {
2850
						// TODO Fix relation table hardcoding
2851
						$query = new SQLQuery("\"SiteTree\".\"ID\"", array(
0 ignored issues
show
Deprecated Code introduced by
The class SQLQuery has been deprecated with message: since version 4.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
2852
							"\"SiteTree\"",
2853
							"LEFT JOIN \"Page_CanView\" ON \"Page_CanView\".\"PageID\" = \"SiteTree\".\"ID\""
2854
							), "\"Page_CanView\".\"PageID\" IS NULL");
2855
2856
							$unsecuredPages = $query->execute()->column();
2857
							if($permissionCache[$memberID][$perm]) {
2858
								$permissionCache[$memberID][$perm]
2859
									= array_merge($permissionCache[$memberID][$perm], $unsecuredPages);
2860
							} else {
2861
								$permissionCache[$memberID][$perm] = $unsecuredPages;
2862
							}
2863
					}
2864
2865
					Config::inst()->update($this->class, 'permissionCache', $permissionCache);
2866
				}
2867
2868
				if($permissionCache[$memberID][$perm]) {
2869
					return in_array($this->ID, $permissionCache[$memberID][$perm]);
2870
				}
2871
			}
2872
		} else {
2873
			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, AggregateTest_Bar, AggregateTest_Baz, AggregateTest_Fab, AggregateTest_Fac, AggregateTest_Foo, BasicAuthTest_ControllerSecuredWithPermission, BasicAuthTest_ControllerSecuredWithoutPermission, BulkLoaderTestPlayer, CMSFormTest_Controller, 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, CompositeDBFieldTest_DataObject, 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, DailyTask, DataDifferencerTest_HasOneRelationObject, DataDifferencerTest_MockImage, DataDifferencerTest_Object, DataExtensionTest_CMSFieldsBase, DataExtensionTest_CMSFieldsChild, DataExtensionTest_CMSFieldsGrandchild, DataExtensionTest_Member, DataExtensionTest_MyObject, DataExtensionTest_Player, DataExtensionTest_RelatedObject, DataObject, DataObjectDuplicateTestClass1, DataObjectDuplicateTestClass2, DataObjectDuplicateTestClass3, DataObjectSchemaGenerationTest_DO, DataObjectSchemaGenerationTest_IndexDO, DataObjectSchemaGenerationTest_Sorted, 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_Sortable, DataObjectTest_Staff, DataObjectTest_SubEquipmentCompany, DataObjectTest_SubTeam, DataObjectTest_Team, DataObjectTest_TeamComment, DataObjectTest_ValidatedObject, DataQueryTest_A, DataQueryTest_B, DataQueryTest_C, DataQueryTest_D, DataQueryTest_E, DataQueryTest_F, DataQueryTest_G, DatabaseAdmin, DatabaseTest_MyObject, DatetimeFieldTest_Model, DbDateTimeTest_Team, 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, GridFieldFilterHeaderTest_DataObject, GridFieldPrintButtonTest_DO, GridFieldSortableHeaderTest_Cheerleader, GridFieldSortableHeaderTest_CheerleaderHat, GridFieldSortableHeaderTest_Team, GridFieldTest_Cheerleader, GridFieldTest_Permissions, GridFieldTest_Player, GridFieldTest_Team, GridField_URLHandlerTest_Controller, Group, GroupTest_Member, HasManyListTest_Company, HasManyListTest_CompanyCar, HasManyListTest_Employee, HierarchyHideTest_Object, HierarchyHideTest_SubObject, HierarchyTest_Object, HourlyTask, HtmlEditorFieldTest_Object, Image, Image_Cached, InstallerTest, JSTestRunner, LeftAndMain, LeftAndMainTest_Controller, LeftAndMainTest_Object, ListboxFieldTest_Article, ListboxFieldTest_DataObject, ListboxFieldTest_Tag, LoginAttempt, ManyManyListTest_Category, ManyManyListTest_ExtraFields, ManyManyListTest_IndirectPrimary, ManyManyListTest_Product, 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, MonthlyTask, MySQLDatabaseTest_Data, NumericFieldTest_Object, OtherSubclassWithSameField, Permission, PermissionRole, PermissionRoleCode, QuarterHourlyTask, RequestHandlingFieldTest_Controller, RequestHandlingTest_AllowedController, RequestHandlingTest_Controller, RequestHandlingTest_Cont...rFormWithAllowedActions, RequestHandlingTest_FormActionController, RestfulServiceTest_Controller, SQLInsertTestBase, SQLQueryTestBase, SQLQueryTestChild, SQLQueryTest_DO, SQLUpdateChild, SQLUpdateTestBase, SSViewerCacheBlockTest_Model, SSViewerCacheBlockTest_VersionedModel, SSViewerTest_Controller, SSViewerTest_Object, SapphireInfo, SapphireREPL, ScheduledTask, 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\Framework\Tests\ClassI, SubclassedDBFieldObject, TaskRunner, TestRunner, TransactionTest_Object, UnsavedRelationListTest_DataObject, Upload, UploadFieldTest_Controller, UploadFieldTest_ExtendedFile, UploadFieldTest_Record, VersionableExtensionsTest_DataObject, VersionedLazySub_DataObject, VersionedLazy_DataObject, VersionedTest_AnotherSubclass, VersionedTest_DataObject, VersionedTest_PublicStage, VersionedTest_PublicViaExtension, VersionedTest_RelatedWithoutVersion, VersionedTest_SingleStage, VersionedTest_Subclass, VersionedTest_UnversionedWithField, VersionedTest_WithIndexes, WeeklyTask, XMLDataFormatterTest_DataObject, YamlFixtureTest_DataObject, YamlFixtureTest_DataObjectRelation, YearlyTask, 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...
2874
		}
2875
	}
2876
2877
	/**
2878
	 * Process tri-state responses from permission-alterting extensions.  The extensions are
2879
	 * expected to return one of three values:
2880
	 *
2881
	 *  - false: Disallow this permission, regardless of what other extensions say
2882
	 *  - true: Allow this permission, as long as no other extensions return false
2883
	 *  - NULL: Don't affect the outcome
2884
	 *
2885
	 * This method itself returns a tri-state value, and is designed to be used like this:
2886
	 *
2887
	 * <code>
2888
	 * $extended = $this->extendedCan('canDoSomething', $member);
2889
	 * if($extended !== null) return $extended;
2890
	 * else return $normalValue;
2891
	 * </code>
2892
	 *
2893
	 * @param String $methodName Method on the same object, e.g. {@link canEdit()}
2894
	 * @param Member|int $member
2895
	 * @return boolean|null
2896
	 */
2897
	public function extendedCan($methodName, $member) {
2898
		$results = $this->extend($methodName, $member);
2899
		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...
2900
			// Remove NULLs
2901
			$results = array_filter($results, function($v) {return !is_null($v);});
2902
			// If there are any non-NULL responses, then return the lowest one of them.
2903
			// If any explicitly deny the permission, then we don't get access
2904
			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...
2905
		}
2906
		return null;
2907
	}
2908
2909
	/**
2910
	 * @param Member $member
2911
	 * @return boolean
2912
	 */
2913
	public function canView($member = null) {
2914
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2913 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...
2915
		if($extended !== null) {
2916
			return $extended;
2917
		}
2918
		return Permission::check('ADMIN', 'any', $member);
2919
	}
2920
2921
	/**
2922
	 * @param Member $member
2923
	 * @return boolean
2924
	 */
2925
	public function canEdit($member = null) {
2926
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2925 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...
2927
		if($extended !== null) {
2928
			return $extended;
2929
		}
2930
		return Permission::check('ADMIN', 'any', $member);
2931
	}
2932
2933
	/**
2934
	 * @param Member $member
2935
	 * @return boolean
2936
	 */
2937
	public function canDelete($member = null) {
2938
		$extended = $this->extendedCan(__FUNCTION__, $member);
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
	 * @todo Should canCreate be a static method?
2947
	 *
2948
	 * @param Member $member
2949
	 * @return boolean
2950
	 */
2951
	public function canCreate($member = null) {
2952
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2951 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...
2953
		if($extended !== null) {
2954
			return $extended;
2955
		}
2956
		return Permission::check('ADMIN', 'any', $member);
2957
	}
2958
2959
	/**
2960
	 * Debugging used by Debug::show()
2961
	 *
2962
	 * @return string HTML data representing this object
2963
	 */
2964
	public function debug() {
2965
		$val = "<h3>Database record: $this->class</h3>\n<ul>\n";
2966
		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...
2967
			$val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
2968
		}
2969
		$val .= "</ul>\n";
2970
		return $val;
2971
	}
2972
2973
	/**
2974
	 * Return the DBField object that represents the given field.
2975
	 * This works similarly to obj() with 2 key differences:
2976
	 *   - it still returns an object even when the field has no value.
2977
	 *   - it only matches fields and not methods
2978
	 *   - it matches foreign keys generated by has_one relationships, eg, "ParentID"
2979
	 *
2980
	 * @param string $fieldName Name of the field
2981
	 * @return DBField The field as a DBField object
2982
	 */
2983
	public function dbObject($fieldName) {
2984
		// If we have a CompositeDBField object in $this->record, then return that
2985
		if(isset($this->record[$fieldName]) && is_object($this->record[$fieldName])) {
2986
			return $this->record[$fieldName];
2987
2988
		// Special case for ID field
2989
		} else if($fieldName == 'ID') {
2990
			return new PrimaryKey($fieldName, $this);
2991
2992
		// Special case for ClassName
2993
		} else if($fieldName == 'ClassName') {
2994
			$val = get_class($this);
2995
			return DBField::create_field('Varchar', $val, $fieldName);
2996
2997
		} else if(array_key_exists($fieldName, self::$fixed_fields)) {
2998
			return DBField::create_field(self::$fixed_fields[$fieldName], $this->$fieldName, $fieldName);
2999
3000
		// General casting information for items in $db
3001
		} else if($helper = $this->db($fieldName)) {
3002
			$obj = Object::create_from_string($helper, $fieldName);
3003
			$obj->setValue($this->$fieldName, $this->record, false);
3004
			return $obj;
3005
3006
		// Special case for has_one relationships
3007
		} else if(preg_match('/ID$/', $fieldName) && $this->hasOneComponent(substr($fieldName,0,-2))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->hasOneComponent(substr($fieldName, 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...
3008
			$val = $this->$fieldName;
3009
			return DBField::create_field('ForeignKey', $val, $fieldName, $this);
3010
3011
		// has_one for polymorphic relations do not end in ID
3012
		} else if(($type = $this->hasOneComponent($fieldName)) && ($type === 'DataObject')) {
3013
			$val = $this->$fieldName();
3014
			return DBField::create_field('PolymorphicForeignKey', $val, $fieldName, $this);
3015
3016
		}
3017
	}
3018
3019
	/**
3020
	 * Traverses to a DBField referenced by relationships between data objects.
3021
	 *
3022
	 * The path to the related field is specified with dot separated syntax
3023
	 * (eg: Parent.Child.Child.FieldName).
3024
	 *
3025
	 * @param string $fieldPath
3026
	 *
3027
	 * @return mixed DBField of the field on the object or a DataList instance.
3028
	 */
3029
	public function relObject($fieldPath) {
3030
		$object = null;
3031
3032
		if(strpos($fieldPath, '.') !== false) {
3033
			$parts = explode('.', $fieldPath);
3034
			$fieldName = array_pop($parts);
3035
3036
			// Traverse dot syntax
3037
			$component = $this;
3038
3039
			foreach($parts as $relation) {
3040
				if($component instanceof SS_List) {
3041
					if(method_exists($component,$relation)) {
3042
						$component = $component->$relation();
3043
					} else {
3044
						$component = $component->relation($relation);
3045
					}
3046
				} else {
3047
					$component = $component->$relation();
3048
				}
3049
			}
3050
3051
			$object = $component->dbObject($fieldName);
3052
3053
		} else {
3054
			$object = $this->dbObject($fieldPath);
3055
		}
3056
3057
		return $object;
3058
	}
3059
3060
	/**
3061
	 * Traverses to a field referenced by relationships between data objects, returning the value
3062
	 * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)
3063
	 *
3064
	 * @param $fieldPath string
3065
	 * @return string | null - will return null on a missing value
3066
	 */
3067
	public function relField($fieldName) {
3068
		$component = $this;
3069
3070
		// We're dealing with relations here so we traverse the dot syntax
3071
		if(strpos($fieldName, '.') !== false) {
3072
			$relations = explode('.', $fieldName);
3073
			$fieldName = array_pop($relations);
3074
			foreach($relations as $relation) {
3075
				// Inspect $component for element $relation
3076
				if($component->hasMethod($relation)) {
3077
					// Check nested method
3078
					$component = $component->$relation();
3079
				} elseif($component instanceof SS_List) {
3080
					// Select adjacent relation from DataList
3081
					$component = $component->relation($relation);
3082
				} elseif($component instanceof DataObject
3083
					&& ($dbObject = $component->dbObject($relation))
3084
				) {
3085
					// Select db object
3086
					$component = $dbObject;
3087
				} else {
3088
					user_error("$relation is not a relation/field on ".get_class($component), E_USER_ERROR);
3089
				}
3090
			}
3091
		}
3092
3093
		// Bail if the component is null
3094
		if(!$component) {
3095
			return null;
3096
		}
3097
		if($component->hasMethod($fieldName)) {
3098
			return $component->$fieldName();
3099
		}
3100
		return $component->$fieldName;
3101
	}
3102
3103
	/**
3104
	 * Temporary hack to return an association name, based on class, to get around the mangle
3105
	 * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
3106
	 *
3107
	 * @return String
3108
	 */
3109
	public function getReverseAssociation($className) {
3110
		if (is_array($this->manyMany())) {
3111
			$many_many = array_flip($this->manyMany());
3112
			if (array_key_exists($className, $many_many)) return $many_many[$className];
3113
		}
3114
		if (is_array($this->hasMany())) {
3115
			$has_many = array_flip($this->hasMany());
3116
			if (array_key_exists($className, $has_many)) return $has_many[$className];
3117
		}
3118
		if (is_array($this->hasOne())) {
3119
			$has_one = array_flip($this->hasOne());
3120
			if (array_key_exists($className, $has_one)) return $has_one[$className];
3121
		}
3122
3123
		return false;
3124
	}
3125
3126
	/**
3127
	 * Return all objects matching the filter
3128
	 * sub-classes are automatically selected and included
3129
	 *
3130
	 * @param string $callerClass The class of objects to be returned
3131
	 * @param string|array $filter A filter to be inserted into the WHERE clause.
3132
	 * Supports parameterised queries. See SQLQuery::addWhere() for syntax examples.
3133
	 * @param string|array $sort A sort expression to be inserted into the ORDER
3134
	 * BY clause.  If omitted, self::$default_sort will be used.
3135
	 * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
3136
	 * @param string|array $limit A limit expression to be inserted into the LIMIT clause.
3137
	 * @param string $containerClass The container class to return the results in.
3138
	 *
3139
	 * @todo $containerClass is Ignored, why?
3140
	 *
3141
	 * @return DataList The objects matching the filter, in the class specified by $containerClass
3142
	 */
3143
	public static function get($callerClass = null, $filter = "", $sort = "", $join = "", $limit = null,
3144
			$containerClass = 'DataList') {
3145
3146
		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...
3147
			$callerClass = get_called_class();
3148
			if($callerClass == 'DataObject') {
3149
				throw new \InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
3150
			}
3151
3152
			if($filter || $sort || $join || $limit || ($containerClass != 'DataList')) {
3153
				throw new \InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
3154
					. ' arguments');
3155
			}
3156
3157
			$result = DataList::create(get_called_class());
3158
			$result->setDataModel(DataModel::inst());
3159
			return $result;
3160
		}
3161
3162
		if($join) {
3163
			throw new \InvalidArgumentException(
3164
				'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
3165
			);
3166
		}
3167
3168
		$result = DataList::create($callerClass)->where($filter)->sort($sort);
3169
3170
		if($limit && strpos($limit, ',') !== false) {
3171
			$limitArguments = explode(',', $limit);
3172
			$result = $result->limit($limitArguments[1],$limitArguments[0]);
3173
		} elseif($limit) {
3174
			$result = $result->limit($limit);
3175
		}
3176
3177
		$result->setDataModel(DataModel::inst());
3178
		return $result;
3179
	}
3180
3181
3182
	/**
3183
	 * @deprecated
3184
	 */
3185
	public function Aggregate($class = null) {
3186
		Deprecation::notice('4.0', 'Call aggregate methods on a DataList directly instead. In templates'
3187
			. ' an example of the new syntax is &lt% cached List(Member).max(LastEdited) %&gt instead'
3188
			. ' (check partial-caching.md documentation for more details.)');
3189
3190
		if($class) {
3191
			$list = new DataList($class);
3192
			$list->setDataModel(DataModel::inst());
3193
		} else if(isset($this)) {
3194
			$list = new DataList(get_class($this));
3195
			$list->setDataModel($this->model);
3196
		} else {
3197
			throw new \InvalidArgumentException("DataObject::aggregate() must be called as an instance method or passed"
3198
				. " a classname");
3199
		}
3200
		return $list;
3201
	}
3202
3203
	/**
3204
	 * @deprecated
3205
	 */
3206
	public function RelationshipAggregate($relationship) {
3207
		Deprecation::notice('4.0', 'Call aggregate methods on a relationship directly instead.');
3208
3209
		return $this->$relationship();
3210
	}
3211
3212
	/**
3213
	 * Return the first item matching the given query.
3214
	 * All calls to get_one() are cached.
3215
	 *
3216
	 * @param string $callerClass The class of objects to be returned
3217
	 * @param string|array $filter A filter to be inserted into the WHERE clause.
3218
	 * Supports parameterised queries. See SQLQuery::addWhere() for syntax examples.
3219
	 * @param boolean $cache Use caching
3220
	 * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
3221
	 *
3222
	 * @return DataObject The first item matching the query
3223
	 */
3224
	public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "") {
3225
		$SNG = singleton($callerClass);
3226
3227
		$cacheComponents = array($filter, $orderby, $SNG->extend('cacheKeyComponent'));
3228
		$cacheKey = md5(serialize($cacheComponents));
3229
3230
		// Flush destroyed items out of the cache
3231
		if($cache && isset(DataObject::$_cache_get_one[$callerClass][$cacheKey])
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...
3232
				&& DataObject::$_cache_get_one[$callerClass][$cacheKey] instanceof DataObject
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...
3233
				&& DataObject::$_cache_get_one[$callerClass][$cacheKey]->destroyed) {
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...
3234
3235
			DataObject::$_cache_get_one[$callerClass][$cacheKey] = false;
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...
3236
		}
3237
		if(!$cache || !isset(DataObject::$_cache_get_one[$callerClass][$cacheKey])) {
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...
3238
			$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...
3239
			$item = $dl->First();
3240
3241
			if($cache) {
3242
				DataObject::$_cache_get_one[$callerClass][$cacheKey] = $item;
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...
3243
				if(!DataObject::$_cache_get_one[$callerClass][$cacheKey]) {
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...
3244
					DataObject::$_cache_get_one[$callerClass][$cacheKey] = false;
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...
3245
				}
3246
			}
3247
		}
3248
		return $cache ? DataObject::$_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...
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...
3249
	}
3250
3251
	/**
3252
	 * Flush the cached results for all relations (has_one, has_many, many_many)
3253
	 * Also clears any cached aggregate data.
3254
	 *
3255
	 * @param boolean $persistent When true will also clear persistent data stored in the Cache system.
3256
	 *                            When false will just clear session-local cached data
3257
	 * @return DataObject $this
3258
	 */
3259
	public function flushCache($persistent = true) {
3260
		if($persistent) Aggregate::flushCache($this->class);
3261
3262
		if($this->class == 'DataObject') {
3263
			DataObject::$_cache_get_one = array();
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...
3264
			return $this;
3265
		}
3266
3267
		$classes = ClassInfo::ancestry($this->class);
3268
		foreach($classes as $class) {
3269
			if(isset(DataObject::$_cache_get_one[$class])) unset(DataObject::$_cache_get_one[$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...
3270
		}
3271
3272
		$this->extend('flushCache');
3273
3274
		$this->components = array();
3275
		return $this;
3276
	}
3277
3278
	/**
3279
	 * Flush the get_one global cache and destroy associated objects.
3280
	 */
3281
	public static function flush_and_destroy_cache() {
3282
		if(DataObject::$_cache_get_one) foreach(DataObject::$_cache_get_one as $class => $items) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \DataObject::$_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...
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...
3283
			if(is_array($items)) foreach($items as $item) {
3284
				if($item) $item->destroy();
3285
			}
3286
		}
3287
		DataObject::$_cache_get_one = array();
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...
3288
	}
3289
3290
	/**
3291
	 * Reset all global caches associated with DataObject.
3292
	 */
3293
	public static function reset() {
3294
		self::clear_classname_spec_cache();
3295
		DataObject::$cache_has_own_table = array();
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...
3296
		DataObject::$_cache_db = array();
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...
3297
		DataObject::$_cache_get_one = array();
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...
3298
		DataObject::$_cache_composite_fields = array();
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...
3299
		DataObject::$_cache_is_composite_field = array();
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...
3300
		DataObject::$_cache_custom_database_fields = array();
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...
3301
		DataObject::$_cache_get_class_ancestry = array();
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...
3302
		DataObject::$_cache_field_labels = array();
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...
3303
	}
3304
3305
	/**
3306
	 * Return the given element, searching by ID
3307
	 *
3308
	 * @param string $callerClass The class of the object to be returned
3309
	 * @param int $id The id of the element
3310
	 * @param boolean $cache See {@link get_one()}
3311
	 *
3312
	 * @return DataObject The element
3313
	 */
3314
	public static function get_by_id($callerClass, $id, $cache = true) {
3315
		if(!is_numeric($id)) {
3316
			user_error("DataObject::get_by_id passed a non-numeric ID #$id", E_USER_WARNING);
3317
		}
3318
3319
		// Check filter column
3320
		if(is_subclass_of($callerClass, 'DataObject')) {
3321
			$baseClass = ClassInfo::baseDataClass($callerClass);
3322
			$column = "\"$baseClass\".\"ID\"";
3323
		} else{
3324
			// This simpler code will be used by non-DataObject classes that implement DataObjectInterface
3325
			$column = '"ID"';
3326
		}
3327
3328
		// Relegate to get_one
3329
		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...
3330
	}
3331
3332
	/**
3333
	 * Get the name of the base table for this object
3334
	 */
3335
	public function baseTable() {
3336
		$tableClasses = ClassInfo::dataClassesFor($this->class);
3337
		return array_shift($tableClasses);
3338
	}
3339
3340
	/**
3341
	 * @var Array Parameters used in the query that built this object.
3342
	 * This can be used by decorators (e.g. lazy loading) to
3343
	 * run additional queries using the same context.
3344
	 */
3345
	protected $sourceQueryParams;
3346
3347
	/**
3348
	 * @see $sourceQueryParams
3349
	 * @return array
3350
	 */
3351
	public function getSourceQueryParams() {
3352
		return $this->sourceQueryParams;
3353
	}
3354
3355
	/**
3356
	 * @see $sourceQueryParams
3357
	 * @param array
3358
	 */
3359
	public function setSourceQueryParams($array) {
3360
		$this->sourceQueryParams = $array;
3361
	}
3362
3363
	/**
3364
	 * @see $sourceQueryParams
3365
	 * @param array
3366
	 */
3367
	public function setSourceQueryParam($key, $value) {
3368
		$this->sourceQueryParams[$key] = $value;
3369
	}
3370
3371
	/**
3372
	 * @see $sourceQueryParams
3373
	 * @return Mixed
3374
	 */
3375
	public function getSourceQueryParam($key) {
3376
		if(isset($this->sourceQueryParams[$key])) return $this->sourceQueryParams[$key];
3377
		else return null;
3378
	}
3379
3380
	//-------------------------------------------------------------------------------------------//
3381
3382
	/**
3383
	 * Return the database indexes on this table.
3384
	 * This array is indexed by the name of the field with the index, and
3385
	 * the value is the type of index.
3386
	 */
3387
	public function databaseIndexes() {
3388
		$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...
3389
		$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...
3390
		$sort = $this->uninherited('default_sort',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...
3391
		//$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...
3392
3393
		$indexes = array();
3394
3395
		if($has_one) {
3396
			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...
3397
				$indexes[$relationshipName . 'ID'] = true;
3398
			}
3399
		}
3400
3401
		if($classIndexes) {
3402
			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...
3403
				$indexes[$indexName] = $indexType;
3404
			}
3405
		}
3406
3407
		if ($sort && is_string($sort)) {
3408
			$sort = preg_split('/,(?![^()]*+\\))/', $sort);
3409
3410
			foreach ($sort as $value) {
3411
				try {
3412
					list ($table, $column) = $this->parseSortColumn(trim($value));
3413
3414
					$table = trim($table, '"');
3415
					$column = trim($column, '"');
3416
3417
					if ($table && strtolower($table) !== strtolower($this->class)) {
3418
						continue;
3419
					}
3420
3421
					if ($this->hasOwnTableDatabaseField($column) && !array_key_exists($column, $indexes)) {
3422
						$indexes[$column] = true;
3423
					}
3424
				} catch (InvalidArgumentException $e) { }
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
3425
			}
3426
		}
3427
3428
		if(get_parent_class($this) == "DataObject") {
3429
			$indexes['ClassName'] = true;
3430
		}
3431
3432
		return $indexes;
3433
	}
3434
3435
	/**
3436
	 * Parses a specified column into a sort field and direction
3437
	 *
3438
	 * @param string $column String to parse containing the column name
3439
	 * @return array Resolved table and column.
3440
	 */
3441
	protected function parseSortColumn($column) {
3442
		// Parse column specification, considering possible ansi sql quoting
3443
		// Note that table prefix is allowed, but discarded
3444
		if(preg_match('/^("?(?<table>[^"\s]+)"?\\.)?"?(?<column>[^"\s]+)"?(\s+(?<direction>((asc)|(desc))(ending)?))?$/i', $column, $match)) {
3445
			$table = $match['table'];
3446
			$column = $match['column'];
3447
		} else {
3448
			throw new InvalidArgumentException("Invalid sort() column");
3449
		}
3450
3451
		return array($table, $column);
3452
	}
3453
3454
	/**
3455
	 * Check the database schema and update it as necessary.
3456
	 *
3457
	 * @uses DataExtension->augmentDatabase()
3458
	 */
3459
	public function requireTable() {
3460
		// Only build the table if we've actually got fields
3461
		$fields = self::database_fields($this->class);
3462
		$extensions = self::database_extensions($this->class);
3463
3464
		$indexes = $this->databaseIndexes();
3465
3466
		// Validate relationship configuration
3467
		$this->validateModelDefinitions();
3468
3469
		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...
3470
			$hasAutoIncPK = ($this->class == ClassInfo::baseDataClass($this->class));
3471
			DB::require_table($this->class, $fields, $indexes, $hasAutoIncPK, $this->stat('create_table_options'),
3472
				$extensions);
3473
		} else {
3474
			DB::dont_require_table($this->class);
3475
		}
3476
3477
		// Build any child tables for many_many items
3478
		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...
3479
			$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...
3480
			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...
3481
				// Build field list
3482
				$manymanyFields = array(
3483
					"{$this->class}ID" => "Int",
3484
				(($this->class == $childClass) ? "ChildID" : "{$childClass}ID") => "Int",
3485
				);
3486
				if(isset($extras[$relationship])) {
3487
					$manymanyFields = array_merge($manymanyFields, $extras[$relationship]);
3488
				}
3489
3490
				// Build index list
3491
				$manymanyIndexes = array(
3492
					"{$this->class}ID" => true,
3493
				(($this->class == $childClass) ? "ChildID" : "{$childClass}ID") => true,
3494
				);
3495
3496
				DB::require_table("{$this->class}_$relationship", $manymanyFields, $manymanyIndexes, true, null,
3497
					$extensions);
3498
			}
3499
		}
3500
3501
		// Let any extentions make their own database fields
3502
		$this->extend('augmentDatabase', $dummy);
3503
	}
3504
3505
	/**
3506
	 * Validate that the configured relations for this class use the correct syntaxes
3507
	 * @throws LogicException
3508
	 */
3509
	protected function validateModelDefinitions() {
3510
		$modelDefinitions = array(
3511
			'db' => Config::inst()->get($this->class, 'db', Config::UNINHERITED),
3512
			'has_one' => Config::inst()->get($this->class, 'has_one', Config::UNINHERITED),
3513
			'has_many' => Config::inst()->get($this->class, 'has_many', Config::UNINHERITED),
3514
			'belongs_to' => Config::inst()->get($this->class, 'belongs_to', Config::UNINHERITED),
3515
			'many_many' => Config::inst()->get($this->class, 'many_many', Config::UNINHERITED),
3516
			'belongs_many_many' => Config::inst()->get($this->class, 'belongs_many_many', Config::UNINHERITED),
3517
			'many_many_extraFields' => Config::inst()->get($this->class, 'many_many_extraFields', Config::UNINHERITED)
3518
		);
3519
3520
		foreach($modelDefinitions as $defType => $relations) {
3521
			if( ! $relations) continue;
3522
3523
			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...
3524
				if($defType === 'many_many_extraFields') {
3525
					if(!is_array($v)) {
3526
						throw new LogicException("$this->class::\$many_many_extraFields has a bad entry: "
3527
							. var_export($k, true) . " => " . var_export($v, true)
3528
							. ". Each many_many_extraFields entry should map to a field specification array.");
3529
					}
3530
				} else {
3531
					if(!is_string($k) || is_numeric($k) || !is_string($v)) {
3532
						throw new LogicException("$this->class::$defType has a bad entry: "
3533
							. var_export($k, true). " => " . var_export($v, true) . ".  Each map key should be a
3534
							 relationship name, and the map value should be the data class to join to.");
3535
					}
3536
				}
3537
			}
3538
		}
3539
	}
3540
3541
	/**
3542
	 * Add default records to database. This function is called whenever the
3543
	 * database is built, after the database tables have all been created. Overload
3544
	 * this to add default records when the database is built, but make sure you
3545
	 * call parent::requireDefaultRecords().
3546
	 *
3547
	 * @uses DataExtension->requireDefaultRecords()
3548
	 */
3549
	public function requireDefaultRecords() {
3550
		$defaultRecords = $this->config()->get('default_records', Config::UNINHERITED);
3551
3552
		if(!empty($defaultRecords)) {
3553
			$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...
3554
			if(!$hasData) {
3555
				$className = $this->class;
3556
				foreach($defaultRecords as $record) {
3557
					$obj = $this->model->$className->newObject($record);
3558
					$obj->write();
3559
				}
3560
				DB::alteration_message("Added default records to $className table","created");
3561
			}
3562
		}
3563
3564
		// Let any extentions make their own database default data
3565
		$this->extend('requireDefaultRecords', $dummy);
3566
	}
3567
3568
	/**
3569
	 * Returns fields bu traversing the class heirachy in a bottom-up direction.
3570
	 *
3571
	 * Needed to avoid getCMSFields being empty when customDatabaseFields overlooks
3572
	 * the inheritance chain of the $db array, where a child data object has no $db array,
3573
	 * but still needs to know the properties of its parent. This should be merged into databaseFields or
3574
	 * customDatabaseFields.
3575
	 *
3576
	 * @todo review whether this is still needed after recent API changes
3577
	 */
3578
	public function inheritedDatabaseFields() {
3579
		$fields     = array();
3580
		$currentObj = $this->class;
3581
3582
		while($currentObj != 'DataObject') {
3583
			$fields     = array_merge($fields, self::custom_database_fields($currentObj));
3584
			$currentObj = get_parent_class($currentObj);
3585
		}
3586
3587
		return (array) $fields;
3588
	}
3589
3590
	/**
3591
	 * Get the default searchable fields for this object, as defined in the
3592
	 * $searchable_fields list. If searchable fields are not defined on the
3593
	 * data object, uses a default selection of summary fields.
3594
	 *
3595
	 * @return array
3596
	 */
3597
	public function searchableFields() {
3598
		// can have mixed format, need to make consistent in most verbose form
3599
		$fields = $this->stat('searchable_fields');
3600
		$labels = $this->fieldLabels();
3601
3602
		// fallback to summary fields (unless empty array is explicitly specified)
3603
		if( ! $fields && ! is_array($fields)) {
3604
			$summaryFields = array_keys($this->summaryFields());
3605
			$fields = array();
3606
3607
			// remove the custom getters as the search should not include them
3608
			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...
3609
				foreach($summaryFields as $key => $name) {
3610
					$spec = $name;
3611
3612
					// Extract field name in case this is a method called on a field (e.g. "Date.Nice")
3613
					if(($fieldPos = strpos($name, '.')) !== false) {
3614
						$name = substr($name, 0, $fieldPos);
3615
					}
3616
3617
					if($this->hasDatabaseField($name)) {
3618
						$fields[] = $name;
3619
					} elseif($this->relObject($spec)) {
3620
						$fields[] = $spec;
3621
					}
3622
				}
3623
			}
3624
		}
3625
3626
		// we need to make sure the format is unified before
3627
		// augmenting fields, so extensions can apply consistent checks
3628
		// but also after augmenting fields, because the extension
3629
		// might use the shorthand notation as well
3630
3631
		// rewrite array, if it is using shorthand syntax
3632
		$rewrite = array();
3633
		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...
3634
			$identifer = (is_int($name)) ? $specOrName : $name;
3635
3636
			if(is_int($name)) {
3637
				// 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...
3638
				$rewrite[$identifer] = array();
3639
			} elseif(is_array($specOrName)) {
3640
				// 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...
3641
				//   'filter => 'ExactMatchFilter',
3642
				//   '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...
3643
				//   '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...
3644
				// ))
3645
				$rewrite[$identifer] = array_merge(
3646
					array('filter' => $this->relObject($identifer)->stat('default_search_filter_class')),
3647
					(array)$specOrName
3648
				);
3649
			} else {
3650
				// 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...
3651
				$rewrite[$identifer] = array(
3652
					'filter' => $specOrName,
3653
				);
3654
			}
3655
			if(!isset($rewrite[$identifer]['title'])) {
3656
				$rewrite[$identifer]['title'] = (isset($labels[$identifer]))
3657
					? $labels[$identifer] : FormField::name_to_label($identifer);
3658
			}
3659
			if(!isset($rewrite[$identifer]['filter'])) {
3660
				$rewrite[$identifer]['filter'] = 'PartialMatchFilter';
3661
			}
3662
		}
3663
3664
		$fields = $rewrite;
3665
3666
		// apply DataExtensions if present
3667
		$this->extend('updateSearchableFields', $fields);
3668
3669
		return $fields;
3670
	}
3671
3672
	/**
3673
	 * Get any user defined searchable fields labels that
3674
	 * exist. Allows overriding of default field names in the form
3675
	 * interface actually presented to the user.
3676
	 *
3677
	 * The reason for keeping this separate from searchable_fields,
3678
	 * which would be a logical place for this functionality, is to
3679
	 * avoid bloating and complicating the configuration array. Currently
3680
	 * much of this system is based on sensible defaults, and this property
3681
	 * would generally only be set in the case of more complex relationships
3682
	 * between data object being required in the search interface.
3683
	 *
3684
	 * Generates labels based on name of the field itself, if no static property
3685
	 * {@link self::field_labels} exists.
3686
	 *
3687
	 * @uses $field_labels
3688
	 * @uses FormField::name_to_label()
3689
	 *
3690
	 * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
3691
	 *
3692
	 * @return array|string Array of all element labels if no argument given, otherwise the label of the field
3693
	 */
3694
	public function fieldLabels($includerelations = true) {
3695
		$cacheKey = $this->class . '_' . $includerelations;
3696
3697
		if(!isset(self::$_cache_field_labels[$cacheKey])) {
3698
			$customLabels = $this->stat('field_labels');
3699
			$autoLabels = array();
3700
3701
			// get all translated static properties as defined in i18nCollectStatics()
3702
			$ancestry = ClassInfo::ancestry($this->class);
3703
			$ancestry = array_reverse($ancestry);
3704
			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...
3705
				if($ancestorClass == 'ViewableData') break;
3706
				$types = array(
3707
					'db'        => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
3708
				);
3709
				if($includerelations){
3710
					$types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
3711
					$types['has_many'] = (array)Config::inst()->get($ancestorClass, 'has_many', Config::UNINHERITED);
3712
					$types['many_many'] = (array)Config::inst()->get($ancestorClass, 'many_many', Config::UNINHERITED);
3713
					$types['belongs_many_many'] = (array)Config::inst()->get($ancestorClass, 'belongs_many_many', Config::UNINHERITED);
3714
				}
3715
				foreach($types as $type => $attrs) {
3716
					foreach($attrs as $name => $spec) {
3717
						$autoLabels[$name] = _t("{$ancestorClass}.{$type}_{$name}",FormField::name_to_label($name));
3718
					}
3719
				}
3720
			}
3721
3722
			$labels = array_merge((array)$autoLabels, (array)$customLabels);
3723
			$this->extend('updateFieldLabels', $labels);
3724
			self::$_cache_field_labels[$cacheKey] = $labels;
3725
		}
3726
3727
		return self::$_cache_field_labels[$cacheKey];
3728
	}
3729
3730
	/**
3731
	 * Get a human-readable label for a single field,
3732
	 * see {@link fieldLabels()} for more details.
3733
	 *
3734
	 * @uses fieldLabels()
3735
	 * @uses FormField::name_to_label()
3736
	 *
3737
	 * @param string $name Name of the field
3738
	 * @return string Label of the field
3739
	 */
3740
	public function fieldLabel($name) {
3741
		$labels = $this->fieldLabels();
3742
		return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name);
3743
	}
3744
3745
	/**
3746
	 * Get the default summary fields for this object.
3747
	 *
3748
	 * @todo use the translation apparatus to return a default field selection for the language
3749
	 *
3750
	 * @return array
3751
	 */
3752
	public function summaryFields() {
3753
		$fields = $this->stat('summary_fields');
3754
3755
		// if fields were passed in numeric array,
3756
		// convert to an associative array
3757
		if($fields && array_key_exists(0, $fields)) {
3758
			$fields = array_combine(array_values($fields), array_values($fields));
3759
		}
3760
3761
		if (!$fields) {
3762
			$fields = array();
3763
			// try to scaffold a couple of usual suspects
3764
			if ($this->hasField('Name')) $fields['Name'] = 'Name';
3765
			if ($this->hasDataBaseField('Title')) $fields['Title'] = 'Title';
3766
			if ($this->hasField('Description')) $fields['Description'] = 'Description';
3767
			if ($this->hasField('FirstName')) $fields['FirstName'] = 'First Name';
3768
		}
3769
		$this->extend("updateSummaryFields", $fields);
3770
3771
		// Final fail-over, just list ID field
3772
		if(!$fields) $fields['ID'] = 'ID';
3773
3774
		// Localize fields (if possible)
3775
		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...
3776
			// only attempt to localize if the label definition is the same as the field name.
3777
			// this will preserve any custom labels set in the summary_fields configuration
3778
			if(isset($fields[$name]) && $name === $fields[$name]) {
3779
				$fields[$name] = $label;
3780
			}
3781
		}
3782
3783
		return $fields;
3784
	}
3785
3786
	/**
3787
	 * Defines a default list of filters for the search context.
3788
	 *
3789
	 * If a filter class mapping is defined on the data object,
3790
	 * it is constructed here. Otherwise, the default filter specified in
3791
	 * {@link DBField} is used.
3792
	 *
3793
	 * @todo error handling/type checking for valid FormField and SearchFilter subclasses?
3794
	 *
3795
	 * @return array
3796
	 */
3797
	public function defaultSearchFilters() {
3798
		$filters = array();
3799
3800
		foreach($this->searchableFields() as $name => $spec) {
3801
			$filterClass = $spec['filter'];
3802
3803
			if($spec['filter'] instanceof SearchFilter) {
3804
				$filters[$name] = $spec['filter'];
3805
			} else {
3806
				$class = $spec['filter'];
3807
3808
				if(!is_subclass_of($spec['filter'], 'SearchFilter')) {
3809
					$class = 'PartialMatchFilter';
3810
				}
3811
3812
				$filters[$name] = new $class($name);
3813
			}
3814
		}
3815
3816
		return $filters;
3817
	}
3818
3819
	/**
3820
	 * @return boolean True if the object is in the database
3821
	 */
3822
	public function isInDB() {
3823
		return is_numeric( $this->ID ) && $this->ID > 0;
3824
	}
3825
3826
	/*
3827
	 * @ignore
3828
	 */
3829
	private static $subclass_access = true;
3830
3831
	/**
3832
	 * Temporarily disable subclass access in data object qeur
3833
	 */
3834
	public static function disable_subclass_access() {
3835
		self::$subclass_access = false;
3836
	}
3837
	public static function enable_subclass_access() {
3838
		self::$subclass_access = true;
3839
	}
3840
3841
	//-------------------------------------------------------------------------------------------//
3842
3843
	/**
3844
	 * Database field definitions.
3845
	 * This is a map from field names to field type. The field
3846
	 * type should be a class that extends .
3847
	 * @var array
3848
	 * @config
3849
	 */
3850
	private static $db = null;
3851
3852
	/**
3853
	 * Use a casting object for a field. This is a map from
3854
	 * field name to class name of the casting object.
3855
	 * @var array
3856
	 */
3857
	private static $casting = array(
3858
		"ID" => 'Int',
3859
		"ClassName" => 'Varchar',
3860
		"LastEdited" => "SS_Datetime",
3861
		"Created" => "SS_Datetime",
3862
		"Title" => 'Text',
3863
	);
3864
3865
	/**
3866
	 * Specify custom options for a CREATE TABLE call.
3867
	 * Can be used to specify a custom storage engine for specific database table.
3868
	 * All options have to be keyed for a specific database implementation,
3869
	 * identified by their class name (extending from {@link SS_Database}).
3870
	 *
3871
	 * <code>
3872
	 * array(
3873
	 *  'MySQLDatabase' => 'ENGINE=MyISAM'
3874
	 * )
3875
	 * </code>
3876
	 *
3877
	 * Caution: This API is experimental, and might not be
3878
	 * included in the next major release. Please use with care.
3879
	 *
3880
	 * @var array
3881
	 * @config
3882
	 */
3883
	private static $create_table_options = array(
3884
		'MySQLDatabase' => 'ENGINE=InnoDB'
3885
	);
3886
3887
	/**
3888
	 * If a field is in this array, then create a database index
3889
	 * on that field. This is a map from fieldname to index type.
3890
	 * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
3891
	 *
3892
	 * @var array
3893
	 * @config
3894
	 */
3895
	private static $indexes = null;
3896
3897
	/**
3898
	 * Inserts standard column-values when a DataObject
3899
	 * is instanciated. Does not insert default records {@see $default_records}.
3900
	 * This is a map from fieldname to default value.
3901
	 *
3902
	 *  - If you would like to change a default value in a sub-class, just specify it.
3903
	 *  - If you would like to disable the default value given by a parent class, set the default value to 0,'',
3904
	 *    or false in your subclass.  Setting it to null won't work.
3905
	 *
3906
	 * @var array
3907
	 * @config
3908
	 */
3909
	private static $defaults = null;
3910
3911
	/**
3912
	 * Multidimensional array which inserts default data into the database
3913
	 * on a db/build-call as long as the database-table is empty. Please use this only
3914
	 * for simple constructs, not for SiteTree-Objects etc. which need special
3915
	 * behaviour such as publishing and ParentNodes.
3916
	 *
3917
	 * Example:
3918
	 * array(
3919
	 *  array('Title' => "DefaultPage1", 'PageTitle' => 'page1'),
3920
	 *  array('Title' => "DefaultPage2")
3921
	 * ).
3922
	 *
3923
	 * @var array
3924
	 * @config
3925
	 */
3926
	private static $default_records = null;
3927
3928
	/**
3929
	 * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a
3930
	 * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class.
3931
	 *
3932
	 * Note that you cannot have a has_one and belongs_to relationship with the same name.
3933
	 *
3934
	 *	@var array
3935
	 * @config
3936
	 */
3937
	private static $has_one = null;
3938
3939
	/**
3940
	 * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.
3941
	 *
3942
	 * This does not actually create any data structures, but allows you to query the other object in a one-to-one
3943
	 * relationship from the child object. If you have multiple belongs_to links to another object you can use the
3944
	 * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use.
3945
	 *
3946
	 * Note that you cannot have a has_one and belongs_to relationship with the same name.
3947
	 *
3948
	 * @var array
3949
	 * @config
3950
	 */
3951
	private static $belongs_to;
3952
3953
	/**
3954
	 * This defines a one-to-many relationship. It is a map of component name to the remote data class.
3955
	 *
3956
	 * This relationship type does not actually create a data structure itself - you need to define a matching $has_one
3957
	 * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this
3958
	 * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show
3959
	 * which foreign key to use.
3960
	 *
3961
	 * @var array
3962
	 * @config
3963
	 */
3964
	private static $has_many = null;
3965
3966
	/**
3967
	 * many-many relationship definitions.
3968
	 * This is a map from component name to data type.
3969
	 * @var array
3970
	 * @config
3971
	 */
3972
	private static $many_many = null;
3973
3974
	/**
3975
	 * Extra fields to include on the connecting many-many table.
3976
	 * This is a map from field name to field type.
3977
	 *
3978
	 * Example code:
3979
	 * <code>
3980
	 * public static $many_many_extraFields = array(
3981
	 *  'Members' => array(
3982
	 *			'Role' => 'Varchar(100)'
3983
	 *		)
3984
	 * );
3985
	 * </code>
3986
	 *
3987
	 * @var array
3988
	 * @config
3989
	 */
3990
	private static $many_many_extraFields = null;
3991
3992
	/**
3993
	 * The inverse side of a many-many relationship.
3994
	 * This is a map from component name to data type.
3995
	 * @var array
3996
	 * @config
3997
	 */
3998
	private static $belongs_many_many = null;
3999
4000
	/**
4001
	 * The default sort expression. This will be inserted in the ORDER BY
4002
	 * clause of a SQL query if no other sort expression is provided.
4003
	 * @var string
4004
	 * @config
4005
	 */
4006
	private static $default_sort = null;
4007
4008
	/**
4009
	 * Default list of fields that can be scaffolded by the ModelAdmin
4010
	 * search interface.
4011
	 *
4012
	 * Overriding the default filter, with a custom defined filter:
4013
	 * <code>
4014
	 *  static $searchable_fields = array(
4015
	 *     "Name" => "PartialMatchFilter"
4016
	 *  );
4017
	 * </code>
4018
	 *
4019
	 * Overriding the default form fields, with a custom defined field.
4020
	 * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}.
4021
	 * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}.
4022
	 * <code>
4023
	 *  static $searchable_fields = array(
4024
	 *    "Name" => array(
4025
	 *      "field" => "TextField"
4026
	 *    )
4027
	 *  );
4028
	 * </code>
4029
	 *
4030
	 * Overriding the default form field, filter and title:
4031
	 * <code>
4032
	 *  static $searchable_fields = array(
4033
	 *    "Organisation.ZipCode" => array(
4034
	 *      "field" => "TextField",
4035
	 *      "filter" => "PartialMatchFilter",
4036
	 *      "title" => 'Organisation ZIP'
4037
	 *    )
4038
	 *  );
4039
	 * </code>
4040
	 * @config
4041
	 */
4042
	private static $searchable_fields = null;
4043
4044
	/**
4045
	 * User defined labels for searchable_fields, used to override
4046
	 * default display in the search form.
4047
	 * @config
4048
	 */
4049
	private static $field_labels = null;
4050
4051
	/**
4052
	 * Provides a default list of fields to be used by a 'summary'
4053
	 * view of this object.
4054
	 * @config
4055
	 */
4056
	private static $summary_fields = null;
4057
4058
	/**
4059
	 * Provides a list of allowed methods that can be called via RESTful api.
4060
	 */
4061
	public static $allowed_actions = null;
4062
4063
	/**
4064
	 * Collect all static properties on the object
4065
	 * which contain natural language, and need to be translated.
4066
	 * The full entity name is composed from the class name and a custom identifier.
4067
	 *
4068
	 * @return array A numerical array which contains one or more entities in array-form.
4069
	 * Each numeric entity array contains the "arguments" for a _t() call as array values:
4070
	 * $entity, $string, $priority, $context.
4071
	 */
4072
	public function provideI18nEntities() {
4073
		$entities = array();
4074
4075
		$entities["{$this->class}.SINGULARNAME"] = array(
4076
			$this->singular_name(),
4077
4078
			'Singular name of the object, used in dropdowns and to generally identify a single object in the interface'
4079
		);
4080
4081
		$entities["{$this->class}.PLURALNAME"] = array(
4082
			$this->plural_name(),
4083
4084
			'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the'
4085
			. ' interface'
4086
		);
4087
4088
		return $entities;
4089
	}
4090
4091
	/**
4092
	 * Returns true if the given method/parameter has a value
4093
	 * (Uses the DBField::hasValue if the parameter is a database field)
4094
	 *
4095
	 * @param string $field The field name
4096
	 * @param array $arguments
4097
	 * @param bool $cache
4098
	 * @return boolean
4099
	 */
4100
	public function hasValue($field, $arguments = null, $cache = true) {
4101
		// has_one fields should not use dbObject to check if a value is given
4102
		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...
4103
			return $obj->exists();
4104
		} else {
4105
			return parent::hasValue($field, $arguments, $cache);
4106
		}
4107
	}
4108
4109
}
4110