Completed
Push — 3.7 ( 81b2d8...ef0909 )
by
unknown
09:42
created

DataObject::cache_composite_fields()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 2
nop 1
dl 0
loc 19
rs 9.0111
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 ManyManyList) { //many-to-many relation
590
                $extraFieldNames = $relations->getExtraFields();
591
592
                if ($relations->Count() > 0) {  //with more than one thing it is related to
593
					foreach($relations as $relation) {
594
                        // Merge extra fields
595
                        $extraFields = array();
596
                        foreach ($extraFieldNames as $fieldName => $fieldType) {
597
                            $extraFields[$fieldName] = $relation->getField($fieldName);
598
                        }
599
                        $destinationObject->$name()->add($relation, $extraFields);
600
                    }
601
                }
602
            } else if ($relations instanceOf RelationList) {   //many-to-something relation
603
				if ($relations->Count() > 0) {  //with more than one thing it is related to
604
					foreach($relations as $relation) {
605
						$destinationObject->$name()->add($relation);
606
					}
607
				}
608
			} else {    //one-to-one relation
609
				$destinationObject->{"{$name}ID"} = $relations->ID;
610
			}
611
		}
612
	}
613
614
	public function getObsoleteClassName() {
615
		$className = $this->getField("ClassName");
616
		if (!ClassInfo::exists($className)) return $className;
617
	}
618
619
	public function getClassName() {
620
		$className = $this->getField("ClassName");
621
		if (!ClassInfo::exists($className)) return get_class($this);
622
		return $className;
623
	}
624
625
	/**
626
	 * Set the ClassName attribute. {@link $class} is also updated.
627
	 * Warning: This will produce an inconsistent record, as the object
628
	 * instance will not automatically switch to the new subclass.
629
	 * Please use {@link newClassInstance()} for this purpose,
630
	 * or destroy and reinstanciate the record.
631
	 *
632
	 * @param string $className The new ClassName attribute (a subclass of {@link DataObject})
633
	 * @return DataObject $this
634
	 */
635
	public function setClassName($className) {
636
		$className = trim($className);
637
		if(!$className || !is_subclass_of($className, 'DataObject')) return;
638
639
		$this->class = $className;
640
		$this->setField("ClassName", $className);
641
		return $this;
642
	}
643
644
	/**
645
	 * Create a new instance of a different class from this object's record.
646
	 * This is useful when dynamically changing the type of an instance. Specifically,
647
	 * it ensures that the instance of the class is a match for the className of the
648
	 * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName}
649
	 * property manually before calling this method, as it will confuse change detection.
650
	 *
651
	 * If the new class is different to the original class, defaults are populated again
652
	 * because this will only occur automatically on instantiation of a DataObject if
653
	 * there is no record, or the record has no ID. In this case, we do have an ID but
654
	 * we still need to repopulate the defaults.
655
	 *
656
	 * @param string $newClassName The name of the new class
657
	 *
658
	 * @return DataObject The new instance of the new class, The exact type will be of the class name provided.
659
	 */
660
	public function newClassInstance($newClassName) {
661
		$originalClass = $this->ClassName;
662
		$newInstance = new $newClassName(array_merge(
663
			$this->record,
664
			array(
665
				'ClassName' => $originalClass,
666
				'RecordClassName' => $originalClass,
667
			)
668
		), false, $this->model);
669
670
		if($newClassName != $originalClass) {
671
			$newInstance->setClassName($newClassName);
672
			$newInstance->populateDefaults();
673
			$newInstance->forceChange();
674
		}
675
676
		return $newInstance;
677
	}
678
679
	/**
680
	 * Adds methods from the extensions.
681
	 * Called by Object::__construct() once per class.
682
	 */
683
	public function defineMethods() {
684
		parent::defineMethods();
685
686
		// Define the extra db fields - this is only necessary for extensions added in the
687
		// class definition.  Object::add_extension() will call this at definition time for
688
		// those objects, which is a better mechanism.  Perhaps extensions defined inside the
689
		// class def can somehow be applied at definiton time also?
690
		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...
691
			if(!$instance->class) {
692
				$class = get_class($instance);
693
				user_error("DataObject::defineMethods(): Please ensure {$class}::__construct() calls"
694
					. " parent::__construct()", E_USER_ERROR);
695
			}
696
		}
697
698
		if($this->class == 'DataObject') return;
699
700
		// Set up accessors for joined items
701
		if($manyMany = $this->manyMany()) {
702
			foreach($manyMany as $relationship => $class) {
703
				$this->addWrapperMethod($relationship, 'getManyManyComponents');
704
			}
705
		}
706
		if($hasMany = $this->hasMany()) {
707
708
			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...
709
				$this->addWrapperMethod($relationship, 'getComponents');
710
			}
711
712
		}
713
		if($hasOne = $this->hasOne()) {
714
			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...
715
				$this->addWrapperMethod($relationship, 'getComponent');
716
			}
717
		}
718
		if($belongsTo = $this->belongsTo()) foreach(array_keys($belongsTo) as $relationship) {
719
			$this->addWrapperMethod($relationship, 'getComponent');
720
		}
721
	}
722
723
	/**
724
	 * Returns true if this object "exists", i.e., has a sensible value.
725
	 * The default behaviour for a DataObject is to return true if
726
	 * the object exists in the database, you can override this in subclasses.
727
	 *
728
	 * @return boolean true if this object exists
729
	 */
730
	public function exists() {
731
		return (isset($this->record['ID']) && $this->record['ID'] > 0);
732
	}
733
734
	/**
735
	 * Returns TRUE if all values (other than "ID") are
736
	 * considered empty (by weak boolean comparison).
737
	 * Only checks for fields listed in {@link custom_database_fields()}
738
	 *
739
	 * @todo Use DBField->hasValue()
740
	 *
741
	 * @return boolean
742
	 */
743
	public function isEmpty(){
744
		$isEmpty = true;
745
		$customFields = self::custom_database_fields(get_class($this));
746
		if($map = $this->toMap()){
747
			foreach($map as $k=>$v){
748
				// only look at custom fields
749
				if(!array_key_exists($k, $customFields)) continue;
750
751
				$dbObj = ($v instanceof DBField) ? $v : $this->dbObject($k);
752
				$isEmpty = ($isEmpty && !$dbObj->exists());
753
			}
754
		}
755
		return $isEmpty;
756
	}
757
758
	/**
759
	 * Get the user friendly singular name of this DataObject.
760
	 * If the name is not defined (by redefining $singular_name in the subclass),
761
	 * this returns the class name.
762
	 *
763
	 * @return string User friendly singular name of this DataObject
764
	 */
765
	public function singular_name() {
766
		if(!$name = $this->stat('singular_name')) {
767
			$name = ucwords(trim(strtolower(preg_replace('/_?([A-Z])/', ' $1', $this->class))));
768
		}
769
770
		return $name;
771
	}
772
773
	/**
774
	 * Get the translated user friendly singular name of this DataObject
775
	 * same as singular_name() but runs it through the translating function
776
	 *
777
	 * Translating string is in the form:
778
	 *     $this->class.SINGULARNAME
779
	 * Example:
780
	 *     Page.SINGULARNAME
781
	 *
782
	 * @return string User friendly translated singular name of this DataObject
783
	 */
784
	public function i18n_singular_name() {
785
		return _t($this->class.'.SINGULARNAME', $this->singular_name());
786
	}
787
788
	/**
789
	 * Get the user friendly plural name of this DataObject
790
	 * If the name is not defined (by renaming $plural_name in the subclass),
791
	 * this returns a pluralised version of the class name.
792
	 *
793
	 * @return string User friendly plural name of this DataObject
794
	 */
795
	public function plural_name() {
796
		if($name = $this->stat('plural_name')) {
797
			return $name;
798
		} else {
799
			$name = $this->singular_name();
800
			//if the penultimate character is not a vowel, replace "y" with "ies"
801
			if (preg_match('/[^aeiou]y$/i', $name)) {
802
				$name = substr($name,0,-1) . 'ie';
803
			}
804
			return ucfirst($name . 's');
805
		}
806
	}
807
808
	/**
809
	 * Get the translated user friendly plural name of this DataObject
810
	 * Same as plural_name but runs it through the translation function
811
	 * Translation string is in the form:
812
	 *      $this->class.PLURALNAME
813
	 * Example:
814
	 *      Page.PLURALNAME
815
	 *
816
	 * @return string User friendly translated plural name of this DataObject
817
	 */
818
	public function i18n_plural_name()
819
	{
820
		$name = $this->plural_name();
821
		return _t($this->class.'.PLURALNAME', $name);
822
	}
823
824
	/**
825
	 * Standard implementation of a title/label for a specific
826
	 * record. Tries to find properties 'Title' or 'Name',
827
	 * and falls back to the 'ID'. Useful to provide
828
	 * user-friendly identification of a record, e.g. in errormessages
829
	 * or UI-selections.
830
	 *
831
	 * Overload this method to have a more specialized implementation,
832
	 * e.g. for an Address record this could be:
833
	 * <code>
834
	 * function getTitle() {
835
	 *   return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
836
	 * }
837
	 * </code>
838
	 *
839
	 * @return string
840
	 */
841
	public function getTitle() {
842
		if($this->hasDatabaseField('Title')) return $this->getField('Title');
843
		if($this->hasDatabaseField('Name')) return $this->getField('Name');
844
845
		return "#{$this->ID}";
846
	}
847
848
	/**
849
	 * Returns the associated database record - in this case, the object itself.
850
	 * This is included so that you can call $dataOrController->data() and get a DataObject all the time.
851
	 *
852
	 * @return DataObject Associated database record
853
	 */
854
	public function data() {
855
		return $this;
856
	}
857
858
	/**
859
	 * Convert this object to a map.
860
	 *
861
	 * @return array The data as a map.
862
	 */
863
	public function toMap() {
864
		$this->loadLazyFields();
865
		return $this->record;
866
	}
867
868
	/**
869
	 * Return all currently fetched database fields.
870
	 *
871
	 * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
872
	 * Obviously, this makes it a lot faster.
873
	 *
874
	 * @return array The data as a map.
875
	 */
876
	public function getQueriedDatabaseFields() {
877
		return $this->record;
878
	}
879
880
	/**
881
	 * Update a number of fields on this object, given a map of the desired changes.
882
	 *
883
	 * The field names can be simple names, or you can use a dot syntax to access $has_one relations.
884
	 * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
885
	 *
886
	 * update() doesn't write the main object, but if you use the dot syntax, it will write()
887
	 * the related objects that it alters.
888
	 *
889
	 * @param array $data A map of field name to data values to update.
890
	 * @return DataObject $this
891
	 */
892
	public function update($data) {
893
		foreach($data as $k => $v) {
894
			// Implement dot syntax for updates
895
			if(strpos($k,'.') !== false) {
896
				$relations = explode('.', $k);
897
				$fieldName = array_pop($relations);
898
				$relObj = $this;
899
				foreach($relations as $i=>$relation) {
900
					// no support for has_many or many_many relationships,
901
					// as the updater wouldn't know which object to write to (or create)
902
					if($relObj->$relation() instanceof DataObject) {
903
						$parentObj = $relObj;
904
						$relObj = $relObj->$relation();
905
						// If the intermediate relationship objects have been created, then write them
906
						if($i<sizeof($relations)-1 && !$relObj->ID || (!$relObj->ID && $parentObj != $this)) {
907
							$relObj->write();
908
							$relatedFieldName = $relation."ID";
909
							$parentObj->$relatedFieldName = $relObj->ID;
910
							$parentObj->write();
911
						}
912
					} else {
913
						user_error(
914
							"DataObject::update(): Can't traverse relationship '$relation'," .
915
							"it has to be a has_one relationship or return a single DataObject",
916
							E_USER_NOTICE
917
						);
918
						// unset relation object so we don't write properties to the wrong object
919
						unset($relObj);
920
						break;
921
					}
922
				}
923
924
				if($relObj) {
925
					$relObj->$fieldName = $v;
926
					$relObj->write();
927
					$relatedFieldName = $relation."ID";
0 ignored issues
show
Bug introduced by
The variable $relation seems to be defined by a foreach iteration on line 899. 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...
928
					$this->$relatedFieldName = $relObj->ID;
929
					$relObj->flushCache();
930
				} else {
931
					user_error("Couldn't follow dot syntax '$k' on '$this->class' object", E_USER_WARNING);
932
				}
933
			} else {
934
				$this->$k = $v;
935
			}
936
		}
937
		return $this;
938
	}
939
940
	/**
941
	 * Pass changes as a map, and try to
942
	 * get automatic casting for these fields.
943
	 * Doesn't write to the database. To write the data,
944
	 * use the write() method.
945
	 *
946
	 * @param array $data A map of field name to data values to update.
947
	 * @return DataObject $this
948
	 */
949
	public function castedUpdate($data) {
950
		foreach($data as $k => $v) {
951
			$this->setCastedField($k,$v);
952
		}
953
		return $this;
954
	}
955
956
	/**
957
	 * Merges data and relations from another object of same class,
958
	 * without conflict resolution. Allows to specify which
959
	 * dataset takes priority in case its not empty.
960
	 * has_one-relations are just transferred with priority 'right'.
961
	 * has_many and many_many-relations are added regardless of priority.
962
	 *
963
	 * Caution: has_many/many_many relations are moved rather than duplicated,
964
	 * meaning they are not connected to the merged object any longer.
965
	 * Caution: Just saves updated has_many/many_many relations to the database,
966
	 * doesn't write the updated object itself (just writes the object-properties).
967
	 * Caution: Does not delete the merged object.
968
	 * Caution: Does now overwrite Created date on the original object.
969
	 *
970
	 * @param $obj DataObject
971
	 * @param $priority String left|right Determines who wins in case of a conflict (optional)
972
	 * @param $includeRelations Boolean Merge any existing relations (optional)
973
	 * @param $overwriteWithEmpty Boolean Overwrite existing left values with empty right values.
974
	 *                            Only applicable with $priority='right'. (optional)
975
	 * @return Boolean
976
	 */
977
	public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false) {
978
		$leftObj = $this;
979
980
		if($leftObj->ClassName != $rightObj->ClassName) {
981
			// we can't merge similiar subclasses because they might have additional relations
982
			user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}'
983
			(expected '{$leftObj->ClassName}').", E_USER_WARNING);
984
			return false;
985
		}
986
987
		if(!$rightObj->ID) {
988
			user_error("DataObject->merge(): Please write your merged-in object to the database before merging,
989
				to make sure all relations are transferred properly.').", E_USER_WARNING);
990
			return false;
991
		}
992
993
		// makes sure we don't merge data like ID or ClassName
994
		$leftData = $leftObj->inheritedDatabaseFields();
995
		$rightData = $rightObj->inheritedDatabaseFields();
996
997
		foreach($rightData as $key=>$rightVal) {
998
			// don't merge conflicting values if priority is 'left'
999
			if($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) continue;
1000
1001
			// don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set)
1002
			if($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) continue;
1003
1004
			// TODO remove redundant merge of has_one fields
1005
			$leftObj->{$key} = $rightObj->{$key};
1006
		}
1007
1008
		// merge relations
1009
		if($includeRelations) {
1010
			if($manyMany = $this->manyMany()) {
1011
				foreach($manyMany as $relationship => $class) {
1012
					$leftComponents = $leftObj->getManyManyComponents($relationship);
1013
					$rightComponents = $rightObj->getManyManyComponents($relationship);
1014
					if($rightComponents && $rightComponents->exists()) {
1015
						$leftComponents->addMany($rightComponents->column('ID'));
1016
					}
1017
					$leftComponents->write();
1018
				}
1019
			}
1020
1021
			if($hasMany = $this->hasMany()) {
1022
				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...
1023
					$leftComponents = $leftObj->getComponents($relationship);
1024
					$rightComponents = $rightObj->getComponents($relationship);
1025
					if($rightComponents && $rightComponents->exists()) {
1026
						$leftComponents->addMany($rightComponents->column('ID'));
1027
					}
1028
					$leftComponents->write();
1029
				}
1030
1031
			}
1032
1033
			if($hasOne = $this->hasOne()) {
1034
				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...
1035
					$leftComponent = $leftObj->getComponent($relationship);
1036
					$rightComponent = $rightObj->getComponent($relationship);
1037
					if($leftComponent->exists() && $rightComponent->exists() && $priority == 'right') {
1038
						$leftObj->{$relationship . 'ID'} = $rightObj->{$relationship . 'ID'};
1039
					}
1040
				}
1041
			}
1042
		}
1043
1044
		return true;
1045
	}
1046
1047
	/**
1048
	 * Forces the record to think that all its data has changed.
1049
	 * Doesn't write to the database. Only sets fields as changed
1050
	 * if they are not already marked as changed.
1051
	 *
1052
	 * @return $this
1053
	 */
1054
	public function forceChange() {
1055
		// Ensure lazy fields loaded
1056
		$this->loadLazyFields();
1057
1058
		// $this->record might not contain the blank values so we loop on $this->inheritedDatabaseFields() as well
1059
		$fieldNames = array_unique(array_merge(
1060
			array_keys($this->record),
1061
			array_keys($this->inheritedDatabaseFields())
1062
		));
1063
1064
		foreach($fieldNames as $fieldName) {
1065
			if(!isset($this->changed[$fieldName])) $this->changed[$fieldName] = self::CHANGE_STRICT;
1066
			// Populate the null values in record so that they actually get written
1067
			if(!isset($this->record[$fieldName])) $this->record[$fieldName] = null;
1068
		}
1069
1070
		// @todo Find better way to allow versioned to write a new version after forceChange
1071
		if($this->isChanged('Version')) unset($this->changed['Version']);
1072
		return $this;
1073
	}
1074
1075
	/**
1076
	 * Validate the current object.
1077
	 *
1078
	 * By default, there is no validation - objects are always valid!  However, you can overload this method in your
1079
	 * DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
1080
	 *
1081
	 * Invalid objects won't be able to be written - a warning will be thrown and no write will occur.  onBeforeWrite()
1082
	 * and onAfterWrite() won't get called either.
1083
	 *
1084
	 * It is expected that you call validate() in your own application to test that an object is valid before
1085
	 * attempting a write, and respond appropriately if it isn't.
1086
	 *
1087
	 * @see {@link ValidationResult}
1088
	 * @return ValidationResult
1089
	 */
1090
	protected function validate() {
1091
		$result = ValidationResult::create();
1092
		$this->extend('validate', $result);
1093
		return $result;
1094
	}
1095
1096
	/**
1097
	 * Public accessor for {@see DataObject::validate()}
1098
	 *
1099
	 * @return ValidationResult
1100
	 */
1101
	public function doValidate() {
1102
		// validate will be public in 4.0
1103
		return $this->validate();
1104
	}
1105
1106
	/**
1107
	 * Event handler called before writing to the database.
1108
	 * You can overload this to clean up or otherwise process data before writing it to the
1109
	 * database.  Don't forget to call parent::onBeforeWrite(), though!
1110
	 *
1111
	 * This called after {@link $this->validate()}, so you can be sure that your data is valid.
1112
	 *
1113
	 * @uses DataExtension->onBeforeWrite()
1114
	 */
1115
	protected function onBeforeWrite() {
1116
		$this->brokenOnWrite = false;
1117
1118
		$dummy = null;
1119
		$this->extend('onBeforeWrite', $dummy);
1120
	}
1121
1122
	/**
1123
	 * Event handler called after writing to the database.
1124
	 * You can overload this to act upon changes made to the data after it is written.
1125
	 * $this->changed will have a record
1126
	 * database.  Don't forget to call parent::onAfterWrite(), though!
1127
	 *
1128
	 * @uses DataExtension->onAfterWrite()
1129
	 */
1130
	protected function onAfterWrite() {
1131
		$dummy = null;
1132
		$this->extend('onAfterWrite', $dummy);
1133
	}
1134
1135
	/**
1136
	 * Event handler called before deleting from the database.
1137
	 * You can overload this to clean up or otherwise process data before delete this
1138
	 * record.  Don't forget to call parent::onBeforeDelete(), though!
1139
	 *
1140
	 * @uses DataExtension->onBeforeDelete()
1141
	 */
1142
	protected function onBeforeDelete() {
1143
		$this->brokenOnDelete = false;
1144
1145
		$dummy = null;
1146
		$this->extend('onBeforeDelete', $dummy);
1147
	}
1148
1149
	protected function onAfterDelete() {
1150
		$this->extend('onAfterDelete');
1151
	}
1152
1153
	/**
1154
	 * Load the default values in from the self::$defaults array.
1155
	 * Will traverse the defaults of the current class and all its parent classes.
1156
	 * Called by the constructor when creating new records.
1157
	 *
1158
	 * @uses DataExtension->populateDefaults()
1159
	 * @return DataObject $this
1160
	 */
1161
	public function populateDefaults() {
1162
		$classes = array_reverse(ClassInfo::ancestry($this));
1163
1164
		foreach($classes as $class) {
1165
			$defaults = Config::inst()->get($class, 'defaults', Config::UNINHERITED);
1166
1167
			if($defaults && !is_array($defaults)) {
1168
				user_error("Bad '$this->class' defaults given: " . var_export($defaults, true),
1169
					E_USER_WARNING);
1170
				$defaults = null;
1171
			}
1172
1173
			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...
1174
				// SRM 2007-03-06: Stricter check
1175
				if(!isset($this->$fieldName) || $this->$fieldName === null) {
1176
					$this->$fieldName = $fieldValue;
1177
				}
1178
				// Set many-many defaults with an array of ids
1179
				if(is_array($fieldValue) && $this->manyManyComponent($fieldName)) {
1180
					$manyManyJoin = $this->$fieldName();
1181
					$manyManyJoin->setByIdList($fieldValue);
1182
				}
1183
			}
1184
			if($class == 'DataObject') {
1185
				break;
1186
			}
1187
		}
1188
1189
		$this->extend('populateDefaults');
1190
		return $this;
1191
	}
1192
1193
	/**
1194
	 * Determine validation of this object prior to write
1195
	 *
1196
	 * @return ValidationException Exception generated by this write, or null if valid
1197
	 */
1198
	protected function validateWrite() {
1199
		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...
1200
			return new ValidationException(
1201
				"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...
1202
				"you need to change the ClassName before you can write it",
1203
				E_USER_WARNING
1204
			);
1205
		}
1206
1207
		if(Config::inst()->get('DataObject', 'validation_enabled')) {
1208
			$result = $this->validate();
1209
			if (!$result->valid()) {
1210
				return new ValidationException(
1211
					$result,
1212
					$result->message(),
1213
					E_USER_WARNING
1214
				);
1215
			}
1216
		}
1217
	}
1218
1219
	/**
1220
	 * Prepare an object prior to write
1221
	 *
1222
	 * @throws ValidationException
1223
	 */
1224
	protected function preWrite() {
1225
		// Validate this object
1226
		if($writeException = $this->validateWrite()) {
1227
			// Used by DODs to clean up after themselves, eg, Versioned
1228
			$this->invokeWithExtensions('onAfterSkippedWrite');
1229
			throw $writeException;
1230
		}
1231
1232
		// Check onBeforeWrite
1233
		$this->brokenOnWrite = true;
1234
		$this->onBeforeWrite();
1235
		if($this->brokenOnWrite) {
1236
			user_error("$this->class has a broken onBeforeWrite() function."
1237
				. " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
1238
		}
1239
	}
1240
1241
	/**
1242
	 * Detects and updates all changes made to this object
1243
	 *
1244
	 * @param bool $forceChanges If set to true, force all fields to be treated as changed
1245
	 * @return bool True if any changes are detected
1246
	 */
1247
	protected function updateChanges($forceChanges = false)
1248
	{
1249
		if($forceChanges) {
1250
			// Force changes, but only for loaded fields
1251
			foreach($this->record as $field => $value) {
1252
				$this->changed[$field] = static::CHANGE_VALUE;
1253
			}
1254
			return true;
1255
		}
1256
		return $this->isChanged();
1257
	}
1258
1259
	/**
1260
	 * Writes a subset of changes for a specific table to the given manipulation
1261
	 *
1262
	 * @param string $baseTable Base table
1263
	 * @param string $now Timestamp to use for the current time
1264
	 * @param bool $isNewRecord Whether this should be treated as a new record write
1265
	 * @param array $manipulation Manipulation to write to
1266
	 * @param string $class Table and Class to select and write to
1267
	 */
1268
	protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class) {
1269
		$manipulation[$class] = array();
1270
1271
		// Extract records for this table
1272
		foreach($this->record as $fieldName => $fieldValue) {
1273
1274
			// Check if this record pertains to this table, and
1275
			// we're not attempting to reset the BaseTable->ID
1276
			if(	empty($this->changed[$fieldName])
1277
				|| ($class === $baseTable && $fieldName === 'ID')
1278
				|| (!self::has_own_table_database_field($class, $fieldName)
1279
					&& !self::is_composite_field($class, $fieldName, false))
1280
			) {
1281
				continue;
1282
			}
1283
1284
1285
			// if database column doesn't correlate to a DBField instance...
1286
			$fieldObj = $this->dbObject($fieldName);
1287
			if(!$fieldObj) {
1288
				$fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName);
1289
			}
1290
1291
			// Ensure DBField is repopulated and written to the manipulation
1292
			$fieldObj->setValue($fieldValue, $this->record);
1293
			$fieldObj->writeToManipulation($manipulation[$class]);
1294
		}
1295
1296
		// Ensure update of Created and LastEdited columns
1297
		if($baseTable === $class) {
1298
			$manipulation[$class]['fields']['LastEdited'] = $now;
1299
			if($isNewRecord) {
1300
				$manipulation[$class]['fields']['Created']
1301
					= empty($this->record['Created'])
1302
						? $now
1303
						: $this->record['Created'];
1304
				$manipulation[$class]['fields']['ClassName'] = $this->class;
1305
			}
1306
		}
1307
1308
		// Inserts done one the base table are performed in another step, so the manipulation should instead
1309
		// attempt an update, as though it were a normal update.
1310
		$manipulation[$class]['command'] = $isNewRecord ? 'insert' : 'update';
1311
		$manipulation[$class]['id'] = $this->record['ID'];
1312
	}
1313
1314
	/**
1315
	 * Ensures that a blank base record exists with the basic fixed fields for this dataobject
1316
	 *
1317
	 * Does nothing if an ID is already assigned for this record
1318
	 *
1319
	 * @param string $baseTable Base table
1320
	 * @param string $now Timestamp to use for the current time
1321
	 */
1322
	protected function writeBaseRecord($baseTable, $now) {
1323
		// Generate new ID if not specified
1324
		if($this->isInDB()) return;
1325
1326
		// Perform an insert on the base table
1327
		$insert = new SQLInsert('"'.$baseTable.'"');
1328
		$insert
1329
			->assign('"Created"', $now)
1330
			->execute();
1331
		$this->changed['ID'] = self::CHANGE_VALUE;
1332
		$this->record['ID'] = DB::get_generated_id($baseTable);
1333
	}
1334
1335
	/**
1336
	 * Generate and write the database manipulation for all changed fields
1337
	 *
1338
	 * @param string $baseTable Base table
1339
	 * @param string $now Timestamp to use for the current time
1340
	 * @param bool $isNewRecord If this is a new record
1341
	 */
1342
	protected function writeManipulation($baseTable, $now, $isNewRecord) {
1343
		// Generate database manipulations for each class
1344
		$manipulation = array();
1345
		foreach($this->getClassAncestry() as $class) {
1346
			if(self::has_own_table($class)) {
1347
				$this->prepareManipulationTable($baseTable, $now, $isNewRecord, $manipulation, $class);
1348
			}
1349
		}
1350
1351
		// Allow extensions to extend this manipulation
1352
		$this->extend('augmentWrite', $manipulation);
1353
1354
		// New records have their insert into the base data table done first, so that they can pass the
1355
		// generated ID on to the rest of the manipulation
1356
		if($isNewRecord) {
1357
			$manipulation[$baseTable]['command'] = 'update';
1358
		}
1359
1360
		// Perform the manipulation
1361
		DB::manipulate($manipulation);
1362
	}
1363
1364
	/**
1365
	 * Writes all changes to this object to the database.
1366
	 *  - It will insert a record whenever ID isn't set, otherwise update.
1367
	 *  - All relevant tables will be updated.
1368
	 *  - $this->onBeforeWrite() gets called beforehand.
1369
	 *  - Extensions such as Versioned will ammend the database-write to ensure that a version is saved.
1370
	 *
1371
	 *  @uses DataExtension->augmentWrite()
1372
	 *
1373
	 * @param boolean $showDebug Show debugging information
1374
	 * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
1375
	 * @param boolean $forceWrite Write to database even if there are no changes
1376
	 * @param boolean $writeComponents Call write() on all associated component instances which were previously
1377
	 *                                 retrieved through {@link getComponent()}, {@link getComponents()} or
1378
	 *                                 {@link getManyManyComponents()} (Default: false)
1379
	 * @return int The ID of the record
1380
	 * @throws ValidationException Exception that can be caught and handled by the calling function
1381
	 */
1382
	public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
1383
		$now = SS_Datetime::now()->Rfc2822();
1384
1385
		// Execute pre-write tasks
1386
		$this->preWrite();
1387
1388
		// Check if we are doing an update or an insert
1389
		$isNewRecord = !$this->isInDB() || $forceInsert;
1390
1391
		// Check changes exist, abort if there are none
1392
		$hasChanges = $this->updateChanges($isNewRecord);
1393
		if($hasChanges || $forceWrite || $isNewRecord) {
1394
1395
			// Ensure Created and LastEdited are populated
1396
			if(!isset($this->record['Created'])) {
1397
				$this->record['Created'] = $now;
1398
			}
1399
			$this->record['LastEdited'] = $now;
1400
			// New records have their insert into the base data table done first, so that they can pass the
1401
			// generated primary key on to the rest of the manipulation
1402
			$baseTable = ClassInfo::baseDataClass($this->class);
1403
			$this->writeBaseRecord($baseTable, $now);
1404
1405
			// Write the DB manipulation for all changed fields
1406
			$this->writeManipulation($baseTable, $now, $isNewRecord);
1407
1408
			// If there's any relations that couldn't be saved before, save them now (we have an ID here)
1409
			$this->writeRelations();
1410
			$this->onAfterWrite();
1411
			$this->changed = array();
1412
		} else {
1413
			if($showDebug) Debug::message("no changes for DataObject");
1414
1415
			// Used by DODs to clean up after themselves, eg, Versioned
1416
			$this->invokeWithExtensions('onAfterSkippedWrite');
1417
		}
1418
1419
		// Write relations as necessary
1420
		if($writeComponents) $this->writeComponents(true);
1421
1422
		// Clears the cache for this object so get_one returns the correct object.
1423
		$this->flushCache();
1424
1425
		return $this->record['ID'];
1426
	}
1427
1428
	/**
1429
	 * Writes cached relation lists to the database, if possible
1430
	 */
1431
	public function writeRelations() {
1432
		if(!$this->isInDB()) return;
1433
1434
		// If there's any relations that couldn't be saved before, save them now (we have an ID here)
1435
		if($this->unsavedRelations) {
1436
			foreach($this->unsavedRelations as $name => $list) {
1437
				$list->changeToList($this->$name());
1438
			}
1439
			$this->unsavedRelations = array();
1440
		}
1441
	}
1442
1443
	/**
1444
	 * Write the cached components to the database. Cached components could refer to two different instances of the
1445
	 * same record.
1446
	 *
1447
	 * @param $recursive Recursively write components
1448
	 * @return DataObject $this
1449
	 */
1450
	public function writeComponents($recursive = false) {
1451
		if(!$this->components) return $this;
1452
1453
		foreach($this->components as $component) {
1454
			$component->write(false, false, false, $recursive);
1455
		}
1456
		return $this;
1457
	}
1458
1459
	/**
1460
	 * Delete this data object.
1461
	 * $this->onBeforeDelete() gets called.
1462
	 * Note that in Versioned objects, both Stage and Live will be deleted.
1463
	 *  @uses DataExtension->augmentSQL()
1464
	 */
1465
	public function delete() {
1466
		$this->brokenOnDelete = true;
1467
		$this->onBeforeDelete();
1468
		if($this->brokenOnDelete) {
1469
			user_error("$this->class has a broken onBeforeDelete() function."
1470
				. " Make sure that you call parent::onBeforeDelete().", E_USER_ERROR);
1471
		}
1472
1473
		// Deleting a record without an ID shouldn't do anything
1474
		if(!$this->ID) throw new LogicException("DataObject::delete() called on a DataObject without an ID");
1475
1476
		// TODO: This is quite ugly.  To improve:
1477
		//  - move the details of the delete code in the DataQuery system
1478
		//  - update the code to just delete the base table, and rely on cascading deletes in the DB to do the rest
1479
		//    obviously, that means getting requireTable() to configure cascading deletes ;-)
1480
		$srcQuery = DataList::create($this->class, $this->model)->where("ID = $this->ID")->dataQuery()->query();
1481
		foreach($srcQuery->queriedTables() as $table) {
1482
			$delete = new SQLDelete("\"$table\"", array('"ID"' => $this->ID));
1483
			$delete->execute();
1484
		}
1485
		// Remove this item out of any caches
1486
		$this->flushCache();
1487
1488
		$this->onAfterDelete();
1489
1490
		$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...
1491
		$this->ID = 0;
1492
	}
1493
1494
	/**
1495
	 * Delete the record with the given ID.
1496
	 *
1497
	 * @param string $className The class name of the record to be deleted
1498
	 * @param int $id ID of record to be deleted
1499
	 */
1500
	public static function delete_by_id($className, $id) {
1501
		$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...
1502
		if($obj) {
1503
			$obj->delete();
1504
		} else {
1505
			user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
1506
		}
1507
	}
1508
1509
	/**
1510
	 * Get the class ancestry, including the current class name.
1511
	 * The ancestry will be returned as an array of class names, where the 0th element
1512
	 * will be the class that inherits directly from DataObject, and the last element
1513
	 * will be the current class.
1514
	 *
1515
	 * @return array Class ancestry
1516
	 */
1517
	public function getClassAncestry() {
1518
		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...
1519
			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...
1520
			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...
1521
				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...
1522
			}
1523
		}
1524
		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...
1525
	}
1526
1527
	/**
1528
	 * Return a component object from a one to one relationship, as a DataObject.
1529
	 * If no component is available, an 'empty component' will be returned for
1530
	 * non-polymorphic relations, or for polymorphic relations with a class set.
1531
	 *
1532
	 * @param string $componentName Name of the component
1533
	 *
1534
	 * @return DataObject The component object. It's exact type will be that of the component.
1535
	 */
1536
	public function getComponent($componentName) {
1537
		if(isset($this->components[$componentName])) {
1538
			return $this->components[$componentName];
1539
		}
1540
1541
		if($class = $this->hasOneComponent($componentName)) {
1542
			$joinField = $componentName . 'ID';
1543
			$joinID    = $this->getField($joinField);
1544
1545
			// Extract class name for polymorphic relations
1546
			if($class === 'DataObject') {
1547
				$class = $this->getField($componentName . 'Class');
1548
				if(empty($class)) return null;
1549
			}
1550
1551
			if($joinID) {
1552
				$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...
1553
			}
1554
1555
			if(empty($component)) {
1556
				$component = $this->model->$class->newObject();
1557
			}
1558
		} elseif($class = $this->belongsToComponent($componentName)) {
1559
1560
			$joinField = $this->getRemoteJoinField($componentName, 'belongs_to', $polymorphic);
1561
			$joinID    = $this->ID;
1562
1563
			if($joinID) {
1564
1565
				$filter = $polymorphic
1566
					? array(
1567
						"{$joinField}ID" => $joinID,
1568
						"{$joinField}Class" => $this->class
1569
					)
1570
					: array(
1571
						$joinField => $joinID
1572
					);
1573
				$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...
1574
			}
1575
1576
			if(empty($component)) {
1577
				$component = $this->model->$class->newObject();
1578
				if($polymorphic) {
1579
					$component->{$joinField.'ID'} = $this->ID;
1580
					$component->{$joinField.'Class'} = $this->class;
1581
				} else {
1582
					$component->$joinField = $this->ID;
1583
				}
1584
			}
1585
		} else {
1586
			throw new Exception("DataObject->getComponent(): Could not find component '$componentName'.");
1587
		}
1588
1589
		$this->components[$componentName] = $component;
1590
		return $component;
1591
	}
1592
1593
	/**
1594
	 * Returns a one-to-many relation as a HasManyList
1595
	 *
1596
	 * @param string $componentName Name of the component
1597
	 * @param string|null $filter Deprecated. A filter to be inserted into the WHERE clause
1598
	 * @param string|null|array $sort Deprecated. A sort expression to be inserted into the ORDER BY clause. If omitted,
1599
	 *                                the static field $default_sort on the component class will be used.
1600
	 * @param string $join Deprecated, use leftJoin($table, $joinClause) instead
1601
	 * @param string|null|array $limit Deprecated. A limit expression to be inserted into the LIMIT clause
1602
	 *
1603
	 * @return HasManyList The components of the one-to-many relationship.
1604
	 */
1605
	public function getComponents($componentName, $filter = null, $sort = null, $join = null, $limit = null) {
1606
		$result = null;
1607
1608
		if(!$componentClass = $this->hasManyComponent($componentName)) {
1609
			user_error("DataObject::getComponents(): Unknown 1-to-many component '$componentName'"
1610
				. " on class '$this->class'", E_USER_ERROR);
1611
		}
1612
1613
		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...
1614
			throw new \InvalidArgumentException(
1615
				'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
1616
			);
1617
		}
1618
1619
		if($filter !== null || $sort !== null || $limit !== null) {
1620
			Deprecation::notice('4.0', 'The $filter, $sort and $limit parameters for DataObject::getComponents()
1621
				have been deprecated. Please manipluate the returned list directly.', Deprecation::SCOPE_GLOBAL);
1622
		}
1623
1624
		// If we haven't been written yet, we can't save these relations, so use a list that handles this case
1625
		if(!$this->ID) {
1626
			if(!isset($this->unsavedRelations[$componentName])) {
1627
				$this->unsavedRelations[$componentName] =
1628
					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 1608 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...
1629
			}
1630
			return $this->unsavedRelations[$componentName];
1631
		}
1632
1633
		// Determine type and nature of foreign relation
1634
		$joinField = $this->getRemoteJoinField($componentName, 'has_many', $polymorphic);
1635
		if($polymorphic) {
1636
			$result = PolymorphicHasManyList::create($componentClass, $joinField, $this->class);
1637
		} else {
1638
			$result = HasManyList::create($componentClass, $joinField);
1639
		}
1640
1641
		if($this->model) $result->setDataModel($this->model);
1642
1643
		return $result
1644
			->forForeignID($this->ID)
1645
			->where($filter)
1646
			->limit($limit)
1647
			->sort($sort);
1648
	}
1649
1650
	/**
1651
	 * @deprecated
1652
	 */
1653
	public function getComponentsQuery($componentName, $filter = "", $sort = "", $join = "", $limit = "") {
1654
		Deprecation::notice('4.0', "Use getComponents to get a filtered DataList for an object's relation");
1655
		return $this->getComponents($componentName, $filter, $sort, $join, $limit);
1656
	}
1657
1658
	/**
1659
	 * Find the foreign class of a relation on this DataObject, regardless of the relation type.
1660
	 *
1661
	 * @param $relationName Relation name.
1662
	 * @return string Class name, or null if not found.
1663
	 */
1664
	public function getRelationClass($relationName) {
1665
		// Go through all relationship configuration fields.
1666
		$candidates = array_merge(
1667
			($relations = Config::inst()->get($this->class, 'has_one')) ? $relations : array(),
1668
			($relations = Config::inst()->get($this->class, 'has_many')) ? $relations : array(),
1669
			($relations = Config::inst()->get($this->class, 'many_many')) ? $relations : array(),
1670
			($relations = Config::inst()->get($this->class, 'belongs_many_many')) ? $relations : array(),
1671
			($relations = Config::inst()->get($this->class, 'belongs_to')) ? $relations : array()
1672
		);
1673
1674
		if (isset($candidates[$relationName])) {
1675
			$remoteClass = $candidates[$relationName];
1676
1677
			// If dot notation is present, extract just the first part that contains the class.
1678
			if(($fieldPos = strpos($remoteClass, '.'))!==false) {
1679
				return substr($remoteClass, 0, $fieldPos);
1680
			}
1681
1682
			// Otherwise just return the class
1683
			return $remoteClass;
1684
		}
1685
1686
		return null;
1687
	}
1688
1689
	/**
1690
	 * Tries to find the database key on another object that is used to store a
1691
	 * relationship to this class. If no join field can be found it defaults to 'ParentID'.
1692
	 *
1693
	 * If the remote field is polymorphic then $polymorphic is set to true, and the return value
1694
	 * is in the form 'Relation' instead of 'RelationID', referencing the composite DBField.
1695
	 *
1696
	 * @param string $component Name of the relation on the current object pointing to the
1697
	 * remote object.
1698
	 * @param string $type the join type - either 'has_many' or 'belongs_to'
1699
	 * @param boolean $polymorphic Flag set to true if the remote join field is polymorphic.
1700
	 * @return string
1701
	 */
1702
	public function getRemoteJoinField($component, $type = 'has_many', &$polymorphic = false) {
1703
		// Extract relation from current object
1704
		if($type === 'has_many') {
1705
			$remoteClass = $this->hasManyComponent($component, false);
1706
		} else {
1707
			$remoteClass = $this->belongsToComponent($component, false);
1708
		}
1709
1710
		if(empty($remoteClass)) {
1711
			throw new Exception("Unknown $type component '$component' on class '$this->class'");
1712
		}
1713
		if(!ClassInfo::exists(strtok($remoteClass, '.'))) {
1714
			throw new Exception(
1715
				"Class '$remoteClass' not found, but used in $type component '$component' on class '$this->class'"
1716
			);
1717
		}
1718
1719
		// If presented with an explicit field name (using dot notation) then extract field name
1720
		$remoteField = null;
1721
		if(strpos($remoteClass, '.') !== false) {
1722
			list($remoteClass, $remoteField) = explode('.', $remoteClass);
1723
		}
1724
1725
		// Reference remote has_one to check against
1726
		$remoteRelations = Config::inst()->get($remoteClass, 'has_one');
1727
1728
		// Without an explicit field name, attempt to match the first remote field
1729
		// with the same type as the current class
1730
		if(empty($remoteField)) {
1731
			// look for remote has_one joins on this class or any parent classes
1732
			$remoteRelationsMap = array_flip($remoteRelations);
1733
			foreach(array_reverse(ClassInfo::ancestry($this)) as $class) {
1734
				if(array_key_exists($class, $remoteRelationsMap)) {
1735
					$remoteField = $remoteRelationsMap[$class];
1736
					break;
1737
				}
1738
			}
1739
		}
1740
1741
		// In case of an indeterminate remote field show an error
1742
		if(empty($remoteField)) {
1743
			$polymorphic = false;
1744
			$message = "No has_one found on class '$remoteClass'";
1745
			if($type == 'has_many') {
1746
				// include a hint for has_many that is missing a has_one
1747
				$message .= ", the has_many relation from '$this->class' to '$remoteClass'";
1748
				$message .= " requires a has_one on '$remoteClass'";
1749
			}
1750
			throw new Exception($message);
1751
		}
1752
1753
		// If given an explicit field name ensure the related class specifies this
1754
		if(empty($remoteRelations[$remoteField])) {
1755
			throw new Exception("Missing expected has_one named '$remoteField'
1756
				on class '$remoteClass' referenced by $type named '$component'
1757
				on class {$this->class}"
1758
			);
1759
		}
1760
1761
		// Inspect resulting found relation
1762
		if($remoteRelations[$remoteField] === 'DataObject') {
1763
			$polymorphic = true;
1764
			return $remoteField; // Composite polymorphic field does not include 'ID' suffix
1765
		} else {
1766
			$polymorphic = false;
1767
			return $remoteField . 'ID';
1768
		}
1769
	}
1770
1771
	/**
1772
	 * Returns a many-to-many component, as a ManyManyList.
1773
	 * @param string $componentName Name of the many-many component
1774
	 * @return ManyManyList The set of components
1775
	 *
1776
	 * @todo Implement query-params
1777
	 */
1778
	public function getManyManyComponents($componentName, $filter = null, $sort = null, $join = null, $limit = null) {
1779
		list($parentClass, $componentClass, $parentField, $componentField, $table)
1780
			= $this->manyManyComponent($componentName);
1781
1782
		if($filter !== null || $sort !== null || $join !== null || $limit !== null) {
1783
			Deprecation::notice('4.0', 'The $filter, $sort, $join and $limit parameters for
1784
				DataObject::getManyManyComponents() have been deprecated.
1785
				Please manipluate the returned list directly.', Deprecation::SCOPE_GLOBAL);
1786
		}
1787
1788
		// If we haven't been written yet, we can't save these relations, so use a list that handles this case
1789
		if(!$this->ID) {
1790
			if(!isset($this->unsavedRelations[$componentName])) {
1791
				$this->unsavedRelations[$componentName] =
1792
					new UnsavedRelationList($parentClass, $componentName, $componentClass);
1793
			}
1794
			return $this->unsavedRelations[$componentName];
1795
		}
1796
1797
		$extraFields = $this->manyManyExtraFieldsForComponent($componentName) ?: array();
1798
		$result = ManyManyList::create($componentClass, $table, $componentField, $parentField, $extraFields);
1799
1800
1801
		// Store component data in query meta-data
1802
		$result = $result->alterDataQuery(function($query) use ($extraFields) {
1803
			$query->setQueryParam('Component.ExtraFields', $extraFields);
1804
		});
1805
1806
		if($this->model) $result->setDataModel($this->model);
1807
1808
		$this->extend('updateManyManyComponents', $result);
1809
1810
		// If this is called on a singleton, then we return an 'orphaned relation' that can have the
1811
		// foreignID set elsewhere.
1812
		return $result
1813
			->forForeignID($this->ID)
1814
			->where($filter)
1815
			->sort($sort)
1816
			->limit($limit);
1817
	}
1818
1819
	/**
1820
	 * @deprecated 4.0 Method has been replaced by hasOne() and hasOneComponent()
1821
	 * @param string $component
1822
	 * @return array|null
1823
	 */
1824
	public function has_one($component = null) {
1825
		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...
1826
			Deprecation::notice('4.0', 'Please use hasOneComponent() instead');
1827
			return $this->hasOneComponent($component);
1828
		}
1829
1830
		Deprecation::notice('4.0', 'Please use hasOne() instead');
1831
		return $this->hasOne();
1832
	}
1833
1834
	/**
1835
	 * Return the class of a one-to-one component.  If $component is null, return all of the one-to-one components and
1836
	 * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.
1837
	 *
1838
	 * @param string $component Deprecated - Name of component
1839
	 * @return string|array The class of the one-to-one component, or an array of all one-to-one components and
1840
	 * 							their classes.
1841
	 */
1842
	public function hasOne($component = null) {
1843
		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...
1844
			Deprecation::notice(
1845
				'4.0',
1846
				'Please use DataObject::hasOneComponent() instead of passing a component name to hasOne()',
1847
				Deprecation::SCOPE_GLOBAL
1848
			);
1849
			return $this->hasOneComponent($component);
1850
		}
1851
1852
		return (array)Config::inst()->get($this->class, 'has_one', Config::INHERITED);
1853
	}
1854
1855
	/**
1856
	 * Return data for a specific has_one component.
1857
	 * @param string $component
1858
	 * @return string|null
1859
	 */
1860
	public function hasOneComponent($component) {
1861
		$hasOnes = (array)Config::inst()->get($this->class, 'has_one', Config::INHERITED);
1862
1863
		if(isset($hasOnes[$component])) {
1864
			return $hasOnes[$component];
1865
		}
1866
	}
1867
1868
	/**
1869
	 * @deprecated 4.0 Method has been replaced by belongsTo() and belongsToComponent()
1870
	 * @param string $component
1871
	 * @param bool $classOnly
1872
	 * @return array|null
1873
	 */
1874
	public function belongs_to($component = null, $classOnly = true) {
1875
		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...
1876
			Deprecation::notice('4.0', 'Please use belongsToComponent() instead');
1877
			return $this->belongsToComponent($component, $classOnly);
1878
		}
1879
1880
		Deprecation::notice('4.0', 'Please use belongsTo() instead');
1881
		return $this->belongsTo(null, $classOnly);
1882
	}
1883
1884
	/**
1885
	 * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
1886
	 * their class name will be returned.
1887
	 *
1888
	 * @param string $component - Name of component
1889
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1890
	 *        the field data stripped off. It defaults to TRUE.
1891
	 * @return string|array
1892
	 */
1893
	public function belongsTo($component = null, $classOnly = true) {
1894
		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...
1895
			Deprecation::notice(
1896
				'4.0',
1897
				'Please use DataObject::belongsToComponent() instead of passing a component name to belongsTo()',
1898
				Deprecation::SCOPE_GLOBAL
1899
			);
1900
			return $this->belongsToComponent($component, $classOnly);
1901
		}
1902
1903
		$belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED);
1904
		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...
1905
			return preg_replace('/(.+)?\..+/', '$1', $belongsTo);
1906
		} else {
1907
			return $belongsTo ? $belongsTo : array();
1908
		}
1909
	}
1910
1911
	/**
1912
	 * Return data for a specific belongs_to component.
1913
	 * @param string $component
1914
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1915
	 *        the field data stripped off. It defaults to TRUE.
1916
	 * @return string|false
1917
	 */
1918
	public function belongsToComponent($component, $classOnly = true) {
1919
		$belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED);
1920
1921
		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...
1922
			$belongsTo = $belongsTo[$component];
1923
		} else {
1924
			return false;
1925
		}
1926
1927
		return ($classOnly) ? preg_replace('/(.+)?\..+/', '$1', $belongsTo) : $belongsTo;
1928
	}
1929
1930
	/**
1931
	 * Return all of the database fields defined in self::$db and all the parent classes.
1932
	 * Doesn't include any fields specified by self::$has_one.  Use $this->hasOne() to get these fields
1933
	 *
1934
	 * @param string $fieldName Limit the output to a specific field name
1935
	 * @return array The database fields
1936
	 */
1937
	public function db($fieldName = null) {
1938
		$classes = ClassInfo::ancestry($this, true);
1939
1940
		// If we're looking for a specific field, we want to hit subclasses first as they may override field types
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
			$classes = array_reverse($classes);
1943
		}
1944
1945
		$items = array();
1946
		foreach($classes as $class) {
1947
			if(isset(self::$_cache_db[$class])) {
1948
				$dbItems = self::$_cache_db[$class];
1949
			} else {
1950
				$dbItems = (array) Config::inst()->get($class, 'db', Config::UNINHERITED);
1951
				self::$_cache_db[$class] = $dbItems;
1952
			}
1953
1954
			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...
1955
				if(isset($dbItems[$fieldName])) {
1956
					return $dbItems[$fieldName];
1957
				}
1958
			} else {
1959
				$items = isset($items) ? array_merge((array) $items, $dbItems) : $dbItems;
1960
			}
1961
		}
1962
		// If we requested a non-existant named field return null instead of all fields
1963
		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...
1964
			return null;
1965
		}
1966
		return $items;
1967
	}
1968
1969
	/**
1970
	 * @deprecated 4.0 Method has been replaced by hasMany() and hasManyComponent()
1971
	 * @param string $component
1972
	 * @param bool $classOnly
1973
	 * @return array|null
1974
	 */
1975
	public function has_many($component = null, $classOnly = true) {
1976
		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...
1977
			Deprecation::notice('4.0', 'Please use hasManyComponent() instead');
1978
			return $this->hasManyComponent($component, $classOnly);
1979
		}
1980
1981
		Deprecation::notice('4.0', 'Please use hasMany() instead');
1982
		return $this->hasMany(null, $classOnly);
1983
	}
1984
1985
	/**
1986
	 * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
1987
	 * relationships and their classes will be returned.
1988
	 *
1989
	 * @param string $component Deprecated - Name of component
1990
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
1991
	 *        the field data stripped off. It defaults to TRUE.
1992
	 * @return string|array|false
1993
	 */
1994
	public function hasMany($component = null, $classOnly = true) {
1995
		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...
1996
			Deprecation::notice(
1997
				'4.0',
1998
				'Please use DataObject::hasManyComponent() instead of passing a component name to hasMany()',
1999
				Deprecation::SCOPE_GLOBAL
2000
			);
2001
			return $this->hasManyComponent($component, $classOnly);
2002
		}
2003
2004
		$hasMany = (array)Config::inst()->get($this->class, 'has_many', Config::INHERITED);
2005
		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...
2006
			return preg_replace('/(.+)?\..+/', '$1', $hasMany);
2007
		} else {
2008
			return $hasMany ? $hasMany : array();
2009
		}
2010
	}
2011
2012
	/**
2013
	 * Return data for a specific has_many component.
2014
	 * @param string $component
2015
	 * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
2016
	 *        the field data stripped off. It defaults to TRUE.
2017
	 * @return string|false
2018
	 */
2019
	public function hasManyComponent($component, $classOnly = true) {
2020
		$hasMany = (array)Config::inst()->get($this->class, 'has_many', Config::INHERITED);
2021
2022
		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...
2023
			$hasMany = $hasMany[$component];
2024
		} else {
2025
			return false;
2026
		}
2027
2028
		return ($classOnly) ? preg_replace('/(.+)?\..+/', '$1', $hasMany) : $hasMany;
2029
	}
2030
2031
	/**
2032
	 * @deprecated 4.0 Method has been replaced by manyManyExtraFields() and
2033
	 *                 manyManyExtraFieldsForComponent()
2034
	 * @param string $component
2035
	 * @return array
2036
	 */
2037
	public function many_many_extraFields($component = null) {
2038
		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...
2039
			Deprecation::notice('4.0', 'Please use manyManyExtraFieldsForComponent() instead');
2040
			return $this->manyManyExtraFieldsForComponent($component);
2041
		}
2042
2043
		Deprecation::notice('4.0', 'Please use manyManyExtraFields() instead');
2044
		return $this->manyManyExtraFields();
2045
	}
2046
2047
	/**
2048
	 * Return the many-to-many extra fields specification.
2049
	 *
2050
	 * If you don't specify a component name, it returns all
2051
	 * extra fields for all components available.
2052
	 *
2053
	 * @param string $component Deprecated - Name of component
2054
	 * @return array|null
2055
	 */
2056
	public function manyManyExtraFields($component = null) {
2057
		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...
2058
			Deprecation::notice(
2059
				'4.0',
2060
				'Please use DataObject::manyManyExtraFieldsForComponent() instead of passing a component name
2061
					to manyManyExtraFields()',
2062
				Deprecation::SCOPE_GLOBAL
2063
			);
2064
			return $this->manyManyExtraFieldsForComponent($component);
2065
		}
2066
2067
		return Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED);
2068
	}
2069
2070
	/**
2071
	 * Return the many-to-many extra fields specification for a specific component.
2072
	 * @param string $component
2073
	 * @return array|null
2074
	 */
2075
	public function manyManyExtraFieldsForComponent($component) {
2076
		// Get all many_many_extraFields defined in this class or parent classes
2077
		$extraFields = (array)Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED);
2078
		// Extra fields are immediately available
2079
		if(isset($extraFields[$component])) {
2080
			return $extraFields[$component];
2081
		}
2082
2083
		// Check this class' belongs_many_manys to see if any of their reverse associations contain extra fields
2084
		$manyMany = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED);
2085
		$candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null;
2086
		if($candidate) {
2087
			$relationName = null;
2088
			// Extract class and relation name from dot-notation
2089
			if(strpos($candidate, '.') !== false) {
2090
				list($candidate, $relationName) = explode('.', $candidate, 2);
2091
			}
2092
2093
			// If we've not already found the relation name from dot notation, we need to find a relation that points
2094
			// back to this class. As there's no dot-notation, there can only be one relation pointing to this class,
2095
			// so it's safe to assume that it's the correct one
2096
			if(!$relationName) {
2097
				$candidateManyManys = (array)Config::inst()->get($candidate, 'many_many', Config::UNINHERITED);
2098
2099
				foreach($candidateManyManys as $relation => $relatedClass) {
2100
					if (is_a($this, $relatedClass)) {
2101
						$relationName = $relation;
2102
					}
2103
				}
2104
			}
2105
2106
			// If we've found a matching relation on the target class, see if we can find extra fields for it
2107
			$extraFields = (array)Config::inst()->get($candidate, 'many_many_extraFields', Config::UNINHERITED);
2108
			if(isset($extraFields[$relationName])) {
2109
				return $extraFields[$relationName];
2110
			}
2111
		}
2112
2113
		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...
2114
	}
2115
2116
	/**
2117
	 * @deprecated 4.0 Method has been renamed to manyMany()
2118
	 * @param string $component
2119
	 * @return array|null
2120
	 */
2121
	public function many_many($component = null) {
2122
		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...
2123
			Deprecation::notice('4.0', 'Please use manyManyComponent() instead');
2124
			return $this->manyManyComponent($component);
2125
		}
2126
2127
		Deprecation::notice('4.0', 'Please use manyMany() instead');
2128
		return $this->manyMany();
2129
	}
2130
2131
	/**
2132
	 * Return information about a many-to-many component.
2133
	 * The return value is an array of (parentclass, childclass).  If $component is null, then all many-many
2134
	 * components are returned.
2135
	 *
2136
	 * @see DataObject::manyManyComponent()
2137
	 * @param string $component Deprecated - Name of component
2138
	 * @return array|null An array of (parentclass, childclass), or an array of all many-many components
2139
	 */
2140
	public function manyMany($component = null) {
2141
		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...
2142
			Deprecation::notice(
2143
				'4.0',
2144
				'Please use DataObject::manyManyComponent() instead of passing a component name to manyMany()',
2145
				Deprecation::SCOPE_GLOBAL
2146
			);
2147
			return $this->manyManyComponent($component);
2148
		}
2149
2150
		$manyManys = (array)Config::inst()->get($this->class, 'many_many', Config::INHERITED);
2151
		$belongsManyManys = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED);
2152
2153
		$items = array_merge($manyManys, $belongsManyManys);
2154
		return $items;
2155
	}
2156
2157
	/**
2158
	 * Return information about a specific many_many component. Returns a numeric array of:
2159
	 * array(
2160
	 * 	<classname>,		The class that relation is defined in e.g. "Product"
2161
	 * 	<candidateName>,	The target class of the relation e.g. "Category"
2162
	 * 	<parentField>,		The field name pointing to <classname>'s table e.g. "ProductID"
2163
	 * 	<childField>,		The field name pointing to <candidatename>'s table e.g. "CategoryID"
2164
	 * 	<joinTable>			The join table between the two classes e.g. "Product_Categories"
2165
	 * )
2166
	 * @param string $component The component name
2167
	 * @return array|null
2168
	 */
2169
	public function manyManyComponent($component) {
2170
		$classes = $this->getClassAncestry();
2171
		foreach($classes as $class) {
2172
			$manyMany = Config::inst()->get($class, 'many_many', Config::UNINHERITED);
2173
			// Check if the component is defined in many_many on this class
2174
			$candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null;
2175
			if($candidate) {
2176
				$parentField = $class . "ID";
2177
				$childField = ($class == $candidate) ? "ChildID" : $candidate . "ID";
2178
				return array($class, $candidate, $parentField, $childField, "{$class}_$component");
2179
			}
2180
2181
			// Check if the component is defined in belongs_many_many on this class
2182
			$belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED);
2183
			$candidate = (isset($belongsManyMany[$component])) ? $belongsManyMany[$component] : null;
2184
			if($candidate) {
2185
				// Extract class and relation name from dot-notation
2186
				if(strpos($candidate, '.') !== false) {
2187
					list($candidate, $relationName) = explode('.', $candidate, 2);
2188
				}
2189
2190
				$childField = $candidate . "ID";
2191
2192
				// We need to find the inverse component name
2193
				$otherManyMany = Config::inst()->get($candidate, 'many_many', Config::UNINHERITED);
2194
				if(!$otherManyMany) {
2195
					throw new LogicException("Inverse component of $candidate not found ({$this->class})");
2196
				}
2197
2198
				// If we've got a relation name (extracted from dot-notation), we can already work out
2199
				// the join table and candidate class name...
2200
				if(isset($relationName) && isset($otherManyMany[$relationName])) {
2201
					$candidateClass = $otherManyMany[$relationName];
2202
					$joinTable = "{$candidate}_{$relationName}";
2203
				} else {
2204
					// ... otherwise, we need to loop over the many_manys and find a relation that
2205
					// matches up to this class
2206
					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...
2207
						if($candidateClass == $class || is_subclass_of($class, $candidateClass)) {
2208
							$joinTable = "{$candidate}_{$inverseComponentName}";
2209
							break;
2210
						}
2211
					}
2212
				}
2213
2214
				// If we could work out the join table, we've got all the info we need
2215
				if(isset($joinTable)) {
2216
					$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...
2217
					return array($class, $candidate, $parentField, $childField, $joinTable);
2218
				}
2219
2220
				throw new LogicException("Orphaned \$belongs_many_many value for $this->class.$component");
2221
			}
2222
		}
2223
	}
2224
2225
	/**
2226
	 * This returns an array (if it exists) describing the database extensions that are required, or false if none
2227
	 *
2228
	 * This is experimental, and is currently only a Postgres-specific enhancement.
2229
	 *
2230
	 * @return array or false
2231
	 */
2232
	public function database_extensions($class){
2233
		$extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
2234
2235
		if($extensions)
2236
			return $extensions;
2237
		else
2238
			return false;
2239
	}
2240
2241
	/**
2242
	 * Generates a SearchContext to be used for building and processing
2243
	 * a generic search form for properties on this object.
2244
	 *
2245
	 * @return SearchContext
2246
	 */
2247
	public function getDefaultSearchContext() {
2248
		return new SearchContext(
2249
			$this->class,
2250
			$this->scaffoldSearchFields(),
2251
			$this->defaultSearchFilters()
2252
		);
2253
	}
2254
2255
	/**
2256
	 * Determine which properties on the DataObject are
2257
	 * searchable, and map them to their default {@link FormField}
2258
	 * representations. Used for scaffolding a searchform for {@link ModelAdmin}.
2259
	 *
2260
	 * Some additional logic is included for switching field labels, based on
2261
	 * how generic or specific the field type is.
2262
	 *
2263
	 * Used by {@link SearchContext}.
2264
	 *
2265
	 * @param array $_params
2266
	 *   'fieldClasses': Associative array of field names as keys and FormField classes as values
2267
	 *   'restrictFields': Numeric array of a field name whitelist
2268
	 * @return FieldList
2269
	 */
2270
	public function scaffoldSearchFields($_params = null) {
2271
		$params = array_merge(
2272
			array(
2273
				'fieldClasses' => false,
2274
				'restrictFields' => false
2275
			),
2276
			(array)$_params
2277
		);
2278
		$fields = new FieldList();
2279
		foreach($this->searchableFields() as $fieldName => $spec) {
2280
			if($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) continue;
2281
2282
			// If a custom fieldclass is provided as a string, use it
2283
			if($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) {
2284
				$fieldClass = $params['fieldClasses'][$fieldName];
2285
				$field = new $fieldClass($fieldName);
2286
			// If we explicitly set a field, then construct that
2287
			} else if(isset($spec['field'])) {
2288
				// If it's a string, use it as a class name and construct
2289
				if(is_string($spec['field'])) {
2290
					$fieldClass = $spec['field'];
2291
					$field = new $fieldClass($fieldName);
2292
2293
				// If it's a FormField object, then just use that object directly.
2294
				} else if($spec['field'] instanceof FormField) {
2295
					$field = $spec['field'];
2296
2297
				// Otherwise we have a bug
2298
				} else {
2299
					user_error("Bad value for searchable_fields, 'field' value: "
2300
						. var_export($spec['field'], true), E_USER_WARNING);
2301
				}
2302
2303
			// Otherwise, use the database field's scaffolder
2304
			} else {
2305
				$field = $this->relObject($fieldName)->scaffoldSearchField();
2306
			}
2307
2308
			if (strstr($fieldName, '.')) {
2309
				$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...
2310
			}
2311
			$field->setTitle($spec['title']);
2312
2313
			$fields->push($field);
2314
		}
2315
		return $fields;
2316
	}
2317
2318
	/**
2319
	 * Scaffold a simple edit form for all properties on this dataobject,
2320
	 * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
2321
	 * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
2322
	 *
2323
	 * @uses FormScaffolder
2324
	 *
2325
	 * @param array $_params Associative array passing through properties to {@link FormScaffolder}.
2326
	 * @return FieldList
2327
	 */
2328
	public function scaffoldFormFields($_params = null) {
2329
		$params = array_merge(
2330
			array(
2331
				'tabbed' => false,
2332
				'includeRelations' => false,
2333
				'restrictFields' => false,
2334
				'fieldClasses' => false,
2335
				'ajaxSafe' => false
2336
			),
2337
			(array)$_params
2338
		);
2339
2340
		$fs = new FormScaffolder($this);
2341
		$fs->tabbed = $params['tabbed'];
2342
		$fs->includeRelations = $params['includeRelations'];
2343
		$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...
2344
		$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...
2345
		$fs->ajaxSafe = $params['ajaxSafe'];
2346
2347
		return $fs->getFieldList();
2348
	}
2349
2350
	/**
2351
	 * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
2352
	 * being called on extensions
2353
	 *
2354
	 * @param callable $callback The callback to execute
2355
	 */
2356
	protected function beforeUpdateCMSFields($callback) {
2357
		$this->beforeExtending('updateCMSFields', $callback);
2358
	}
2359
2360
	/**
2361
	 * Centerpiece of every data administration interface in Silverstripe,
2362
	 * which returns a {@link FieldList} suitable for a {@link Form} object.
2363
	 * If not overloaded, we're using {@link scaffoldFormFields()} to automatically
2364
	 * generate this set. To customize, overload this method in a subclass
2365
	 * or extended onto it by using {@link DataExtension->updateCMSFields()}.
2366
	 *
2367
	 * <code>
2368
	 * class MyCustomClass extends DataObject {
2369
	 *  static $db = array('CustomProperty'=>'Boolean');
2370
	 *
2371
	 *  function getCMSFields() {
2372
	 *    $fields = parent::getCMSFields();
2373
	 *    $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
2374
	 *    return $fields;
2375
	 *  }
2376
	 * }
2377
	 * </code>
2378
	 *
2379
	 * @see Good example of complex FormField building: SiteTree::getCMSFields()
2380
	 *
2381
	 * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms.
2382
	 */
2383
	public function getCMSFields() {
2384
		$tabbedFields = $this->scaffoldFormFields(array(
2385
			// Don't allow has_many/many_many relationship editing before the record is first saved
2386
			'includeRelations' => ($this->ID > 0),
2387
			'tabbed' => true,
2388
			'ajaxSafe' => true
2389
		));
2390
2391
		$this->extend('updateCMSFields', $tabbedFields);
2392
2393
		return $tabbedFields;
2394
	}
2395
2396
	/**
2397
	 * need to be overload by solid dataobject, so that the customised actions of that dataobject,
2398
	 * including that dataobject's extensions customised actions could be added to the EditForm.
2399
	 *
2400
	 * @return an Empty FieldList(); need to be overload by solid subclass
2401
	 */
2402
	public function getCMSActions() {
2403
		$actions = new FieldList();
2404
		$this->extend('updateCMSActions', $actions);
2405
		return $actions;
2406
	}
2407
2408
2409
	/**
2410
	 * Used for simple frontend forms without relation editing
2411
	 * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()}
2412
	 * by default. To customize, either overload this method in your
2413
	 * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.
2414
	 *
2415
	 * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API
2416
	 *
2417
	 * @param array $params See {@link scaffoldFormFields()}
2418
	 * @return FieldList Always returns a simple field collection without TabSet.
2419
	 */
2420
	public function getFrontEndFields($params = null) {
2421
		$untabbedFields = $this->scaffoldFormFields($params);
2422
		$this->extend('updateFrontEndFields', $untabbedFields);
2423
2424
		return $untabbedFields;
2425
	}
2426
2427
	/**
2428
	 * Gets the value of a field.
2429
	 * Called by {@link __get()} and any getFieldName() methods you might create.
2430
	 *
2431
	 * @param string $field The name of the field
2432
	 *
2433
	 * @return mixed The field value
2434
	 */
2435
	public function getField($field) {
2436
		// If we already have an object in $this->record, then we should just return that
2437
		if(isset($this->record[$field]) && is_object($this->record[$field]))  return $this->record[$field];
2438
2439
		// Do we have a field that needs to be lazy loaded?
2440
		if(isset($this->record[$field.'_Lazy'])) {
2441
			$tableClass = $this->record[$field.'_Lazy'];
2442
			$this->loadLazyFields($tableClass);
2443
		}
2444
2445
		// Otherwise, we need to determine if this is a complex field
2446
		if(self::is_composite_field($this->class, $field)) {
2447
			$helper = $this->castingHelper($field);
2448
			$fieldObj = SS_Object::create_from_string($helper, $field);
2449
2450
			$compositeFields = $fieldObj->compositeDatabaseFields();
2451
			foreach ($compositeFields as $compositeName => $compositeType) {
2452
				if(isset($this->record[$field.$compositeName.'_Lazy'])) {
2453
					$tableClass = $this->record[$field.$compositeName.'_Lazy'];
2454
					$this->loadLazyFields($tableClass);
2455
				}
2456
			}
2457
2458
			// write value only if either the field value exists,
2459
			// or a valid record has been loaded from the database
2460
			$value = (isset($this->record[$field])) ? $this->record[$field] : null;
2461
			if($value || $this->exists()) $fieldObj->setValue($value, $this->record, false);
2462
2463
			$this->record[$field] = $fieldObj;
2464
2465
			return $this->record[$field];
2466
		}
2467
2468
		return isset($this->record[$field]) ? $this->record[$field] : null;
2469
	}
2470
2471
	/**
2472
	 * Loads all the stub fields that an initial lazy load didn't load fully.
2473
	 *
2474
	 * @param string $tableClass Base table to load the values from. Others are joined as required.
2475
	 * Not specifying a tableClass will load all lazy fields from all tables.
2476
	 * @return bool Flag if lazy loading succeeded
2477
	 */
2478
	protected function loadLazyFields($tableClass = null) {
2479
		if(!$this->isInDB() || !is_numeric($this->ID)) {
2480
			return false;
2481
		}
2482
2483
		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...
2484
			$loaded = array();
2485
2486
			foreach ($this->record as $key => $value) {
2487
				if (strlen($key) > 5 && substr($key, -5) == '_Lazy' && !array_key_exists($value, $loaded)) {
2488
					$this->loadLazyFields($value);
2489
					$loaded[$value] = $value;
2490
				}
2491
			}
2492
2493
			return false;
2494
		}
2495
2496
		$dataQuery = new DataQuery($tableClass);
2497
2498
		// Reset query parameter context to that of this DataObject
2499
		if($params = $this->getSourceQueryParams()) {
2500
			foreach($params as $key => $value) $dataQuery->setQueryParam($key, $value);
2501
		}
2502
2503
		// Limit query to the current record, unless it has the Versioned extension,
2504
		// in which case it requires special handling through augmentLoadLazyFields()
2505
		if(!$this->hasExtension('Versioned')) {
2506
			$dataQuery->where("\"$tableClass\".\"ID\" = {$this->record['ID']}")->limit(1);
2507
		}
2508
2509
		$columns = array();
2510
2511
		// Add SQL for fields, both simple & multi-value
2512
		// TODO: This is copy & pasted from buildSQL(), it could be moved into a method
2513
		$databaseFields = self::database_fields($tableClass, false);
2514
		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...
2515
			if(!isset($this->record[$k]) || $this->record[$k] === null) {
2516
				$columns[] = $k;
2517
			}
2518
		}
2519
2520
		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...
2521
			$query = $dataQuery->query();
2522
			$this->extend('augmentLoadLazyFields', $query, $dataQuery, $this);
2523
			$this->extend('augmentSQL', $query, $dataQuery);
2524
2525
			$dataQuery->setQueriedColumns($columns);
2526
			$newData = $dataQuery->execute()->record();
2527
2528
			// Load the data into record
2529
			if($newData) {
2530
				foreach($newData as $k => $v) {
2531
					if (in_array($k, $columns)) {
2532
						$this->record[$k] = $v;
2533
						$this->original[$k] = $v;
2534
						unset($this->record[$k . '_Lazy']);
2535
					}
2536
				}
2537
2538
			// No data means that the query returned nothing; assign 'null' to all the requested fields
2539
			} else {
2540
				foreach($columns as $k) {
2541
					$this->record[$k] = null;
2542
					$this->original[$k] = null;
2543
					unset($this->record[$k . '_Lazy']);
2544
				}
2545
			}
2546
		}
2547
		return true;
2548
	}
2549
2550
	/**
2551
	 * Return the fields that have changed.
2552
	 *
2553
	 * The change level affects what the functions defines as "changed":
2554
	 * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
2555
	 * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes,
2556
	 *   for example a change from 0 to null would not be included.
2557
	 *
2558
	 * Example return:
2559
	 * <code>
2560
	 * array(
2561
	 *   'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE)
2562
	 * )
2563
	 * </code>
2564
	 *
2565
	 * @param boolean $databaseFieldsOnly Get only database fields that have changed
2566
	 * @param int $changeLevel The strictness of what is defined as change. Defaults to strict
2567
	 * @return array
2568
	 */
2569
	public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT) {
2570
		$changedFields = array();
2571
2572
		// Update the changed array with references to changed obj-fields
2573
		foreach($this->record as $k => $v) {
2574
			if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
2575
				$this->changed[$k] = self::CHANGE_VALUE;
2576
			}
2577
		}
2578
2579
		if($databaseFieldsOnly) {
2580
			// Merge all DB fields together
2581
			$inheritedFields = $this->inheritedDatabaseFields();
2582
			$compositeFields = static::composite_fields(get_class($this));
2583
			$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...
2584
			$databaseFields = array_merge(
2585
				$inheritedFields,
2586
				$fixedFields,
2587
				$compositeFields
2588
			);
2589
			$fields = array_intersect_key((array)$this->changed, $databaseFields);
2590
		} else {
2591
			$fields = $this->changed;
2592
		}
2593
2594
		// Filter the list to those of a certain change level
2595
		if($changeLevel > self::CHANGE_STRICT) {
2596
			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...
2597
				if($level < $changeLevel) {
2598
					unset($fields[$name]);
2599
				}
2600
			}
2601
		}
2602
2603
		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...
2604
			$changedFields[$name] = array(
2605
				'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null,
2606
				'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null,
2607
				'level' => $level
2608
			);
2609
		}
2610
2611
		return $changedFields;
2612
	}
2613
2614
	/**
2615
	 * Uses {@link getChangedFields()} to determine if fields have been changed
2616
	 * since loading them from the database.
2617
	 *
2618
	 * @param string $fieldName Name of the database field to check, will check for any if not given
2619
	 * @param int $changeLevel See {@link getChangedFields()}
2620
	 * @return boolean
2621
	 */
2622
	public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT) {
2623
		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...
2624
			// Limit "any changes" to db fields only
2625
			$changed = $this->getChangedFields(true, $changeLevel);
2626
			return !empty($changed);
2627
		} else {
2628
			// Given a field name, check all fields
2629
			$changed = $this->getChangedFields(false, $changeLevel);
2630
			return array_key_exists($fieldName, $changed);
2631
		}
2632
	}
2633
2634
	/**
2635
	 * Set the value of the field
2636
	 * Called by {@link __set()} and any setFieldName() methods you might create.
2637
	 *
2638
	 * @param string $fieldName Name of the field
2639
	 * @param mixed $val New field value
2640
	 * @return DataObject $this
2641
	 */
2642
	public function setField($fieldName, $val) {
2643
		//if it's a has_one component, destroy the cache
2644
		if (substr($fieldName, -2) == 'ID') {
2645
			unset($this->components[substr($fieldName, 0, -2)]);
2646
		}
2647
		// Situation 1: Passing an DBField
2648
		if($val instanceof DBField) {
2649
			$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...
2650
2651
			// If we've just lazy-loaded the column, then we need to populate the $original array by
2652
			// called getField(). Too much overhead? Could this be done by a quicker method? Maybe only
2653
			// on a call to getChanged()?
2654
			$this->getField($fieldName);
2655
2656
			$this->record[$fieldName] = $val;
2657
		// Situation 2: Passing a literal or non-DBField object
2658
		} else {
2659
			// If this is a proper database field, we shouldn't be getting non-DBField objects
2660
			if(is_object($val) && $this->db($fieldName)) {
2661
				user_error('DataObject::setField: passed an object that is not a DBField', E_USER_WARNING);
2662
			}
2663
2664
			// if a field is not existing or has strictly changed
2665
			if(!isset($this->record[$fieldName]) || $this->record[$fieldName] !== $val) {
2666
				// TODO Add check for php-level defaults which are not set in the db
2667
				// TODO Add check for hidden input-fields (readonly) which are not set in the db
2668
				// At the very least, the type has changed
2669
				$this->changed[$fieldName] = self::CHANGE_STRICT;
2670
2671
				if((!isset($this->record[$fieldName]) && $val) || (isset($this->record[$fieldName])
2672
						&& $this->record[$fieldName] != $val)) {
2673
2674
					// Value has changed as well, not just the type
2675
					$this->changed[$fieldName] = self::CHANGE_VALUE;
2676
				}
2677
2678
				// If we've just lazy-loaded the column, then we need to populate the $original array by
2679
				// called getField(). Too much overhead? Could this be done by a quicker method? Maybe only
2680
				// on a call to getChanged()?
2681
				$this->getField($fieldName);
2682
2683
				// Value is always saved back when strict check succeeds.
2684
				$this->record[$fieldName] = $val;
2685
			}
2686
		}
2687
		return $this;
2688
	}
2689
2690
	/**
2691
	 * Set the value of the field, using a casting object.
2692
	 * This is useful when you aren't sure that a date is in SQL format, for example.
2693
	 * setCastedField() can also be used, by forms, to set related data.  For example, uploaded images
2694
	 * can be saved into the Image table.
2695
	 *
2696
	 * @param string $fieldName Name of the field
2697
	 * @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...
2698
	 * @return DataObject $this
2699
	 */
2700
	public function setCastedField($fieldName, $val) {
2701
		if(!$fieldName) {
2702
			user_error("DataObject::setCastedField: Called without a fieldName", E_USER_ERROR);
2703
		}
2704
		$castingHelper = $this->castingHelper($fieldName);
2705
		if($castingHelper) {
2706
			$fieldObj = SS_Object::create_from_string($castingHelper, $fieldName);
2707
			$fieldObj->setValue($val);
2708
			$fieldObj->saveInto($this);
2709
		} else {
2710
			$this->$fieldName = $val;
2711
		}
2712
		return $this;
2713
	}
2714
2715
	/**
2716
	 * {@inheritdoc}
2717
	 */
2718
	public function castingHelper($field) {
2719
		if ($fieldSpec = $this->db($field)) {
2720
			return $fieldSpec;
2721
		}
2722
2723
		// many_many_extraFields aren't presented by db(), so we check if the source query params
2724
		// provide us with meta-data for a many_many relation we can inspect for extra fields.
2725
		$queryParams = $this->getSourceQueryParams();
2726
		if (!empty($queryParams['Component.ExtraFields'])) {
2727
			$extraFields = $queryParams['Component.ExtraFields'];
2728
2729
			if (isset($extraFields[$field])) {
2730
				return $extraFields[$field];
2731
			}
2732
		}
2733
2734
		return parent::castingHelper($field);
2735
	}
2736
2737
	/**
2738
	 * Returns true if the given field exists in a database column on any of
2739
	 * the objects tables and optionally look up a dynamic getter with
2740
	 * get<fieldName>().
2741
	 *
2742
	 * @param string $field Name of the field
2743
	 * @return boolean True if the given field exists
2744
	 */
2745
	public function hasField($field) {
2746
		return (
2747
			array_key_exists($field, $this->record)
2748
			|| $this->db($field)
2749
			|| (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...
2750
			|| $this->hasMethod("get{$field}")
2751
		);
2752
	}
2753
2754
	/**
2755
	 * Returns true if the given field exists as a database column
2756
	 *
2757
	 * @param string $field Name of the field
2758
	 *
2759
	 * @return boolean
2760
	 */
2761
	public function hasDatabaseField($field) {
2762
		if(isset(self::$fixed_fields[$field])) return true;
2763
2764
		return array_key_exists($field, $this->inheritedDatabaseFields());
2765
	}
2766
2767
	/**
2768
	 * Returns the field type of the given field, if it belongs to this class, and not a parent.
2769
	 * Note that the field type will not include constructor arguments in round brackets, only the classname.
2770
	 *
2771
	 * @param string $field Name of the field
2772
	 * @return string The field type of the given field
2773
	 */
2774
	public function hasOwnTableDatabaseField($field) {
2775
		return self::has_own_table_database_field($this->class, $field);
2776
	}
2777
2778
	/**
2779
	 * Returns the field type of the given field, if it belongs to this class, and not a parent.
2780
	 * Note that the field type will not include constructor arguments in round brackets, only the classname.
2781
	 *
2782
	 * @param string $class Class name to check
2783
	 * @param string $field Name of the field
2784
	 * @return string The field type of the given field
2785
	 */
2786
	public static function has_own_table_database_field($class, $field) {
2787
		// Since database_fields omits 'ID'
2788
		if($field == "ID") return "Int";
2789
2790
		$fieldMap = self::database_fields($class, false);
2791
2792
		// Remove string-based "constructor-arguments" from the DBField definition
2793
		if(isset($fieldMap[$field])) {
2794
			$spec = $fieldMap[$field];
2795
			if(is_string($spec)) return strtok($spec,'(');
2796
			else return $spec['type'];
2797
		}
2798
	}
2799
2800
	/**
2801
	 * Returns true if given class has its own table. Uses the rules for whether the table should exist rather than
2802
	 * actually looking in the database.
2803
	 *
2804
	 * @param string $dataClass
2805
	 * @return bool
2806
	 */
2807
	public static function has_own_table($dataClass) {
2808
		if(!is_subclass_of($dataClass,'DataObject')) return false;
2809
2810
		$dataClass = ClassInfo::class_name($dataClass);
2811
		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...
2812
			if(get_parent_class($dataClass) == 'DataObject') {
2813
				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...
2814
			} else {
2815
				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...
2816
					= Config::inst()->get($dataClass, 'db', Config::UNINHERITED)
2817
					|| Config::inst()->get($dataClass, 'has_one', Config::UNINHERITED);
2818
			}
2819
		}
2820
		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...
2821
	}
2822
2823
	/**
2824
	 * Returns true if the member is allowed to do the given action.
2825
	 * See {@link extendedCan()} for a more versatile tri-state permission control.
2826
	 *
2827
	 * @param string $perm The permission to be checked, such as 'View'.
2828
	 * @param Member $member The member whose permissions need checking.  Defaults to the currently logged
2829
	 * in user.
2830
	 *
2831
	 * @return boolean True if the the member is allowed to do the given action
2832
	 */
2833
	public function can($perm, $member = null) {
2834
		if(!isset($member)) {
2835
			$member = Member::currentUser();
2836
		}
2837
		if(Permission::checkMember($member, "ADMIN")) return true;
2838
2839
		if($this->manyManyComponent('Can' . $perm)) {
2840
			if($this->ParentID && $this->SecurityType == 'Inherit') {
2841
				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...
2842
					return false;
2843
				}
2844
				return $this->Parent->can($perm, $member);
2845
2846
			} else {
2847
				$permissionCache = $this->uninherited('permissionCache');
2848
				$memberID = $member ? $member->ID : 'none';
2849
2850
				if(!isset($permissionCache[$memberID][$perm])) {
2851
					if($member->ID) {
2852
						$groups = $member->Groups();
2853
					}
2854
2855
					$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...
2856
2857
					// TODO Fix relation table hardcoding
2858
					$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...
2859
						"\"Page_Can$perm\".PageID",
2860
					array("\"Page_Can$perm\""),
2861
						"GroupID IN ($groupList)");
2862
2863
					$permissionCache[$memberID][$perm] = $query->execute()->column();
2864
2865
					if($perm == "View") {
2866
						// TODO Fix relation table hardcoding
2867
						$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...
2868
							"\"SiteTree\"",
2869
							"LEFT JOIN \"Page_CanView\" ON \"Page_CanView\".\"PageID\" = \"SiteTree\".\"ID\""
2870
							), "\"Page_CanView\".\"PageID\" IS NULL");
2871
2872
							$unsecuredPages = $query->execute()->column();
2873
							if($permissionCache[$memberID][$perm]) {
2874
								$permissionCache[$memberID][$perm]
2875
									= array_merge($permissionCache[$memberID][$perm], $unsecuredPages);
2876
							} else {
2877
								$permissionCache[$memberID][$perm] = $unsecuredPages;
2878
							}
2879
					}
2880
2881
					Config::inst()->update($this->class, 'permissionCache', $permissionCache);
2882
				}
2883
2884
				if($permissionCache[$memberID][$perm]) {
2885
					return in_array($this->ID, $permissionCache[$memberID][$perm]);
2886
				}
2887
			}
2888
		} else {
2889
			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, DataObjectSchemaGenerationTest_SortedByText, 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, HTTPCacheControlIntegrationTest_RuleController, HTTPCacheControlIntegrationTest_SessionController, 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...
2890
		}
2891
	}
2892
2893
	/**
2894
	 * Process tri-state responses from permission-alterting extensions.  The extensions are
2895
	 * expected to return one of three values:
2896
	 *
2897
	 *  - false: Disallow this permission, regardless of what other extensions say
2898
	 *  - true: Allow this permission, as long as no other extensions return false
2899
	 *  - NULL: Don't affect the outcome
2900
	 *
2901
	 * This method itself returns a tri-state value, and is designed to be used like this:
2902
	 *
2903
	 * <code>
2904
	 * $extended = $this->extendedCan('canDoSomething', $member);
2905
	 * if($extended !== null) return $extended;
2906
	 * else return $normalValue;
2907
	 * </code>
2908
	 *
2909
	 * @param String $methodName Method on the same object, e.g. {@link canEdit()}
2910
	 * @param Member|int $member
2911
	 * @return boolean|null
2912
	 */
2913
	public function extendedCan($methodName, $member) {
2914
		$results = $this->extend($methodName, $member);
2915
		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...
2916
			// Remove NULLs
2917
			$results = array_filter($results, function($v) {return !is_null($v);});
2918
			// If there are any non-NULL responses, then return the lowest one of them.
2919
			// If any explicitly deny the permission, then we don't get access
2920
			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...
2921
		}
2922
		return null;
2923
	}
2924
2925
	/**
2926
	 * @param Member $member
2927
	 * @return boolean
2928
	 */
2929
	public function canView($member = null) {
2930
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2929 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...
2931
		if($extended !== null) {
2932
			return $extended;
2933
		}
2934
		return Permission::check('ADMIN', 'any', $member);
2935
	}
2936
2937
	/**
2938
	 * @param Member $member
2939
	 * @return boolean
2940
	 */
2941
	public function canEdit($member = null) {
2942
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2941 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...
2943
		if($extended !== null) {
2944
			return $extended;
2945
		}
2946
		return Permission::check('ADMIN', 'any', $member);
2947
	}
2948
2949
	/**
2950
	 * @param Member $member
2951
	 * @return boolean
2952
	 */
2953
	public function canDelete($member = null) {
2954
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2953 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...
2955
		if($extended !== null) {
2956
			return $extended;
2957
		}
2958
		return Permission::check('ADMIN', 'any', $member);
2959
	}
2960
2961
	/**
2962
	 * @todo Should canCreate be a static method?
2963
	 *
2964
	 * @param Member $member
2965
	 * @return boolean
2966
	 */
2967
	public function canCreate($member = null) {
2968
		$extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 2967 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...
2969
		if($extended !== null) {
2970
			return $extended;
2971
		}
2972
		return Permission::check('ADMIN', 'any', $member);
2973
	}
2974
2975
	/**
2976
	 * Debugging used by Debug::show()
2977
	 *
2978
	 * @return string HTML data representing this object
2979
	 */
2980
	public function debug() {
2981
		$val = "<h3>Database record: $this->class</h3>\n<ul>\n";
2982
		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...
2983
			$val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n";
2984
		}
2985
		$val .= "</ul>\n";
2986
		return $val;
2987
	}
2988
2989
	/**
2990
	 * Return the DBField object that represents the given field.
2991
	 * This works similarly to obj() with 2 key differences:
2992
	 *   - it still returns an object even when the field has no value.
2993
	 *   - it only matches fields and not methods
2994
	 *   - it matches foreign keys generated by has_one relationships, eg, "ParentID"
2995
	 *
2996
	 * @param string $fieldName Name of the field
2997
	 * @return DBField The field as a DBField object
2998
	 */
2999
	public function dbObject($fieldName) {
3000
		// If we have a CompositeDBField object in $this->record, then return that
3001
		if(isset($this->record[$fieldName]) && is_object($this->record[$fieldName])) {
3002
			return $this->record[$fieldName];
3003
3004
		// Special case for ID field
3005
		} else if($fieldName == 'ID') {
3006
			return new PrimaryKey($fieldName, $this);
3007
3008
		// Special case for ClassName
3009
		} else if($fieldName == 'ClassName') {
3010
			$val = get_class($this);
3011
			return DBField::create_field('Varchar', $val, $fieldName);
3012
3013
		} else if(array_key_exists($fieldName, self::$fixed_fields)) {
3014
			return DBField::create_field(self::$fixed_fields[$fieldName], $this->$fieldName, $fieldName);
3015
3016
		// General casting information for items in $db
3017
		} else if($helper = $this->db($fieldName)) {
3018
			$obj = SS_Object::create_from_string($helper, $fieldName);
3019
			$obj->setValue($this->$fieldName, $this->record, false);
3020
			return $obj;
3021
3022
		// Special case for has_one relationships
3023
		} 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...
3024
			$val = $this->$fieldName;
3025
			return DBField::create_field('ForeignKey', $val, $fieldName, $this);
3026
3027
		// has_one for polymorphic relations do not end in ID
3028
		} else if(($type = $this->hasOneComponent($fieldName)) && ($type === 'DataObject')) {
3029
			$val = $this->$fieldName();
3030
			return DBField::create_field('PolymorphicForeignKey', $val, $fieldName, $this);
3031
3032
		}
3033
	}
3034
3035
	/**
3036
	 * Traverses to a DBField referenced by relationships between data objects.
3037
	 *
3038
	 * The path to the related field is specified with dot separated syntax
3039
	 * (eg: Parent.Child.Child.FieldName).
3040
	 *
3041
	 * @param string $fieldPath
3042
	 *
3043
	 * @return mixed DBField of the field on the object or a DataList instance.
3044
	 */
3045
	public function relObject($fieldPath) {
3046
		$object = null;
3047
3048
		if(strpos($fieldPath, '.') !== false) {
3049
			$parts = explode('.', $fieldPath);
3050
			$fieldName = array_pop($parts);
3051
3052
			// Traverse dot syntax
3053
			$component = $this;
3054
3055
			foreach($parts as $relation) {
3056
				if($component instanceof SS_List) {
3057
					if(method_exists($component,$relation)) {
3058
						$component = $component->$relation();
3059
					} else {
3060
						$component = $component->relation($relation);
3061
					}
3062
				} else {
3063
					$component = $component->$relation();
3064
				}
3065
			}
3066
3067
			$object = $component->dbObject($fieldName);
3068
3069
		} else {
3070
			$object = $this->dbObject($fieldPath);
3071
		}
3072
3073
		return $object;
3074
	}
3075
3076
	/**
3077
	 * Traverses to a field referenced by relationships between data objects, returning the value
3078
	 * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)
3079
	 *
3080
	 * @param $fieldPath string
3081
	 * @return string | null - will return null on a missing value
3082
	 */
3083
	public function relField($fieldName) {
3084
		$component = $this;
3085
3086
		// We're dealing with relations here so we traverse the dot syntax
3087
		if(strpos($fieldName, '.') !== false) {
3088
			$relations = explode('.', $fieldName);
3089
			$fieldName = array_pop($relations);
3090
			foreach($relations as $relation) {
3091
				// Bail if the component is null
3092
				if(!$component) {
3093
					return null;
3094
				// Inspect $component for element $relation
3095
				} elseif($component->hasMethod($relation)) {
3096
					// Check nested method
3097
					$component = $component->$relation();
3098
				} elseif($component instanceof SS_List) {
3099
					// Select adjacent relation from DataList
3100
					$component = $component->relation($relation);
3101
				} elseif($component instanceof DataObject
3102
					&& ($dbObject = $component->dbObject($relation))
3103
				) {
3104
					// Select db object
3105
					$component = $dbObject;
3106
				} else {
3107
					user_error("$relation is not a relation/field on ".get_class($component), E_USER_ERROR);
3108
				}
3109
			}
3110
		}
3111
3112
		// Bail if the component is null
3113
		if(!$component) {
3114
			return null;
3115
		}
3116
		if($component->hasMethod($fieldName)) {
3117
			return $component->$fieldName();
3118
		}
3119
		return $component->$fieldName;
3120
	}
3121
3122
	/**
3123
	 * Temporary hack to return an association name, based on class, to get around the mangle
3124
	 * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
3125
	 *
3126
	 * @return String
3127
	 */
3128
	public function getReverseAssociation($className) {
3129
		if (is_array($this->manyMany())) {
3130
			$many_many = array_flip($this->manyMany());
3131
			if (array_key_exists($className, $many_many)) return $many_many[$className];
3132
		}
3133
		if (is_array($this->hasMany())) {
3134
			$has_many = array_flip($this->hasMany());
3135
			if (array_key_exists($className, $has_many)) return $has_many[$className];
3136
		}
3137
		if (is_array($this->hasOne())) {
3138
			$has_one = array_flip($this->hasOne());
3139
			if (array_key_exists($className, $has_one)) return $has_one[$className];
3140
		}
3141
3142
		return false;
3143
	}
3144
3145
	/**
3146
	 * Return all objects matching the filter
3147
	 * sub-classes are automatically selected and included
3148
	 *
3149
	 * @param string $callerClass The class of objects to be returned
3150
	 * @param string|array $filter A filter to be inserted into the WHERE clause.
3151
	 * Supports parameterised queries. See SQLQuery::addWhere() for syntax examples.
3152
	 * @param string|array $sort A sort expression to be inserted into the ORDER
3153
	 * BY clause.  If omitted, self::$default_sort will be used.
3154
	 * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.
3155
	 * @param string|array $limit A limit expression to be inserted into the LIMIT clause.
3156
	 * @param string $containerClass The container class to return the results in.
3157
	 *
3158
	 * @todo $containerClass is Ignored, why?
3159
	 *
3160
	 * @return DataList The objects matching the filter, in the class specified by $containerClass
3161
	 */
3162
	public static function get($callerClass = null, $filter = "", $sort = "", $join = "", $limit = null,
3163
			$containerClass = 'DataList') {
3164
3165
		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...
3166
			$callerClass = get_called_class();
3167
			if($callerClass == 'DataObject') {
3168
				throw new \InvalidArgumentException('Call <classname>::get() instead of DataObject::get()');
3169
			}
3170
3171
			if($filter || $sort || $join || $limit || ($containerClass != 'DataList')) {
3172
				throw new \InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other'
3173
					. ' arguments');
3174
			}
3175
3176
			$result = DataList::create(get_called_class());
3177
			$result->setDataModel(DataModel::inst());
3178
			return $result;
3179
		}
3180
3181
		if($join) {
3182
			throw new \InvalidArgumentException(
3183
				'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.'
3184
			);
3185
		}
3186
3187
		$result = DataList::create($callerClass)->where($filter)->sort($sort);
3188
3189
		if($limit && strpos($limit, ',') !== false) {
3190
			$limitArguments = explode(',', $limit);
3191
			$result = $result->limit($limitArguments[1],$limitArguments[0]);
3192
		} elseif($limit) {
3193
			$result = $result->limit($limit);
3194
		}
3195
3196
		$result->setDataModel(DataModel::inst());
3197
		return $result;
3198
	}
3199
3200
3201
	/**
3202
	 * @deprecated
3203
	 */
3204
	public function Aggregate($class = null) {
3205
		Deprecation::notice('4.0', 'Call aggregate methods on a DataList directly instead. In templates'
3206
			. ' an example of the new syntax is &lt% cached List(Member).max(LastEdited) %&gt instead'
3207
			. ' (check partial-caching.md documentation for more details.)');
3208
3209
		if($class) {
3210
			$list = new DataList($class);
3211
			$list->setDataModel(DataModel::inst());
3212
		} else if(isset($this)) {
3213
			$list = new DataList(get_class($this));
3214
			$list->setDataModel($this->model);
3215
		} else {
3216
			throw new \InvalidArgumentException("DataObject::aggregate() must be called as an instance method or passed"
3217
				. " a classname");
3218
		}
3219
		return $list;
3220
	}
3221
3222
	/**
3223
	 * @deprecated
3224
	 */
3225
	public function RelationshipAggregate($relationship) {
3226
		Deprecation::notice('4.0', 'Call aggregate methods on a relationship directly instead.');
3227
3228
		return $this->$relationship();
3229
	}
3230
3231
	/**
3232
	 * Return the first item matching the given query.
3233
	 * All calls to get_one() are cached.
3234
	 *
3235
	 * @param string $callerClass The class of objects to be returned
3236
	 * @param string|array $filter A filter to be inserted into the WHERE clause.
3237
	 * Supports parameterised queries. See SQLQuery::addWhere() for syntax examples.
3238
	 * @param boolean $cache Use caching
3239
	 * @param string $orderby A sort expression to be inserted into the ORDER BY clause.
3240
	 *
3241
	 * @return DataObject The first item matching the query
3242
	 */
3243
	public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "") {
3244
		$SNG = singleton($callerClass);
3245
3246
		$cacheComponents = array($filter, $orderby, $SNG->extend('cacheKeyComponent'));
3247
		$cacheKey = md5(serialize($cacheComponents));
3248
3249
		// Flush destroyed items out of the cache
3250
		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...
3251
				&& 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...
3252
				&& 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...
3253
3254
			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...
3255
		}
3256
		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...
3257
			$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...
3258
			$item = $dl->First();
3259
3260
			if($cache) {
3261
				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...
3262
				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...
3263
					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...
3264
				}
3265
			}
3266
		}
3267
		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...
3268
	}
3269
3270
	/**
3271
	 * Flush the cached results for all relations (has_one, has_many, many_many)
3272
	 * Also clears any cached aggregate data.
3273
	 *
3274
	 * @param boolean $persistent When true will also clear persistent data stored in the Cache system.
3275
	 *                            When false will just clear session-local cached data
3276
	 * @return DataObject $this
3277
	 */
3278
	public function flushCache($persistent = true) {
3279
		if($persistent) Aggregate::flushCache($this->class);
3280
3281
		if($this->class == 'DataObject') {
3282
			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...
3283
			return $this;
3284
		}
3285
3286
		$classes = ClassInfo::ancestry($this->class);
3287
		foreach($classes as $class) {
3288
			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...
3289
		}
3290
3291
		$this->extend('flushCache');
3292
3293
		$this->components = array();
3294
		return $this;
3295
	}
3296
3297
	/**
3298
	 * Flush the get_one global cache and destroy associated objects.
3299
	 */
3300
	public static function flush_and_destroy_cache() {
3301
		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...
3302
			if(is_array($items)) foreach($items as $item) {
3303
				if($item) $item->destroy();
3304
			}
3305
		}
3306
		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...
3307
	}
3308
3309
	/**
3310
	 * Reset all global caches associated with DataObject.
3311
	 */
3312
	public static function reset() {
3313
		self::clear_classname_spec_cache();
3314
		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...
3315
		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...
3316
		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...
3317
		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...
3318
		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...
3319
		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...
3320
		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...
3321
		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...
3322
	}
3323
3324
	/**
3325
	 * Return the given element, searching by ID
3326
	 *
3327
	 * @param string $callerClass The class of the object to be returned
3328
	 * @param int $id The id of the element
3329
	 * @param boolean $cache See {@link get_one()}
3330
	 *
3331
	 * @return DataObject The element
3332
	 */
3333
	public static function get_by_id($callerClass, $id, $cache = true) {
3334
		if(!is_numeric($id)) {
3335
			user_error("DataObject::get_by_id passed a non-numeric ID #$id", E_USER_WARNING);
3336
		}
3337
3338
		// Check filter column
3339
		if(is_subclass_of($callerClass, 'DataObject')) {
3340
			$baseClass = ClassInfo::baseDataClass($callerClass);
3341
			$column = "\"$baseClass\".\"ID\"";
3342
		} else{
3343
			// This simpler code will be used by non-DataObject classes that implement DataObjectInterface
3344
			$column = '"ID"';
3345
		}
3346
3347
		// Relegate to get_one
3348
		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...
3349
	}
3350
3351
	/**
3352
	 * Get the name of the base table for this object
3353
	 */
3354
	public function baseTable() {
3355
		$tableClasses = ClassInfo::dataClassesFor($this->class);
3356
		return array_shift($tableClasses);
3357
	}
3358
3359
	/**
3360
	 * @var Array Parameters used in the query that built this object.
3361
	 * This can be used by decorators (e.g. lazy loading) to
3362
	 * run additional queries using the same context.
3363
	 */
3364
	protected $sourceQueryParams;
3365
3366
	/**
3367
	 * @see $sourceQueryParams
3368
	 * @return array
3369
	 */
3370
	public function getSourceQueryParams() {
3371
		return $this->sourceQueryParams;
3372
	}
3373
3374
	/**
3375
	 * @see $sourceQueryParams
3376
	 * @param array
3377
	 */
3378
	public function setSourceQueryParams($array) {
3379
		$this->sourceQueryParams = $array;
3380
	}
3381
3382
	/**
3383
	 * @see $sourceQueryParams
3384
	 * @param array
3385
	 */
3386
	public function setSourceQueryParam($key, $value) {
3387
		$this->sourceQueryParams[$key] = $value;
3388
	}
3389
3390
	/**
3391
	 * @see $sourceQueryParams
3392
	 * @return Mixed
3393
	 */
3394
	public function getSourceQueryParam($key) {
3395
		if(isset($this->sourceQueryParams[$key])) return $this->sourceQueryParams[$key];
3396
		else return null;
3397
	}
3398
3399
	//-------------------------------------------------------------------------------------------//
3400
3401
	/**
3402
	 * Return the database indexes on this table.
3403
	 * This array is indexed by the name of the field with the index, and
3404
	 * the value is the type of index.
3405
	 */
3406
	public function databaseIndexes() {
3407
		$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...
3408
		$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...
3409
		$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...
3410
		//$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...
3411
3412
		$indexes = array();
3413
3414
		if($has_one) {
3415
			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...
3416
				$indexes[$relationshipName . 'ID'] = true;
3417
			}
3418
		}
3419
3420
		if($classIndexes) {
3421
			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...
3422
				$indexes[$indexName] = $indexType;
3423
			}
3424
		}
3425
3426
		if ($sort && is_string($sort)) {
3427
			$sort = preg_split('/,(?![^()]*+\\))/', $sort);
3428
3429
			foreach ($sort as $value) {
3430
				try {
3431
					list ($table, $column) = $this->parseSortColumn(trim($value));
3432
3433
					$table = trim($table, '"');
3434
					$column = trim($column, '"');
3435
3436
					if ($table && strtolower($table) !== strtolower($this->class)) {
3437
						continue;
3438
					}
3439
					// Skip already indexed columns
3440
					if (array_key_exists($column, $indexes)) {
3441
						continue;
3442
					}
3443
					// Get field type (including fixed fields) on this table, if it exists
3444
					$fieldType = $this->hasOwnTableDatabaseField($column);
3445
					if (!$fieldType) {
3446
						continue;
3447
					}
3448
					$isAutoIndexable = Config::inst()->get($fieldType, 'auto_indexable')
3449
						|| Config::inst()->get("DB{$fieldType}", 'auto_indexable');
3450
					if ($isAutoIndexable) {
3451
						$indexes[$column] = true;
3452
					}
3453
				} catch (InvalidArgumentException $e) { }
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
3454
			}
3455
		}
3456
3457
		if(get_parent_class($this) == "DataObject") {
3458
			$indexes['ClassName'] = true;
3459
		}
3460
3461
		return $indexes;
3462
	}
3463
3464
	/**
3465
	 * Parses a specified column into a sort field and direction
3466
	 *
3467
	 * @param string $column String to parse containing the column name
3468
	 * @return array Resolved table and column.
3469
	 */
3470
	protected function parseSortColumn($column) {
3471
		// Parse column specification, considering possible ansi sql quoting
3472
		// Note that table prefix is allowed, but discarded
3473
		if(preg_match('/^("?(?<table>[^"\s]+)"?\\.)?"?(?<column>[^"\s]+)"?(\s+(?<direction>((asc)|(desc))(ending)?))?$/i', $column, $match)) {
3474
			$table = $match['table'];
3475
			$column = $match['column'];
3476
		} else {
3477
			throw new InvalidArgumentException("Invalid sort() column");
3478
		}
3479
3480
		return array($table, $column);
3481
	}
3482
3483
	/**
3484
	 * Check the database schema and update it as necessary.
3485
	 *
3486
	 * @uses DataExtension->augmentDatabase()
3487
	 */
3488
	public function requireTable() {
3489
		// Only build the table if we've actually got fields
3490
		$fields = self::database_fields($this->class);
3491
		$extensions = self::database_extensions($this->class);
3492
3493
		$indexes = $this->databaseIndexes();
3494
3495
		// Validate relationship configuration
3496
		$this->validateModelDefinitions();
3497
3498
		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...
3499
			$hasAutoIncPK = ($this->class == ClassInfo::baseDataClass($this->class));
3500
			DB::require_table($this->class, $fields, $indexes, $hasAutoIncPK, $this->stat('create_table_options'),
3501
				$extensions);
3502
		} else {
3503
			DB::dont_require_table($this->class);
3504
		}
3505
3506
		// Build any child tables for many_many items
3507
		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...
3508
			$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...
3509
			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...
3510
				// Build field list
3511
				$manymanyFields = array(
3512
					"{$this->class}ID" => "Int",
3513
				(($this->class == $childClass) ? "ChildID" : "{$childClass}ID") => "Int",
3514
				);
3515
				if(isset($extras[$relationship])) {
3516
					$manymanyFields = array_merge($manymanyFields, $extras[$relationship]);
3517
				}
3518
3519
				// Build index list
3520
				$manymanyIndexes = array(
3521
					"{$this->class}ID" => true,
3522
				(($this->class == $childClass) ? "ChildID" : "{$childClass}ID") => true,
3523
				);
3524
3525
				DB::require_table("{$this->class}_$relationship", $manymanyFields, $manymanyIndexes, true, null,
3526
					$extensions);
3527
			}
3528
		}
3529
3530
		// Let any extentions make their own database fields
3531
		$this->extend('augmentDatabase', $dummy);
3532
	}
3533
3534
	/**
3535
	 * Validate that the configured relations for this class use the correct syntaxes
3536
	 * @throws LogicException
3537
	 */
3538
	protected function validateModelDefinitions() {
3539
		$modelDefinitions = array(
3540
			'db' => Config::inst()->get($this->class, 'db', Config::UNINHERITED),
3541
			'has_one' => Config::inst()->get($this->class, 'has_one', Config::UNINHERITED),
3542
			'has_many' => Config::inst()->get($this->class, 'has_many', Config::UNINHERITED),
3543
			'belongs_to' => Config::inst()->get($this->class, 'belongs_to', Config::UNINHERITED),
3544
			'many_many' => Config::inst()->get($this->class, 'many_many', Config::UNINHERITED),
3545
			'belongs_many_many' => Config::inst()->get($this->class, 'belongs_many_many', Config::UNINHERITED),
3546
			'many_many_extraFields' => Config::inst()->get($this->class, 'many_many_extraFields', Config::UNINHERITED)
3547
		);
3548
3549
		foreach($modelDefinitions as $defType => $relations) {
3550
			if( ! $relations) continue;
3551
3552
			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...
3553
				if($defType === 'many_many_extraFields') {
3554
					if(!is_array($v)) {
3555
						throw new LogicException("$this->class::\$many_many_extraFields has a bad entry: "
3556
							. var_export($k, true) . " => " . var_export($v, true)
3557
							. ". Each many_many_extraFields entry should map to a field specification array.");
3558
					}
3559
				} else {
3560
					if(!is_string($k) || is_numeric($k) || !is_string($v)) {
3561
						throw new LogicException("$this->class::$defType has a bad entry: "
3562
							. var_export($k, true). " => " . var_export($v, true) . ".  Each map key should be a
3563
							 relationship name, and the map value should be the data class to join to.");
3564
					}
3565
				}
3566
			}
3567
		}
3568
	}
3569
3570
	/**
3571
	 * Add default records to database. This function is called whenever the
3572
	 * database is built, after the database tables have all been created. Overload
3573
	 * this to add default records when the database is built, but make sure you
3574
	 * call parent::requireDefaultRecords().
3575
	 *
3576
	 * @uses DataExtension->requireDefaultRecords()
3577
	 */
3578
	public function requireDefaultRecords() {
3579
		$defaultRecords = $this->config()->get('default_records', Config::UNINHERITED);
3580
3581
		if(!empty($defaultRecords)) {
3582
			$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...
3583
			if(!$hasData) {
3584
				$className = $this->class;
3585
				foreach($defaultRecords as $record) {
3586
					$obj = $this->model->$className->newObject($record);
3587
					$obj->write();
3588
				}
3589
				DB::alteration_message("Added default records to $className table","created");
3590
			}
3591
		}
3592
3593
		// Let any extentions make their own database default data
3594
		$this->extend('requireDefaultRecords', $dummy);
3595
	}
3596
3597
	/**
3598
	 * Returns fields bu traversing the class heirachy in a bottom-up direction.
3599
	 *
3600
	 * Needed to avoid getCMSFields being empty when customDatabaseFields overlooks
3601
	 * the inheritance chain of the $db array, where a child data object has no $db array,
3602
	 * but still needs to know the properties of its parent. This should be merged into databaseFields or
3603
	 * customDatabaseFields.
3604
	 *
3605
	 * @todo review whether this is still needed after recent API changes
3606
	 */
3607
	public function inheritedDatabaseFields() {
3608
		$fields     = array();
3609
		$currentObj = $this->class;
3610
3611
		while($currentObj != 'DataObject') {
3612
			$fields     = array_merge($fields, self::custom_database_fields($currentObj));
3613
			$currentObj = get_parent_class($currentObj);
3614
		}
3615
3616
		return (array) $fields;
3617
	}
3618
3619
	/**
3620
	 * Get the default searchable fields for this object, as defined in the
3621
	 * $searchable_fields list. If searchable fields are not defined on the
3622
	 * data object, uses a default selection of summary fields.
3623
	 *
3624
	 * @return array
3625
	 */
3626
	public function searchableFields() {
3627
		// can have mixed format, need to make consistent in most verbose form
3628
		$fields = $this->stat('searchable_fields');
3629
		$labels = $this->fieldLabels();
3630
3631
		// fallback to summary fields (unless empty array is explicitly specified)
3632
		if( ! $fields && ! is_array($fields)) {
3633
			$summaryFields = array_keys($this->summaryFields());
3634
			$fields = array();
3635
3636
			// remove the custom getters as the search should not include them
3637
			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...
3638
				foreach($summaryFields as $key => $name) {
3639
					$spec = $name;
3640
3641
					// Extract field name in case this is a method called on a field (e.g. "Date.Nice")
3642
					if(($fieldPos = strpos($name, '.')) !== false) {
3643
						$name = substr($name, 0, $fieldPos);
3644
					}
3645
3646
					if($this->hasDatabaseField($name)) {
3647
						$fields[] = $name;
3648
					} elseif($this->relObject($spec)) {
3649
						$fields[] = $spec;
3650
					}
3651
				}
3652
			}
3653
		}
3654
3655
		// we need to make sure the format is unified before
3656
		// augmenting fields, so extensions can apply consistent checks
3657
		// but also after augmenting fields, because the extension
3658
		// might use the shorthand notation as well
3659
3660
		// rewrite array, if it is using shorthand syntax
3661
		$rewrite = array();
3662
		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...
3663
			$identifer = (is_int($name)) ? $specOrName : $name;
3664
3665
			if(is_int($name)) {
3666
				// 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...
3667
				$rewrite[$identifer] = array();
3668
			} elseif(is_array($specOrName)) {
3669
				// 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...
3670
				//   'filter => 'ExactMatchFilter',
3671
				//   '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...
3672
				//   '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...
3673
				// ))
3674
				$rewrite[$identifer] = array_merge(
3675
					array('filter' => $this->relObject($identifer)->stat('default_search_filter_class')),
3676
					(array)$specOrName
3677
				);
3678
			} else {
3679
				// 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...
3680
				$rewrite[$identifer] = array(
3681
					'filter' => $specOrName,
3682
				);
3683
			}
3684
			if(!isset($rewrite[$identifer]['title'])) {
3685
				$rewrite[$identifer]['title'] = (isset($labels[$identifer]))
3686
					? $labels[$identifer] : FormField::name_to_label($identifer);
3687
			}
3688
			if(!isset($rewrite[$identifer]['filter'])) {
3689
				$rewrite[$identifer]['filter'] = 'PartialMatchFilter';
3690
			}
3691
		}
3692
3693
		$fields = $rewrite;
3694
3695
		// apply DataExtensions if present
3696
		$this->extend('updateSearchableFields', $fields);
3697
3698
		return $fields;
3699
	}
3700
3701
	/**
3702
	 * Get any user defined searchable fields labels that
3703
	 * exist. Allows overriding of default field names in the form
3704
	 * interface actually presented to the user.
3705
	 *
3706
	 * The reason for keeping this separate from searchable_fields,
3707
	 * which would be a logical place for this functionality, is to
3708
	 * avoid bloating and complicating the configuration array. Currently
3709
	 * much of this system is based on sensible defaults, and this property
3710
	 * would generally only be set in the case of more complex relationships
3711
	 * between data object being required in the search interface.
3712
	 *
3713
	 * Generates labels based on name of the field itself, if no static property
3714
	 * {@link self::field_labels} exists.
3715
	 *
3716
	 * @uses $field_labels
3717
	 * @uses FormField::name_to_label()
3718
	 *
3719
	 * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields
3720
	 *
3721
	 * @return array|string Array of all element labels if no argument given, otherwise the label of the field
3722
	 */
3723
	public function fieldLabels($includerelations = true) {
3724
		$cacheKey = $this->class . '_' . $includerelations;
3725
3726
		if(!isset(self::$_cache_field_labels[$cacheKey])) {
3727
			$customLabels = $this->stat('field_labels');
3728
			$autoLabels = array();
3729
3730
			// get all translated static properties as defined in i18nCollectStatics()
3731
			$ancestry = ClassInfo::ancestry($this->class);
3732
			$ancestry = array_reverse($ancestry);
3733
			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...
3734
				if($ancestorClass == 'ViewableData') break;
3735
				$types = array(
3736
					'db'        => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED)
3737
				);
3738
				if($includerelations){
3739
					$types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED);
3740
					$types['has_many'] = (array)Config::inst()->get($ancestorClass, 'has_many', Config::UNINHERITED);
3741
					$types['many_many'] = (array)Config::inst()->get($ancestorClass, 'many_many', Config::UNINHERITED);
3742
					$types['belongs_many_many'] = (array)Config::inst()->get($ancestorClass, 'belongs_many_many', Config::UNINHERITED);
3743
				}
3744
				foreach($types as $type => $attrs) {
3745
					foreach($attrs as $name => $spec) {
3746
						$autoLabels[$name] = _t("{$ancestorClass}.{$type}_{$name}",FormField::name_to_label($name));
3747
					}
3748
				}
3749
			}
3750
3751
			$labels = array_merge((array)$autoLabels, (array)$customLabels);
3752
			$this->extend('updateFieldLabels', $labels);
3753
			self::$_cache_field_labels[$cacheKey] = $labels;
3754
		}
3755
3756
		return self::$_cache_field_labels[$cacheKey];
3757
	}
3758
3759
	/**
3760
	 * Get a human-readable label for a single field,
3761
	 * see {@link fieldLabels()} for more details.
3762
	 *
3763
	 * @uses fieldLabels()
3764
	 * @uses FormField::name_to_label()
3765
	 *
3766
	 * @param string $name Name of the field
3767
	 * @return string Label of the field
3768
	 */
3769
	public function fieldLabel($name) {
3770
		$labels = $this->fieldLabels();
3771
		return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name);
3772
	}
3773
3774
	/**
3775
	 * Get the default summary fields for this object.
3776
	 *
3777
	 * @todo use the translation apparatus to return a default field selection for the language
3778
	 *
3779
	 * @return array
3780
	 */
3781
	public function summaryFields() {
3782
		$rawFields = $this->stat('summary_fields');
3783
3784
		$fields = array();
3785
		// Merge associative / numeric keys
3786
		if (is_array($rawFields)) {
3787
			foreach ($rawFields as $key => $value) {
3788
				if (is_int($key)) {
3789
					$key = $value;
3790
				}
3791
				$fields[$key] = $value;
3792
			}
3793
		}
3794
3795
		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...
3796
			$fields = array();
3797
			// try to scaffold a couple of usual suspects
3798
			if ($this->hasField('Name')) $fields['Name'] = 'Name';
3799
			if ($this->hasDataBaseField('Title')) $fields['Title'] = 'Title';
3800
			if ($this->hasField('Description')) $fields['Description'] = 'Description';
3801
			if ($this->hasField('FirstName')) $fields['FirstName'] = 'First Name';
3802
		}
3803
		$this->extend("updateSummaryFields", $fields);
3804
3805
		// Final fail-over, just list ID field
3806
		if(!$fields) $fields['ID'] = 'ID';
3807
3808
		// Localize fields (if possible)
3809
		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...
3810
			// only attempt to localize if the label definition is the same as the field name.
3811
			// this will preserve any custom labels set in the summary_fields configuration
3812
			if(isset($fields[$name]) && $name === $fields[$name]) {
3813
				$fields[$name] = $label;
3814
			}
3815
		}
3816
3817
		return $fields;
3818
	}
3819
3820
	/**
3821
	 * Defines a default list of filters for the search context.
3822
	 *
3823
	 * If a filter class mapping is defined on the data object,
3824
	 * it is constructed here. Otherwise, the default filter specified in
3825
	 * {@link DBField} is used.
3826
	 *
3827
	 * @todo error handling/type checking for valid FormField and SearchFilter subclasses?
3828
	 *
3829
	 * @return array
3830
	 */
3831
	public function defaultSearchFilters() {
3832
		$filters = array();
3833
3834
		foreach($this->searchableFields() as $name => $spec) {
3835
			$filterClass = $spec['filter'];
3836
3837
			if($spec['filter'] instanceof SearchFilter) {
3838
				$filters[$name] = $spec['filter'];
3839
			} else {
3840
				$class = $spec['filter'];
3841
3842
				if(!is_subclass_of($spec['filter'], 'SearchFilter')) {
3843
					$class = 'PartialMatchFilter';
3844
				}
3845
3846
				$filters[$name] = new $class($name);
3847
			}
3848
		}
3849
3850
		return $filters;
3851
	}
3852
3853
	/**
3854
	 * @return boolean True if the object is in the database
3855
	 */
3856
	public function isInDB() {
3857
		return is_numeric( $this->ID ) && $this->ID > 0;
3858
	}
3859
3860
	/*
3861
	 * @ignore
3862
	 */
3863
	private static $subclass_access = true;
3864
3865
	/**
3866
	 * Temporarily disable subclass access in data object qeur
3867
	 */
3868
	public static function disable_subclass_access() {
3869
		self::$subclass_access = false;
3870
	}
3871
	public static function enable_subclass_access() {
3872
		self::$subclass_access = true;
3873
	}
3874
3875
	//-------------------------------------------------------------------------------------------//
3876
3877
	/**
3878
	 * Database field definitions.
3879
	 * This is a map from field names to field type. The field
3880
	 * type should be a class that extends .
3881
	 * @var array
3882
	 * @config
3883
	 */
3884
	private static $db = null;
3885
3886
	/**
3887
	 * Use a casting object for a field. This is a map from
3888
	 * field name to class name of the casting object.
3889
	 * @var array
3890
	 */
3891
	private static $casting = array(
3892
		"ID" => 'Int',
3893
		"ClassName" => 'Varchar',
3894
		"LastEdited" => "SS_Datetime",
3895
		"Created" => "SS_Datetime",
3896
		"Title" => 'Text',
3897
	);
3898
3899
	/**
3900
	 * Specify custom options for a CREATE TABLE call.
3901
	 * Can be used to specify a custom storage engine for specific database table.
3902
	 * All options have to be keyed for a specific database implementation,
3903
	 * identified by their class name (extending from {@link SS_Database}).
3904
	 *
3905
	 * <code>
3906
	 * array(
3907
	 *  'MySQLDatabase' => 'ENGINE=MyISAM'
3908
	 * )
3909
	 * </code>
3910
	 *
3911
	 * Caution: This API is experimental, and might not be
3912
	 * included in the next major release. Please use with care.
3913
	 *
3914
	 * @var array
3915
	 * @config
3916
	 */
3917
	private static $create_table_options = array(
3918
		'MySQLDatabase' => 'ENGINE=InnoDB'
3919
	);
3920
3921
	/**
3922
	 * If a field is in this array, then create a database index
3923
	 * on that field. This is a map from fieldname to index type.
3924
	 * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
3925
	 *
3926
	 * @var array
3927
	 * @config
3928
	 */
3929
	private static $indexes = null;
3930
3931
	/**
3932
	 * Inserts standard column-values when a DataObject
3933
	 * is instanciated. Does not insert default records {@see $default_records}.
3934
	 * This is a map from fieldname to default value.
3935
	 *
3936
	 *  - If you would like to change a default value in a sub-class, just specify it.
3937
	 *  - If you would like to disable the default value given by a parent class, set the default value to 0,'',
3938
	 *    or false in your subclass.  Setting it to null won't work.
3939
	 *
3940
	 * @var array
3941
	 * @config
3942
	 */
3943
	private static $defaults = null;
3944
3945
	/**
3946
	 * Multidimensional array which inserts default data into the database
3947
	 * on a db/build-call as long as the database-table is empty. Please use this only
3948
	 * for simple constructs, not for SiteTree-Objects etc. which need special
3949
	 * behaviour such as publishing and ParentNodes.
3950
	 *
3951
	 * Example:
3952
	 * array(
3953
	 *  array('Title' => "DefaultPage1", 'PageTitle' => 'page1'),
3954
	 *  array('Title' => "DefaultPage2")
3955
	 * ).
3956
	 *
3957
	 * @var array
3958
	 * @config
3959
	 */
3960
	private static $default_records = null;
3961
3962
	/**
3963
	 * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a
3964
	 * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class.
3965
	 *
3966
	 * Note that you cannot have a has_one and belongs_to relationship with the same name.
3967
	 *
3968
	 *	@var array
3969
	 * @config
3970
	 */
3971
	private static $has_one = null;
3972
3973
	/**
3974
	 * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.
3975
	 *
3976
	 * This does not actually create any data structures, but allows you to query the other object in a one-to-one
3977
	 * relationship from the child object. If you have multiple belongs_to links to another object you can use the
3978
	 * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use.
3979
	 *
3980
	 * Note that you cannot have a has_one and belongs_to relationship with the same name.
3981
	 *
3982
	 * @var array
3983
	 * @config
3984
	 */
3985
	private static $belongs_to;
3986
3987
	/**
3988
	 * This defines a one-to-many relationship. It is a map of component name to the remote data class.
3989
	 *
3990
	 * This relationship type does not actually create a data structure itself - you need to define a matching $has_one
3991
	 * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this
3992
	 * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show
3993
	 * which foreign key to use.
3994
	 *
3995
	 * @var array
3996
	 * @config
3997
	 */
3998
	private static $has_many = null;
3999
4000
	/**
4001
	 * many-many relationship definitions.
4002
	 * This is a map from component name to data type.
4003
	 * @var array
4004
	 * @config
4005
	 */
4006
	private static $many_many = null;
4007
4008
	/**
4009
	 * Extra fields to include on the connecting many-many table.
4010
	 * This is a map from field name to field type.
4011
	 *
4012
	 * Example code:
4013
	 * <code>
4014
	 * public static $many_many_extraFields = array(
4015
	 *  'Members' => array(
4016
	 *			'Role' => 'Varchar(100)'
4017
	 *		)
4018
	 * );
4019
	 * </code>
4020
	 *
4021
	 * @var array
4022
	 * @config
4023
	 */
4024
	private static $many_many_extraFields = null;
4025
4026
	/**
4027
	 * The inverse side of a many-many relationship.
4028
	 * This is a map from component name to data type.
4029
	 * @var array
4030
	 * @config
4031
	 */
4032
	private static $belongs_many_many = null;
4033
4034
	/**
4035
	 * The default sort expression. This will be inserted in the ORDER BY
4036
	 * clause of a SQL query if no other sort expression is provided.
4037
	 * @var string
4038
	 * @config
4039
	 */
4040
	private static $default_sort = null;
4041
4042
	/**
4043
	 * Default list of fields that can be scaffolded by the ModelAdmin
4044
	 * search interface.
4045
	 *
4046
	 * Overriding the default filter, with a custom defined filter:
4047
	 * <code>
4048
	 *  static $searchable_fields = array(
4049
	 *     "Name" => "PartialMatchFilter"
4050
	 *  );
4051
	 * </code>
4052
	 *
4053
	 * Overriding the default form fields, with a custom defined field.
4054
	 * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}.
4055
	 * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}.
4056
	 * <code>
4057
	 *  static $searchable_fields = array(
4058
	 *    "Name" => array(
4059
	 *      "field" => "TextField"
4060
	 *    )
4061
	 *  );
4062
	 * </code>
4063
	 *
4064
	 * Overriding the default form field, filter and title:
4065
	 * <code>
4066
	 *  static $searchable_fields = array(
4067
	 *    "Organisation.ZipCode" => array(
4068
	 *      "field" => "TextField",
4069
	 *      "filter" => "PartialMatchFilter",
4070
	 *      "title" => 'Organisation ZIP'
4071
	 *    )
4072
	 *  );
4073
	 * </code>
4074
	 * @config
4075
	 */
4076
	private static $searchable_fields = null;
4077
4078
	/**
4079
	 * User defined labels for searchable_fields, used to override
4080
	 * default display in the search form.
4081
	 * @config
4082
	 */
4083
	private static $field_labels = null;
4084
4085
	/**
4086
	 * Provides a default list of fields to be used by a 'summary'
4087
	 * view of this object.
4088
	 * @config
4089
	 */
4090
	private static $summary_fields = null;
4091
4092
	/**
4093
	 * Provides a list of allowed methods that can be called via RESTful api.
4094
	 */
4095
	public static $allowed_actions = null;
4096
4097
	/**
4098
	 * Collect all static properties on the object
4099
	 * which contain natural language, and need to be translated.
4100
	 * The full entity name is composed from the class name and a custom identifier.
4101
	 *
4102
	 * @return array A numerical array which contains one or more entities in array-form.
4103
	 * Each numeric entity array contains the "arguments" for a _t() call as array values:
4104
	 * $entity, $string, $priority, $context.
4105
	 */
4106
	public function provideI18nEntities() {
4107
		$entities = array();
4108
4109
		$entities["{$this->class}.SINGULARNAME"] = array(
4110
			$this->singular_name(),
4111
4112
			'Singular name of the object, used in dropdowns and to generally identify a single object in the interface'
4113
		);
4114
4115
		$entities["{$this->class}.PLURALNAME"] = array(
4116
			$this->plural_name(),
4117
4118
			'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the'
4119
			. ' interface'
4120
		);
4121
4122
		return $entities;
4123
	}
4124
4125
	/**
4126
	 * Returns true if the given method/parameter has a value
4127
	 * (Uses the DBField::hasValue if the parameter is a database field)
4128
	 *
4129
	 * @param string $field The field name
4130
	 * @param array $arguments
4131
	 * @param bool $cache
4132
	 * @return boolean
4133
	 */
4134
	public function hasValue($field, $arguments = null, $cache = true) {
4135
		// has_one fields should not use dbObject to check if a value is given
4136
		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...
4137
			return $obj->exists();
4138
		} else {
4139
			return parent::hasValue($field, $arguments, $cache);
4140
		}
4141
	}
4142
4143
}
4144