Total Complexity | 561 |
Total Lines | 4099 |
Duplicated Lines | 0 % |
Changes | 4 | ||
Bugs | 0 | Features | 0 |
Complex classes like DataObject often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use DataObject, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
109 | class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider, Resettable |
||
110 | { |
||
111 | |||
112 | /** |
||
113 | * Human-readable singular name. |
||
114 | * @var string |
||
115 | * @config |
||
116 | */ |
||
117 | private static $singular_name = null; |
||
118 | |||
119 | /** |
||
120 | * Human-readable plural name |
||
121 | * @var string |
||
122 | * @config |
||
123 | */ |
||
124 | private static $plural_name = null; |
||
125 | |||
126 | /** |
||
127 | * Allow API access to this object? |
||
128 | * @todo Define the options that can be set here |
||
129 | * @config |
||
130 | */ |
||
131 | private static $api_access = false; |
||
132 | |||
133 | /** |
||
134 | * Allows specification of a default value for the ClassName field. |
||
135 | * Configure this value only in subclasses of DataObject. |
||
136 | * |
||
137 | * @config |
||
138 | * @var string |
||
139 | */ |
||
140 | private static $default_classname = null; |
||
141 | |||
142 | /** |
||
143 | * @deprecated 4.0.0:5.0.0 |
||
144 | * @var bool |
||
145 | */ |
||
146 | public $destroyed = false; |
||
147 | |||
148 | /** |
||
149 | * Data stored in this objects database record. An array indexed by fieldname. |
||
150 | * |
||
151 | * Use {@link toMap()} if you want an array representation |
||
152 | * of this object, as the $record array might contain lazy loaded field aliases. |
||
153 | * |
||
154 | * @var array |
||
155 | */ |
||
156 | protected $record; |
||
157 | |||
158 | /** |
||
159 | * If selected through a many_many through relation, this is the instance of the through record |
||
160 | * |
||
161 | * @var DataObject |
||
162 | */ |
||
163 | protected $joinRecord; |
||
164 | |||
165 | /** |
||
166 | * Represents a field that hasn't changed (before === after, thus before == after) |
||
167 | */ |
||
168 | const CHANGE_NONE = 0; |
||
169 | |||
170 | /** |
||
171 | * Represents a field that has changed type, although not the loosely defined value. |
||
172 | * (before !== after && before == after) |
||
173 | * E.g. change 1 to true or "true" to true, but not true to 0. |
||
174 | * Value changes are by nature also considered strict changes. |
||
175 | */ |
||
176 | const CHANGE_STRICT = 1; |
||
177 | |||
178 | /** |
||
179 | * Represents a field that has changed the loosely defined value |
||
180 | * (before != after, thus, before !== after)) |
||
181 | * E.g. change false to true, but not false to 0 |
||
182 | */ |
||
183 | const CHANGE_VALUE = 2; |
||
184 | |||
185 | /** |
||
186 | * An array indexed by fieldname, true if the field has been changed. |
||
187 | * Use {@link getChangedFields()} and {@link isChanged()} to inspect |
||
188 | * the changed state. |
||
189 | * |
||
190 | * @var array |
||
191 | */ |
||
192 | private $changed = []; |
||
193 | |||
194 | /** |
||
195 | * A flag to indicate that a "strict" change of the entire record been forced |
||
196 | * Use {@link getChangedFields()} and {@link isChanged()} to inspect |
||
197 | * the changed state. |
||
198 | * |
||
199 | * @var boolean |
||
200 | */ |
||
201 | private $changeForced = false; |
||
202 | |||
203 | /** |
||
204 | * The database record (in the same format as $record), before |
||
205 | * any changes. |
||
206 | * @var array |
||
207 | */ |
||
208 | protected $original = []; |
||
209 | |||
210 | /** |
||
211 | * Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete() |
||
212 | * @var boolean |
||
213 | */ |
||
214 | protected $brokenOnDelete = false; |
||
215 | |||
216 | /** |
||
217 | * Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite() |
||
218 | * @var boolean |
||
219 | */ |
||
220 | protected $brokenOnWrite = false; |
||
221 | |||
222 | /** |
||
223 | * Should dataobjects be validated before they are written? |
||
224 | * |
||
225 | * Caution: Validation can contain safeguards against invalid/malicious data, |
||
226 | * and check permission levels (e.g. on {@link Group}). Therefore it is recommended |
||
227 | * to only disable validation for very specific use cases. |
||
228 | * |
||
229 | * @config |
||
230 | * @var boolean |
||
231 | */ |
||
232 | private static $validation_enabled = true; |
||
233 | |||
234 | /** |
||
235 | * Static caches used by relevant functions. |
||
236 | * |
||
237 | * @var array |
||
238 | */ |
||
239 | protected static $_cache_get_one; |
||
240 | |||
241 | /** |
||
242 | * Cache of field labels |
||
243 | * |
||
244 | * @var array |
||
245 | */ |
||
246 | protected static $_cache_field_labels = array(); |
||
247 | |||
248 | /** |
||
249 | * Base fields which are not defined in static $db |
||
250 | * |
||
251 | * @config |
||
252 | * @var array |
||
253 | */ |
||
254 | private static $fixed_fields = array( |
||
255 | 'ID' => 'PrimaryKey', |
||
256 | 'ClassName' => 'DBClassName', |
||
257 | 'LastEdited' => 'DBDatetime', |
||
258 | 'Created' => 'DBDatetime', |
||
259 | ); |
||
260 | |||
261 | /** |
||
262 | * Override table name for this class. If ignored will default to FQN of class. |
||
263 | * This option is not inheritable, and must be set on each class. |
||
264 | * If left blank naming will default to the legacy (3.x) behaviour. |
||
265 | * |
||
266 | * @var string |
||
267 | */ |
||
268 | private static $table_name = null; |
||
269 | |||
270 | /** |
||
271 | * Non-static relationship cache, indexed by component name. |
||
272 | * |
||
273 | * @var DataObject[] |
||
274 | */ |
||
275 | protected $components = []; |
||
276 | |||
277 | /** |
||
278 | * Non-static cache of has_many and many_many relations that can't be written until this object is saved. |
||
279 | * |
||
280 | * @var UnsavedRelationList[] |
||
281 | */ |
||
282 | protected $unsavedRelations; |
||
283 | |||
284 | /** |
||
285 | * List of relations that should be cascade deleted, similar to `owns` |
||
286 | * Note: This will trigger delete on many_many objects, not only the mapping table. |
||
287 | * For many_many through you can specify the components you want to delete separately |
||
288 | * (many_many or has_many sub-component) |
||
289 | * |
||
290 | * @config |
||
291 | * @var array |
||
292 | */ |
||
293 | private static $cascade_deletes = []; |
||
294 | |||
295 | /** |
||
296 | * List of relations that should be cascade duplicate. |
||
297 | * many_many duplications are shallow only. |
||
298 | * |
||
299 | * Note: If duplicating a many_many through you should refer to the |
||
300 | * has_many intermediary relation instead, otherwise extra fields |
||
301 | * will be omitted from the duplicated relation. |
||
302 | * |
||
303 | * @var array |
||
304 | */ |
||
305 | private static $cascade_duplicates = []; |
||
306 | |||
307 | /** |
||
308 | * Get schema object |
||
309 | * |
||
310 | * @return DataObjectSchema |
||
311 | */ |
||
312 | public static function getSchema() |
||
313 | { |
||
314 | return Injector::inst()->get(DataObjectSchema::class); |
||
315 | } |
||
316 | |||
317 | /** |
||
318 | * Construct a new DataObject. |
||
319 | * |
||
320 | * @param array|null $record Used internally for rehydrating an object from database content. |
||
321 | * Bypasses setters on this class, and hence should not be used |
||
322 | * for populating data on new records. |
||
323 | * @param boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods. |
||
324 | * Singletons don't have their defaults set. |
||
325 | * @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects. |
||
326 | */ |
||
327 | public function __construct($record = null, $isSingleton = false, $queryParams = array()) |
||
328 | { |
||
329 | parent::__construct(); |
||
330 | |||
331 | // Set query params on the DataObject to tell the lazy loading mechanism the context the object creation context |
||
332 | $this->setSourceQueryParams($queryParams); |
||
333 | |||
334 | // Set the fields data. |
||
335 | if (!$record) { |
||
336 | $record = array( |
||
337 | 'ID' => 0, |
||
338 | 'ClassName' => static::class, |
||
339 | 'RecordClassName' => static::class |
||
340 | ); |
||
341 | } |
||
342 | |||
343 | if ($record instanceof stdClass) { |
||
|
|||
344 | $record = (array)$record; |
||
345 | } |
||
346 | |||
347 | if (!is_array($record)) { |
||
348 | if (is_object($record)) { |
||
349 | $passed = "an object of type '" . get_class($record) . "'"; |
||
350 | } else { |
||
351 | $passed = "The value '$record'"; |
||
352 | } |
||
353 | |||
354 | user_error( |
||
355 | "DataObject::__construct passed $passed. It's supposed to be passed an array," |
||
356 | . " taken straight from the database. Perhaps you should use DataList::create()->First(); instead?", |
||
357 | E_USER_WARNING |
||
358 | ); |
||
359 | $record = null; |
||
360 | } |
||
361 | |||
362 | // Set $this->record to $record, but ignore NULLs |
||
363 | $this->record = array(); |
||
364 | foreach ($record as $k => $v) { |
||
365 | // Ensure that ID is stored as a number and not a string |
||
366 | // To do: this kind of clean-up should be done on all numeric fields, in some relatively |
||
367 | // performant manner |
||
368 | if ($v !== null) { |
||
369 | if ($k == 'ID' && is_numeric($v)) { |
||
370 | $this->record[$k] = (int)$v; |
||
371 | } else { |
||
372 | $this->record[$k] = $v; |
||
373 | } |
||
374 | } |
||
375 | } |
||
376 | |||
377 | // Identify fields that should be lazy loaded, but only on existing records |
||
378 | if (!empty($record['ID'])) { |
||
379 | // Get all field specs scoped to class for later lazy loading |
||
380 | $fields = static::getSchema()->fieldSpecs( |
||
381 | static::class, |
||
382 | DataObjectSchema::INCLUDE_CLASS | DataObjectSchema::DB_ONLY |
||
383 | ); |
||
384 | foreach ($fields as $field => $fieldSpec) { |
||
385 | $fieldClass = strtok($fieldSpec, "."); |
||
386 | if (!array_key_exists($field, $record)) { |
||
387 | $this->record[$field . '_Lazy'] = $fieldClass; |
||
388 | } |
||
389 | } |
||
390 | } |
||
391 | |||
392 | $this->original = $this->record; |
||
393 | |||
394 | // Must be called after parent constructor |
||
395 | if (!$isSingleton && (!isset($this->record['ID']) || !$this->record['ID'])) { |
||
396 | $this->populateDefaults(); |
||
397 | } |
||
398 | |||
399 | // prevent populateDefaults() and setField() from marking overwritten defaults as changed |
||
400 | $this->changed = []; |
||
401 | $this->changeForced = false; |
||
402 | } |
||
403 | |||
404 | /** |
||
405 | * Destroy all of this objects dependant objects and local caches. |
||
406 | * You'll need to call this to get the memory of an object that has components or extensions freed. |
||
407 | */ |
||
408 | public function destroy() |
||
409 | { |
||
410 | $this->flushCache(false); |
||
411 | } |
||
412 | |||
413 | /** |
||
414 | * Create a duplicate of this node. Can duplicate many_many relations |
||
415 | * |
||
416 | * @param bool $doWrite Perform a write() operation before returning the object. |
||
417 | * If this is true, it will create the duplicate in the database. |
||
418 | * @param array|null|false $relations List of relations to duplicate. |
||
419 | * Will default to `cascade_duplicates` if null. |
||
420 | * Set to 'false' to force none. |
||
421 | * Set to specific array of names to duplicate to override these. |
||
422 | * Note: If using versioned, this will additionally failover to `owns` config. |
||
423 | * @return static A duplicate of this node. The exact type will be the type of this node. |
||
424 | */ |
||
425 | public function duplicate($doWrite = true, $relations = null) |
||
426 | { |
||
427 | // Handle legacy behaviour |
||
428 | if (is_string($relations) || $relations === true) { |
||
429 | if ($relations === true) { |
||
430 | $relations = 'many_many'; |
||
431 | } |
||
432 | Deprecation::notice('5.0', 'Use cascade_duplicates config instead of providing a string to duplicate()'); |
||
433 | $relations = array_keys($this->config()->get($relations)) ?: []; |
||
434 | } |
||
435 | |||
436 | // Get duplicates |
||
437 | if ($relations === null) { |
||
438 | $relations = $this->config()->get('cascade_duplicates'); |
||
439 | // Remove any duplicate entries before duplicating them |
||
440 | if (is_array($relations)) { |
||
441 | $relations = array_unique($relations); |
||
442 | } |
||
443 | } |
||
444 | |||
445 | // Create unsaved raw duplicate |
||
446 | $map = $this->toMap(); |
||
447 | unset($map['Created']); |
||
448 | /** @var static $clone */ |
||
449 | $clone = Injector::inst()->create(static::class, $map, false, $this->getSourceQueryParams()); |
||
450 | $clone->ID = 0; |
||
451 | |||
452 | // Note: Extensions such as versioned may update $relations here |
||
453 | $clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite, $relations); |
||
454 | if ($relations) { |
||
455 | $this->duplicateRelations($this, $clone, $relations); |
||
456 | } |
||
457 | if ($doWrite) { |
||
458 | $clone->write(); |
||
459 | } |
||
460 | $clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite, $relations); |
||
461 | |||
462 | return $clone; |
||
463 | } |
||
464 | |||
465 | /** |
||
466 | * Copies the given relations from this object to the destination |
||
467 | * |
||
468 | * @param DataObject $sourceObject the source object to duplicate from |
||
469 | * @param DataObject $destinationObject the destination object to populate with the duplicated relations |
||
470 | * @param array $relations List of relations |
||
471 | */ |
||
472 | protected function duplicateRelations($sourceObject, $destinationObject, $relations) |
||
473 | { |
||
474 | // Get list of duplicable relation types |
||
475 | $manyMany = $sourceObject->manyMany(); |
||
476 | $hasMany = $sourceObject->hasMany(); |
||
477 | $hasOne = $sourceObject->hasOne(); |
||
478 | $belongsTo = $sourceObject->belongsTo(); |
||
479 | |||
480 | // Duplicate each relation based on type |
||
481 | foreach ($relations as $relation) { |
||
482 | switch (true) { |
||
483 | case array_key_exists($relation, $manyMany): { |
||
484 | $this->duplicateManyManyRelation($sourceObject, $destinationObject, $relation); |
||
485 | break; |
||
486 | } |
||
487 | case array_key_exists($relation, $hasMany): { |
||
488 | $this->duplicateHasManyRelation($sourceObject, $destinationObject, $relation); |
||
489 | break; |
||
490 | } |
||
491 | case array_key_exists($relation, $hasOne): { |
||
492 | $this->duplicateHasOneRelation($sourceObject, $destinationObject, $relation); |
||
493 | break; |
||
494 | } |
||
495 | case array_key_exists($relation, $belongsTo): { |
||
496 | $this->duplicateBelongsToRelation($sourceObject, $destinationObject, $relation); |
||
497 | break; |
||
498 | } |
||
499 | default: { |
||
500 | $sourceType = get_class($sourceObject); |
||
501 | throw new InvalidArgumentException( |
||
502 | "Cannot duplicate unknown relation {$relation} on parent type {$sourceType}" |
||
503 | ); |
||
504 | } |
||
505 | } |
||
506 | } |
||
507 | } |
||
508 | |||
509 | /** |
||
510 | * Copies the many_many and belongs_many_many relations from one object to another instance of the name of object. |
||
511 | * |
||
512 | * @deprecated 4.1.0:5.0.0 Use duplicateRelations() instead |
||
513 | * @param DataObject $sourceObject the source object to duplicate from |
||
514 | * @param DataObject $destinationObject the destination object to populate with the duplicated relations |
||
515 | * @param bool|string $filter |
||
516 | */ |
||
517 | protected function duplicateManyManyRelations($sourceObject, $destinationObject, $filter) |
||
518 | { |
||
519 | Deprecation::notice('5.0', 'Use duplicateRelations() instead'); |
||
520 | |||
521 | // Get list of relations to duplicate |
||
522 | if ($filter === 'many_many' || $filter === 'belongs_many_many') { |
||
523 | $relations = $sourceObject->config()->get($filter); |
||
524 | } elseif ($filter === true) { |
||
525 | $relations = $sourceObject->manyMany(); |
||
526 | } else { |
||
527 | throw new InvalidArgumentException("Invalid many_many duplication filter"); |
||
528 | } |
||
529 | foreach ($relations as $manyManyName => $type) { |
||
530 | $this->duplicateManyManyRelation($sourceObject, $destinationObject, $manyManyName); |
||
531 | } |
||
532 | } |
||
533 | |||
534 | /** |
||
535 | * Duplicates a single many_many relation from one object to another. |
||
536 | * |
||
537 | * @param DataObject $sourceObject |
||
538 | * @param DataObject $destinationObject |
||
539 | * @param string $relation |
||
540 | */ |
||
541 | protected function duplicateManyManyRelation($sourceObject, $destinationObject, $relation) |
||
542 | { |
||
543 | // Copy all components from source to destination |
||
544 | $source = $sourceObject->getManyManyComponents($relation); |
||
545 | $dest = $destinationObject->getManyManyComponents($relation); |
||
546 | |||
547 | if ($source instanceof ManyManyList) { |
||
548 | $extraFieldNames = $source->getExtraFields(); |
||
549 | } else { |
||
550 | $extraFieldNames = []; |
||
551 | } |
||
552 | |||
553 | foreach ($source as $item) { |
||
554 | // Merge extra fields |
||
555 | $extraFields = []; |
||
556 | foreach ($extraFieldNames as $fieldName => $fieldType) { |
||
557 | $extraFields[$fieldName] = $item->getField($fieldName); |
||
558 | } |
||
559 | $dest->add($item, $extraFields); |
||
560 | } |
||
561 | } |
||
562 | |||
563 | /** |
||
564 | * Duplicates a single many_many relation from one object to another. |
||
565 | * |
||
566 | * @param DataObject $sourceObject |
||
567 | * @param DataObject $destinationObject |
||
568 | * @param string $relation |
||
569 | */ |
||
570 | protected function duplicateHasManyRelation($sourceObject, $destinationObject, $relation) |
||
571 | { |
||
572 | // Copy all components from source to destination |
||
573 | $source = $sourceObject->getComponents($relation); |
||
574 | $dest = $destinationObject->getComponents($relation); |
||
575 | |||
576 | /** @var DataObject $item */ |
||
577 | foreach ($source as $item) { |
||
578 | // Don't write on duplicate; Wait until ParentID is available later. |
||
579 | // writeRelations() will eventually write these records when converting |
||
580 | // from UnsavedRelationList |
||
581 | $clonedItem = $item->duplicate(false); |
||
582 | $dest->add($clonedItem); |
||
583 | } |
||
584 | } |
||
585 | |||
586 | /** |
||
587 | * Duplicates a single has_one relation from one object to another. |
||
588 | * Note: Child object will be force written. |
||
589 | * |
||
590 | * @param DataObject $sourceObject |
||
591 | * @param DataObject $destinationObject |
||
592 | * @param string $relation |
||
593 | */ |
||
594 | protected function duplicateHasOneRelation($sourceObject, $destinationObject, $relation) |
||
595 | { |
||
596 | // Check if original object exists |
||
597 | $item = $sourceObject->getComponent($relation); |
||
598 | if (!$item->isInDB()) { |
||
599 | return; |
||
600 | } |
||
601 | |||
602 | $clonedItem = $item->duplicate(false); |
||
603 | $destinationObject->setComponent($relation, $clonedItem); |
||
604 | } |
||
605 | |||
606 | /** |
||
607 | * Duplicates a single belongs_to relation from one object to another. |
||
608 | * Note: This will force a write on both parent / child objects. |
||
609 | * |
||
610 | * @param DataObject $sourceObject |
||
611 | * @param DataObject $destinationObject |
||
612 | * @param string $relation |
||
613 | */ |
||
614 | protected function duplicateBelongsToRelation($sourceObject, $destinationObject, $relation) |
||
615 | { |
||
616 | // Check if original object exists |
||
617 | $item = $sourceObject->getComponent($relation); |
||
618 | if (!$item->isInDB()) { |
||
619 | return; |
||
620 | } |
||
621 | |||
622 | $clonedItem = $item->duplicate(false); |
||
623 | $destinationObject->setComponent($relation, $clonedItem); |
||
624 | // After $clonedItem is assigned the appropriate FieldID / FieldClass, force write |
||
625 | // @todo Write this component in onAfterWrite instead, assigning the FieldID then |
||
626 | // https://github.com/silverstripe/silverstripe-framework/issues/7818 |
||
627 | $clonedItem->write(); |
||
628 | } |
||
629 | |||
630 | /** |
||
631 | * Return obsolete class name, if this is no longer a valid class |
||
632 | * |
||
633 | * @return string |
||
634 | */ |
||
635 | public function getObsoleteClassName() |
||
636 | { |
||
637 | $className = $this->getField("ClassName"); |
||
638 | if (!ClassInfo::exists($className)) { |
||
639 | return $className; |
||
640 | } |
||
641 | return null; |
||
642 | } |
||
643 | |||
644 | /** |
||
645 | * Gets name of this class |
||
646 | * |
||
647 | * @return string |
||
648 | */ |
||
649 | public function getClassName() |
||
650 | { |
||
651 | $className = $this->getField("ClassName"); |
||
652 | if (!ClassInfo::exists($className)) { |
||
653 | return static::class; |
||
654 | } |
||
655 | return $className; |
||
656 | } |
||
657 | |||
658 | /** |
||
659 | * Set the ClassName attribute. {@link $class} is also updated. |
||
660 | * Warning: This will produce an inconsistent record, as the object |
||
661 | * instance will not automatically switch to the new subclass. |
||
662 | * Please use {@link newClassInstance()} for this purpose, |
||
663 | * or destroy and reinstanciate the record. |
||
664 | * |
||
665 | * @param string $className The new ClassName attribute (a subclass of {@link DataObject}) |
||
666 | * @return $this |
||
667 | */ |
||
668 | public function setClassName($className) |
||
669 | { |
||
670 | $className = trim($className); |
||
671 | if (!$className || !is_subclass_of($className, self::class)) { |
||
672 | return $this; |
||
673 | } |
||
674 | |||
675 | $this->setField("ClassName", $className); |
||
676 | $this->setField('RecordClassName', $className); |
||
677 | return $this; |
||
678 | } |
||
679 | |||
680 | /** |
||
681 | * Create a new instance of a different class from this object's record. |
||
682 | * This is useful when dynamically changing the type of an instance. Specifically, |
||
683 | * it ensures that the instance of the class is a match for the className of the |
||
684 | * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName} |
||
685 | * property manually before calling this method, as it will confuse change detection. |
||
686 | * |
||
687 | * If the new class is different to the original class, defaults are populated again |
||
688 | * because this will only occur automatically on instantiation of a DataObject if |
||
689 | * there is no record, or the record has no ID. In this case, we do have an ID but |
||
690 | * we still need to repopulate the defaults. |
||
691 | * |
||
692 | * @param string $newClassName The name of the new class |
||
693 | * |
||
694 | * @return DataObject The new instance of the new class, The exact type will be of the class name provided. |
||
695 | */ |
||
696 | public function newClassInstance($newClassName) |
||
697 | { |
||
698 | if (!is_subclass_of($newClassName, self::class)) { |
||
699 | throw new InvalidArgumentException("$newClassName is not a valid subclass of DataObject"); |
||
700 | } |
||
701 | |||
702 | $originalClass = $this->ClassName; |
||
703 | |||
704 | /** @var DataObject $newInstance */ |
||
705 | $newInstance = Injector::inst()->create($newClassName, $this->record, false); |
||
706 | |||
707 | // Modify ClassName |
||
708 | if ($newClassName != $originalClass) { |
||
709 | $newInstance->setClassName($newClassName); |
||
710 | $newInstance->populateDefaults(); |
||
711 | $newInstance->forceChange(); |
||
712 | } |
||
713 | |||
714 | return $newInstance; |
||
715 | } |
||
716 | |||
717 | /** |
||
718 | * Adds methods from the extensions. |
||
719 | * Called by Object::__construct() once per class. |
||
720 | */ |
||
721 | public function defineMethods() |
||
722 | { |
||
723 | parent::defineMethods(); |
||
724 | |||
725 | if (static::class === self::class) { |
||
726 | return; |
||
727 | } |
||
728 | |||
729 | // Set up accessors for joined items |
||
730 | if ($manyMany = $this->manyMany()) { |
||
731 | foreach ($manyMany as $relationship => $class) { |
||
732 | $this->addWrapperMethod($relationship, 'getManyManyComponents'); |
||
733 | } |
||
734 | } |
||
735 | if ($hasMany = $this->hasMany()) { |
||
736 | foreach ($hasMany as $relationship => $class) { |
||
737 | $this->addWrapperMethod($relationship, 'getComponents'); |
||
738 | } |
||
739 | } |
||
740 | if ($hasOne = $this->hasOne()) { |
||
741 | foreach ($hasOne as $relationship => $class) { |
||
742 | $this->addWrapperMethod($relationship, 'getComponent'); |
||
743 | } |
||
744 | } |
||
745 | if ($belongsTo = $this->belongsTo()) { |
||
746 | foreach (array_keys($belongsTo) as $relationship) { |
||
747 | $this->addWrapperMethod($relationship, 'getComponent'); |
||
748 | } |
||
749 | } |
||
750 | } |
||
751 | |||
752 | /** |
||
753 | * Returns true if this object "exists", i.e., has a sensible value. |
||
754 | * The default behaviour for a DataObject is to return true if |
||
755 | * the object exists in the database, you can override this in subclasses. |
||
756 | * |
||
757 | * @return boolean true if this object exists |
||
758 | */ |
||
759 | public function exists() |
||
760 | { |
||
761 | return (isset($this->record['ID']) && $this->record['ID'] > 0); |
||
762 | } |
||
763 | |||
764 | /** |
||
765 | * Returns TRUE if all values (other than "ID") are |
||
766 | * considered empty (by weak boolean comparison). |
||
767 | * |
||
768 | * @return boolean |
||
769 | */ |
||
770 | public function isEmpty() |
||
771 | { |
||
772 | $fixed = DataObject::config()->uninherited('fixed_fields'); |
||
773 | foreach ($this->toMap() as $field => $value) { |
||
774 | // only look at custom fields |
||
775 | if (isset($fixed[$field])) { |
||
776 | continue; |
||
777 | } |
||
778 | |||
779 | $dbObject = $this->dbObject($field); |
||
780 | if (!$dbObject) { |
||
781 | continue; |
||
782 | } |
||
783 | if ($dbObject->exists()) { |
||
784 | return false; |
||
785 | } |
||
786 | } |
||
787 | return true; |
||
788 | } |
||
789 | |||
790 | /** |
||
791 | * Pluralise this item given a specific count. |
||
792 | * |
||
793 | * E.g. "0 Pages", "1 File", "3 Images" |
||
794 | * |
||
795 | * @param string $count |
||
796 | * @return string |
||
797 | */ |
||
798 | public function i18n_pluralise($count) |
||
799 | { |
||
800 | $default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name(); |
||
801 | return i18n::_t( |
||
802 | static::class . '.PLURALS', |
||
803 | $default, |
||
804 | ['count' => $count] |
||
805 | ); |
||
806 | } |
||
807 | |||
808 | /** |
||
809 | * Get the user friendly singular name of this DataObject. |
||
810 | * If the name is not defined (by redefining $singular_name in the subclass), |
||
811 | * this returns the class name. |
||
812 | * |
||
813 | * @return string User friendly singular name of this DataObject |
||
814 | */ |
||
815 | public function singular_name() |
||
816 | { |
||
817 | $name = $this->config()->get('singular_name'); |
||
818 | if ($name) { |
||
819 | return $name; |
||
820 | } |
||
821 | return ucwords(trim(strtolower(preg_replace( |
||
822 | '/_?([A-Z])/', |
||
823 | ' $1', |
||
824 | ClassInfo::shortName($this) |
||
825 | )))); |
||
826 | } |
||
827 | |||
828 | /** |
||
829 | * Get the translated user friendly singular name of this DataObject |
||
830 | * same as singular_name() but runs it through the translating function |
||
831 | * |
||
832 | * Translating string is in the form: |
||
833 | * $this->class.SINGULARNAME |
||
834 | * Example: |
||
835 | * Page.SINGULARNAME |
||
836 | * |
||
837 | * @return string User friendly translated singular name of this DataObject |
||
838 | */ |
||
839 | public function i18n_singular_name() |
||
840 | { |
||
841 | return _t(static::class . '.SINGULARNAME', $this->singular_name()); |
||
842 | } |
||
843 | |||
844 | /** |
||
845 | * Get the user friendly plural name of this DataObject |
||
846 | * If the name is not defined (by renaming $plural_name in the subclass), |
||
847 | * this returns a pluralised version of the class name. |
||
848 | * |
||
849 | * @return string User friendly plural name of this DataObject |
||
850 | */ |
||
851 | public function plural_name() |
||
852 | { |
||
853 | if ($name = $this->config()->get('plural_name')) { |
||
854 | return $name; |
||
855 | } |
||
856 | $name = $this->singular_name(); |
||
857 | //if the penultimate character is not a vowel, replace "y" with "ies" |
||
858 | if (preg_match('/[^aeiou]y$/i', $name)) { |
||
859 | $name = substr($name, 0, -1) . 'ie'; |
||
860 | } |
||
861 | return ucfirst($name . 's'); |
||
862 | } |
||
863 | |||
864 | /** |
||
865 | * Get the translated user friendly plural name of this DataObject |
||
866 | * Same as plural_name but runs it through the translation function |
||
867 | * Translation string is in the form: |
||
868 | * $this->class.PLURALNAME |
||
869 | * Example: |
||
870 | * Page.PLURALNAME |
||
871 | * |
||
872 | * @return string User friendly translated plural name of this DataObject |
||
873 | */ |
||
874 | public function i18n_plural_name() |
||
875 | { |
||
876 | return _t(static::class . '.PLURALNAME', $this->plural_name()); |
||
877 | } |
||
878 | |||
879 | /** |
||
880 | * Standard implementation of a title/label for a specific |
||
881 | * record. Tries to find properties 'Title' or 'Name', |
||
882 | * and falls back to the 'ID'. Useful to provide |
||
883 | * user-friendly identification of a record, e.g. in errormessages |
||
884 | * or UI-selections. |
||
885 | * |
||
886 | * Overload this method to have a more specialized implementation, |
||
887 | * e.g. for an Address record this could be: |
||
888 | * <code> |
||
889 | * function getTitle() { |
||
890 | * return "{$this->StreetNumber} {$this->StreetName} {$this->City}"; |
||
891 | * } |
||
892 | * </code> |
||
893 | * |
||
894 | * @return string |
||
895 | */ |
||
896 | public function getTitle() |
||
897 | { |
||
898 | $schema = static::getSchema(); |
||
899 | if ($schema->fieldSpec($this, 'Title')) { |
||
900 | return $this->getField('Title'); |
||
901 | } |
||
902 | if ($schema->fieldSpec($this, 'Name')) { |
||
903 | return $this->getField('Name'); |
||
904 | } |
||
905 | |||
906 | return "#{$this->ID}"; |
||
907 | } |
||
908 | |||
909 | /** |
||
910 | * Returns the associated database record - in this case, the object itself. |
||
911 | * This is included so that you can call $dataOrController->data() and get a DataObject all the time. |
||
912 | * |
||
913 | * @return DataObject Associated database record |
||
914 | */ |
||
915 | public function data() |
||
916 | { |
||
917 | return $this; |
||
918 | } |
||
919 | |||
920 | /** |
||
921 | * Convert this object to a map. |
||
922 | * |
||
923 | * @return array The data as a map. |
||
924 | */ |
||
925 | public function toMap() |
||
926 | { |
||
927 | $this->loadLazyFields(); |
||
928 | return $this->record; |
||
929 | } |
||
930 | |||
931 | /** |
||
932 | * Return all currently fetched database fields. |
||
933 | * |
||
934 | * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields. |
||
935 | * Obviously, this makes it a lot faster. |
||
936 | * |
||
937 | * @return array The data as a map. |
||
938 | */ |
||
939 | public function getQueriedDatabaseFields() |
||
940 | { |
||
941 | return $this->record; |
||
942 | } |
||
943 | |||
944 | /** |
||
945 | * Update a number of fields on this object, given a map of the desired changes. |
||
946 | * |
||
947 | * The field names can be simple names, or you can use a dot syntax to access $has_one relations. |
||
948 | * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim". |
||
949 | * |
||
950 | * Doesn't write the main object, but if you use the dot syntax, it will write() |
||
951 | * the related objects that it alters. |
||
952 | * |
||
953 | * When using this method with user supplied data, it's very important to |
||
954 | * whitelist the allowed keys. |
||
955 | * |
||
956 | * @param array $data A map of field name to data values to update. |
||
957 | * @return DataObject $this |
||
958 | */ |
||
959 | public function update($data) |
||
960 | { |
||
961 | foreach ($data as $key => $value) { |
||
962 | // Implement dot syntax for updates |
||
963 | if (strpos($key, '.') !== false) { |
||
964 | $relations = explode('.', $key); |
||
965 | $fieldName = array_pop($relations); |
||
966 | /** @var static $relObj */ |
||
967 | $relObj = $this; |
||
968 | $relation = null; |
||
969 | foreach ($relations as $i => $relation) { |
||
970 | // no support for has_many or many_many relationships, |
||
971 | // as the updater wouldn't know which object to write to (or create) |
||
972 | if ($relObj->$relation() instanceof DataObject) { |
||
973 | $parentObj = $relObj; |
||
974 | $relObj = $relObj->$relation(); |
||
975 | // If the intermediate relationship objects haven't been created, then write them |
||
976 | if ($i < sizeof($relations) - 1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) { |
||
977 | $relObj->write(); |
||
978 | $relatedFieldName = $relation . "ID"; |
||
979 | $parentObj->$relatedFieldName = $relObj->ID; |
||
980 | $parentObj->write(); |
||
981 | } |
||
982 | } else { |
||
983 | user_error( |
||
984 | "DataObject::update(): Can't traverse relationship '$relation'," . |
||
985 | "it has to be a has_one relationship or return a single DataObject", |
||
986 | E_USER_NOTICE |
||
987 | ); |
||
988 | // unset relation object so we don't write properties to the wrong object |
||
989 | $relObj = null; |
||
990 | break; |
||
991 | } |
||
992 | } |
||
993 | |||
994 | if ($relObj) { |
||
995 | $relObj->$fieldName = $value; |
||
996 | $relObj->write(); |
||
997 | $relatedFieldName = $relation . "ID"; |
||
998 | $this->$relatedFieldName = $relObj->ID; |
||
999 | $relObj->flushCache(); |
||
1000 | } else { |
||
1001 | $class = static::class; |
||
1002 | user_error("Couldn't follow dot syntax '{$key}' on '{$class}' object", E_USER_WARNING); |
||
1003 | } |
||
1004 | } else { |
||
1005 | $this->$key = $value; |
||
1006 | } |
||
1007 | } |
||
1008 | return $this; |
||
1009 | } |
||
1010 | |||
1011 | /** |
||
1012 | * Pass changes as a map, and try to |
||
1013 | * get automatic casting for these fields. |
||
1014 | * Doesn't write to the database. To write the data, |
||
1015 | * use the write() method. |
||
1016 | * |
||
1017 | * @param array $data A map of field name to data values to update. |
||
1018 | * @return DataObject $this |
||
1019 | */ |
||
1020 | public function castedUpdate($data) |
||
1021 | { |
||
1022 | foreach ($data as $k => $v) { |
||
1023 | $this->setCastedField($k, $v); |
||
1024 | } |
||
1025 | return $this; |
||
1026 | } |
||
1027 | |||
1028 | /** |
||
1029 | * Merges data and relations from another object of same class, |
||
1030 | * without conflict resolution. Allows to specify which |
||
1031 | * dataset takes priority in case its not empty. |
||
1032 | * has_one-relations are just transferred with priority 'right'. |
||
1033 | * has_many and many_many-relations are added regardless of priority. |
||
1034 | * |
||
1035 | * Caution: has_many/many_many relations are moved rather than duplicated, |
||
1036 | * meaning they are not connected to the merged object any longer. |
||
1037 | * Caution: Just saves updated has_many/many_many relations to the database, |
||
1038 | * doesn't write the updated object itself (just writes the object-properties). |
||
1039 | * Caution: Does not delete the merged object. |
||
1040 | * Caution: Does now overwrite Created date on the original object. |
||
1041 | * |
||
1042 | * @param DataObject $rightObj |
||
1043 | * @param string $priority left|right Determines who wins in case of a conflict (optional) |
||
1044 | * @param bool $includeRelations Merge any existing relations (optional) |
||
1045 | * @param bool $overwriteWithEmpty Overwrite existing left values with empty right values. |
||
1046 | * Only applicable with $priority='right'. (optional) |
||
1047 | * @return Boolean |
||
1048 | */ |
||
1049 | public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false) |
||
1050 | { |
||
1051 | $leftObj = $this; |
||
1052 | |||
1053 | if ($leftObj->ClassName != $rightObj->ClassName) { |
||
1054 | // we can't merge similiar subclasses because they might have additional relations |
||
1055 | user_error("DataObject->merge(): Invalid object class '{$rightObj->ClassName}' |
||
1056 | (expected '{$leftObj->ClassName}').", E_USER_WARNING); |
||
1057 | return false; |
||
1058 | } |
||
1059 | |||
1060 | if (!$rightObj->ID) { |
||
1061 | user_error("DataObject->merge(): Please write your merged-in object to the database before merging, |
||
1062 | to make sure all relations are transferred properly.').", E_USER_WARNING); |
||
1063 | return false; |
||
1064 | } |
||
1065 | |||
1066 | // makes sure we don't merge data like ID or ClassName |
||
1067 | $rightData = DataObject::getSchema()->fieldSpecs(get_class($rightObj)); |
||
1068 | foreach ($rightData as $key => $rightSpec) { |
||
1069 | // Don't merge ID |
||
1070 | if ($key === 'ID') { |
||
1071 | continue; |
||
1072 | } |
||
1073 | |||
1074 | // Only merge relations if allowed |
||
1075 | if ($rightSpec === 'ForeignKey' && !$includeRelations) { |
||
1076 | continue; |
||
1077 | } |
||
1078 | |||
1079 | // don't merge conflicting values if priority is 'left' |
||
1080 | if ($priority == 'left' && $leftObj->{$key} !== $rightObj->{$key}) { |
||
1081 | continue; |
||
1082 | } |
||
1083 | |||
1084 | // don't overwrite existing left values with empty right values (if $overwriteWithEmpty is set) |
||
1085 | if ($priority == 'right' && !$overwriteWithEmpty && empty($rightObj->{$key})) { |
||
1086 | continue; |
||
1087 | } |
||
1088 | |||
1089 | // TODO remove redundant merge of has_one fields |
||
1090 | $leftObj->{$key} = $rightObj->{$key}; |
||
1091 | } |
||
1092 | |||
1093 | // merge relations |
||
1094 | if ($includeRelations) { |
||
1095 | if ($manyMany = $this->manyMany()) { |
||
1096 | foreach ($manyMany as $relationship => $class) { |
||
1097 | /** @var DataObject $leftComponents */ |
||
1098 | $leftComponents = $leftObj->getManyManyComponents($relationship); |
||
1099 | $rightComponents = $rightObj->getManyManyComponents($relationship); |
||
1100 | if ($rightComponents && $rightComponents->exists()) { |
||
1101 | $leftComponents->addMany($rightComponents->column('ID')); |
||
1102 | } |
||
1103 | $leftComponents->write(); |
||
1104 | } |
||
1105 | } |
||
1106 | |||
1107 | if ($hasMany = $this->hasMany()) { |
||
1108 | foreach ($hasMany as $relationship => $class) { |
||
1109 | $leftComponents = $leftObj->getComponents($relationship); |
||
1110 | $rightComponents = $rightObj->getComponents($relationship); |
||
1111 | if ($rightComponents && $rightComponents->exists()) { |
||
1112 | $leftComponents->addMany($rightComponents->column('ID')); |
||
1113 | } |
||
1114 | $leftComponents->write(); |
||
1115 | } |
||
1116 | } |
||
1117 | } |
||
1118 | |||
1119 | return true; |
||
1120 | } |
||
1121 | |||
1122 | /** |
||
1123 | * Forces the record to think that all its data has changed. |
||
1124 | * Doesn't write to the database. Force-change preseved until |
||
1125 | * next write. Existing CHANGE_VALUE or CHANGE_STRICT values |
||
1126 | * are preserved. |
||
1127 | * |
||
1128 | * @return $this |
||
1129 | */ |
||
1130 | public function forceChange() |
||
1131 | { |
||
1132 | // Ensure lazy fields loaded |
||
1133 | $this->loadLazyFields(); |
||
1134 | |||
1135 | // Populate the null values in record so that they actually get written |
||
1136 | foreach (array_keys(static::getSchema()->fieldSpecs(static::class)) as $fieldName) { |
||
1137 | if (!isset($this->record[$fieldName])) { |
||
1138 | $this->record[$fieldName] = null; |
||
1139 | } |
||
1140 | } |
||
1141 | |||
1142 | $this->changeForced = true; |
||
1143 | |||
1144 | return $this; |
||
1145 | } |
||
1146 | |||
1147 | /** |
||
1148 | * Validate the current object. |
||
1149 | * |
||
1150 | * By default, there is no validation - objects are always valid! However, you can overload this method in your |
||
1151 | * DataObject sub-classes to specify custom validation, or use the hook through DataExtension. |
||
1152 | * |
||
1153 | * Invalid objects won't be able to be written - a warning will be thrown and no write will occur. onBeforeWrite() |
||
1154 | * and onAfterWrite() won't get called either. |
||
1155 | * |
||
1156 | * It is expected that you call validate() in your own application to test that an object is valid before |
||
1157 | * attempting a write, and respond appropriately if it isn't. |
||
1158 | * |
||
1159 | * @see {@link ValidationResult} |
||
1160 | * @return ValidationResult |
||
1161 | */ |
||
1162 | public function validate() |
||
1163 | { |
||
1164 | $result = ValidationResult::create(); |
||
1165 | $this->extend('validate', $result); |
||
1166 | return $result; |
||
1167 | } |
||
1168 | |||
1169 | /** |
||
1170 | * Public accessor for {@see DataObject::validate()} |
||
1171 | * |
||
1172 | * @return ValidationResult |
||
1173 | */ |
||
1174 | public function doValidate() |
||
1175 | { |
||
1176 | Deprecation::notice('5.0', 'Use validate'); |
||
1177 | return $this->validate(); |
||
1178 | } |
||
1179 | |||
1180 | /** |
||
1181 | * Event handler called before writing to the database. |
||
1182 | * You can overload this to clean up or otherwise process data before writing it to the |
||
1183 | * database. Don't forget to call parent::onBeforeWrite(), though! |
||
1184 | * |
||
1185 | * This called after {@link $this->validate()}, so you can be sure that your data is valid. |
||
1186 | * |
||
1187 | * @uses DataExtension->onBeforeWrite() |
||
1188 | */ |
||
1189 | protected function onBeforeWrite() |
||
1190 | { |
||
1191 | $this->brokenOnWrite = false; |
||
1192 | |||
1193 | $dummy = null; |
||
1194 | $this->extend('onBeforeWrite', $dummy); |
||
1195 | } |
||
1196 | |||
1197 | /** |
||
1198 | * Event handler called after writing to the database. |
||
1199 | * You can overload this to act upon changes made to the data after it is written. |
||
1200 | * $this->changed will have a record |
||
1201 | * database. Don't forget to call parent::onAfterWrite(), though! |
||
1202 | * |
||
1203 | * @uses DataExtension->onAfterWrite() |
||
1204 | */ |
||
1205 | protected function onAfterWrite() |
||
1206 | { |
||
1207 | $dummy = null; |
||
1208 | $this->extend('onAfterWrite', $dummy); |
||
1209 | } |
||
1210 | |||
1211 | /** |
||
1212 | * Find all objects that will be cascade deleted if this object is deleted |
||
1213 | * |
||
1214 | * Notes: |
||
1215 | * - If this object is versioned, objects will only be searched in the same stage as the given record. |
||
1216 | * - This will only be useful prior to deletion, as post-deletion this record will no longer exist. |
||
1217 | * |
||
1218 | * @param bool $recursive True if recursive |
||
1219 | * @param ArrayList $list Optional list to add items to |
||
1220 | * @return ArrayList list of objects |
||
1221 | */ |
||
1222 | public function findCascadeDeletes($recursive = true, $list = null) |
||
1223 | { |
||
1224 | // Find objects in these relationships |
||
1225 | return $this->findRelatedObjects('cascade_deletes', $recursive, $list); |
||
1226 | } |
||
1227 | |||
1228 | /** |
||
1229 | * Event handler called before deleting from the database. |
||
1230 | * You can overload this to clean up or otherwise process data before delete this |
||
1231 | * record. Don't forget to call parent::onBeforeDelete(), though! |
||
1232 | * |
||
1233 | * @uses DataExtension->onBeforeDelete() |
||
1234 | */ |
||
1235 | protected function onBeforeDelete() |
||
1236 | { |
||
1237 | $this->brokenOnDelete = false; |
||
1238 | |||
1239 | $dummy = null; |
||
1240 | $this->extend('onBeforeDelete', $dummy); |
||
1241 | |||
1242 | // Cascade deletes |
||
1243 | $deletes = $this->findCascadeDeletes(false); |
||
1244 | foreach ($deletes as $delete) { |
||
1245 | $delete->delete(); |
||
1246 | } |
||
1247 | } |
||
1248 | |||
1249 | protected function onAfterDelete() |
||
1250 | { |
||
1251 | $this->extend('onAfterDelete'); |
||
1252 | } |
||
1253 | |||
1254 | /** |
||
1255 | * Load the default values in from the self::$defaults array. |
||
1256 | * Will traverse the defaults of the current class and all its parent classes. |
||
1257 | * Called by the constructor when creating new records. |
||
1258 | * |
||
1259 | * @uses DataExtension->populateDefaults() |
||
1260 | * @return DataObject $this |
||
1261 | */ |
||
1262 | public function populateDefaults() |
||
1263 | { |
||
1264 | $classes = array_reverse(ClassInfo::ancestry($this)); |
||
1265 | |||
1266 | foreach ($classes as $class) { |
||
1267 | $defaults = Config::inst()->get($class, 'defaults', Config::UNINHERITED); |
||
1268 | |||
1269 | if ($defaults && !is_array($defaults)) { |
||
1270 | user_error( |
||
1271 | "Bad '" . static::class . "' defaults given: " . var_export($defaults, true), |
||
1272 | E_USER_WARNING |
||
1273 | ); |
||
1274 | $defaults = null; |
||
1275 | } |
||
1276 | |||
1277 | if ($defaults) { |
||
1278 | foreach ($defaults as $fieldName => $fieldValue) { |
||
1279 | // SRM 2007-03-06: Stricter check |
||
1280 | if (!isset($this->$fieldName) || $this->$fieldName === null) { |
||
1281 | $this->$fieldName = $fieldValue; |
||
1282 | } |
||
1283 | // Set many-many defaults with an array of ids |
||
1284 | if (is_array($fieldValue) && $this->getSchema()->manyManyComponent(static::class, $fieldName)) { |
||
1285 | /** @var ManyManyList $manyManyJoin */ |
||
1286 | $manyManyJoin = $this->$fieldName(); |
||
1287 | $manyManyJoin->setByIDList($fieldValue); |
||
1288 | } |
||
1289 | } |
||
1290 | } |
||
1291 | if ($class == self::class) { |
||
1292 | break; |
||
1293 | } |
||
1294 | } |
||
1295 | |||
1296 | $this->extend('populateDefaults'); |
||
1297 | return $this; |
||
1298 | } |
||
1299 | |||
1300 | /** |
||
1301 | * Determine validation of this object prior to write |
||
1302 | * |
||
1303 | * @return ValidationException Exception generated by this write, or null if valid |
||
1304 | */ |
||
1305 | protected function validateWrite() |
||
1306 | { |
||
1307 | if ($this->ObsoleteClassName) { |
||
1308 | return new ValidationException( |
||
1309 | "Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " . |
||
1310 | "you need to change the ClassName before you can write it" |
||
1311 | ); |
||
1312 | } |
||
1313 | |||
1314 | // Note: Validation can only be disabled at the global level, not per-model |
||
1315 | if (DataObject::config()->uninherited('validation_enabled')) { |
||
1316 | $result = $this->validate(); |
||
1317 | if (!$result->isValid()) { |
||
1318 | return new ValidationException($result); |
||
1319 | } |
||
1320 | } |
||
1321 | return null; |
||
1322 | } |
||
1323 | |||
1324 | /** |
||
1325 | * Prepare an object prior to write |
||
1326 | * |
||
1327 | * @throws ValidationException |
||
1328 | */ |
||
1329 | protected function preWrite() |
||
1330 | { |
||
1331 | // Validate this object |
||
1332 | if ($writeException = $this->validateWrite()) { |
||
1333 | // Used by DODs to clean up after themselves, eg, Versioned |
||
1334 | $this->invokeWithExtensions('onAfterSkippedWrite'); |
||
1335 | throw $writeException; |
||
1336 | } |
||
1337 | |||
1338 | // Check onBeforeWrite |
||
1339 | $this->brokenOnWrite = true; |
||
1340 | $this->onBeforeWrite(); |
||
1341 | if ($this->brokenOnWrite) { |
||
1342 | user_error(static::class . " has a broken onBeforeWrite() function." |
||
1343 | . " Make sure that you call parent::onBeforeWrite().", E_USER_ERROR); |
||
1344 | } |
||
1345 | } |
||
1346 | |||
1347 | /** |
||
1348 | * Detects and updates all changes made to this object |
||
1349 | * |
||
1350 | * @param bool $forceChanges If set to true, force all fields to be treated as changed |
||
1351 | * @return bool True if any changes are detected |
||
1352 | */ |
||
1353 | protected function updateChanges($forceChanges = false) |
||
1363 | } |
||
1364 | |||
1365 | /** |
||
1366 | * Writes a subset of changes for a specific table to the given manipulation |
||
1367 | * |
||
1368 | * @param string $baseTable Base table |
||
1369 | * @param string $now Timestamp to use for the current time |
||
1370 | * @param bool $isNewRecord Whether this should be treated as a new record write |
||
1371 | * @param array $manipulation Manipulation to write to |
||
1372 | * @param string $class Class of table to manipulate |
||
1373 | */ |
||
1374 | protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class) |
||
1375 | { |
||
1376 | $schema = $this->getSchema(); |
||
1377 | $table = $schema->tableName($class); |
||
1378 | $manipulation[$table] = array(); |
||
1379 | |||
1380 | $changed = $this->getChangedFields(); |
||
1381 | |||
1382 | // Extract records for this table |
||
1383 | foreach ($this->record as $fieldName => $fieldValue) { |
||
1384 | // we're not attempting to reset the BaseTable->ID |
||
1385 | // Ignore unchanged fields or attempts to reset the BaseTable->ID |
||
1386 | if (empty($changed[$fieldName]) || ($table === $baseTable && $fieldName === 'ID')) { |
||
1387 | continue; |
||
1388 | } |
||
1389 | |||
1390 | // Ensure this field pertains to this table |
||
1391 | $specification = $schema->fieldSpec( |
||
1392 | $class, |
||
1393 | $fieldName, |
||
1394 | DataObjectSchema::DB_ONLY | DataObjectSchema::UNINHERITED |
||
1395 | ); |
||
1396 | if (!$specification) { |
||
1397 | continue; |
||
1398 | } |
||
1399 | |||
1400 | // if database column doesn't correlate to a DBField instance... |
||
1401 | $fieldObj = $this->dbObject($fieldName); |
||
1402 | if (!$fieldObj) { |
||
1403 | $fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName); |
||
1404 | } |
||
1405 | |||
1406 | // Write to manipulation |
||
1407 | $fieldObj->writeToManipulation($manipulation[$table]); |
||
1408 | } |
||
1409 | |||
1410 | // Ensure update of Created and LastEdited columns |
||
1411 | if ($baseTable === $table) { |
||
1412 | $manipulation[$table]['fields']['LastEdited'] = $now; |
||
1413 | if ($isNewRecord) { |
||
1414 | $manipulation[$table]['fields']['Created'] = empty($this->record['Created']) |
||
1415 | ? $now |
||
1416 | : $this->record['Created']; |
||
1417 | $manipulation[$table]['fields']['ClassName'] = static::class; |
||
1418 | } |
||
1419 | } |
||
1420 | |||
1421 | // Inserts done one the base table are performed in another step, so the manipulation should instead |
||
1422 | // attempt an update, as though it were a normal update. |
||
1423 | $manipulation[$table]['command'] = $isNewRecord ? 'insert' : 'update'; |
||
1424 | $manipulation[$table]['class'] = $class; |
||
1425 | if ($this->isInDB()) { |
||
1426 | $manipulation[$table]['id'] = $this->record['ID']; |
||
1427 | } |
||
1428 | } |
||
1429 | |||
1430 | /** |
||
1431 | * Ensures that a blank base record exists with the basic fixed fields for this dataobject |
||
1432 | * |
||
1433 | * Does nothing if an ID is already assigned for this record |
||
1434 | * |
||
1435 | * @param string $baseTable Base table |
||
1436 | * @param string $now Timestamp to use for the current time |
||
1437 | */ |
||
1438 | protected function writeBaseRecord($baseTable, $now) |
||
1452 | } |
||
1453 | |||
1454 | /** |
||
1455 | * Generate and write the database manipulation for all changed fields |
||
1456 | * |
||
1457 | * @param string $baseTable Base table |
||
1458 | * @param string $now Timestamp to use for the current time |
||
1459 | * @param bool $isNewRecord If this is a new record |
||
1460 | * @throws InvalidArgumentException |
||
1461 | */ |
||
1462 | protected function writeManipulation($baseTable, $now, $isNewRecord) |
||
1499 | } |
||
1500 | |||
1501 | /** |
||
1502 | * Writes all changes to this object to the database. |
||
1503 | * - It will insert a record whenever ID isn't set, otherwise update. |
||
1504 | * - All relevant tables will be updated. |
||
1505 | * - $this->onBeforeWrite() gets called beforehand. |
||
1506 | * - Extensions such as Versioned will ammend the database-write to ensure that a version is saved. |
||
1507 | * |
||
1508 | * @uses DataExtension->augmentWrite() |
||
1509 | * |
||
1510 | * @param boolean $showDebug Show debugging information |
||
1511 | * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists |
||
1512 | * @param boolean $forceWrite Write to database even if there are no changes |
||
1513 | * @param boolean|array $writeComponents Call write() on all associated component instances which were previously |
||
1514 | * retrieved through {@link getComponent()}, {@link getComponents()} or |
||
1515 | * {@link getManyManyComponents()}. Default to `false`. The parameter can also be provided in |
||
1516 | * the form of an array: `['recursive' => true, skip => ['Page'=>[1,2,3]]`. This avoid infinite |
||
1517 | * loops when one DataObject are components of each other. |
||
1518 | * @return int The ID of the record |
||
1519 | * @throws ValidationException Exception that can be caught and handled by the calling function |
||
1520 | */ |
||
1521 | public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) |
||
1522 | { |
||
1523 | $now = DBDatetime::now()->Rfc2822(); |
||
1524 | |||
1525 | // Execute pre-write tasks |
||
1526 | $this->preWrite(); |
||
1527 | |||
1528 | // Check if we are doing an update or an insert |
||
1529 | $isNewRecord = !$this->isInDB() || $forceInsert; |
||
1530 | |||
1531 | // Check changes exist, abort if there are none |
||
1532 | $hasChanges = $this->updateChanges($isNewRecord); |
||
1533 | if ($hasChanges || $forceWrite || $isNewRecord) { |
||
1534 | // Ensure Created and LastEdited are populated |
||
1535 | if (!isset($this->record['Created'])) { |
||
1536 | $this->record['Created'] = $now; |
||
1537 | } |
||
1538 | $this->record['LastEdited'] = $now; |
||
1539 | |||
1540 | // New records have their insert into the base data table done first, so that they can pass the |
||
1541 | // generated primary key on to the rest of the manipulation |
||
1542 | $baseTable = $this->baseTable(); |
||
1543 | $this->writeBaseRecord($baseTable, $now); |
||
1544 | |||
1545 | // Write the DB manipulation for all changed fields |
||
1546 | $this->writeManipulation($baseTable, $now, $isNewRecord); |
||
1547 | |||
1548 | // If there's any relations that couldn't be saved before, save them now (we have an ID here) |
||
1549 | $this->writeRelations(); |
||
1550 | $this->onAfterWrite(); |
||
1551 | |||
1552 | // Reset isChanged data |
||
1553 | // DBComposites properly bound to the parent record will also have their isChanged value reset |
||
1554 | $this->changed = []; |
||
1555 | $this->changeForced = false; |
||
1556 | $this->original = $this->record; |
||
1557 | } else { |
||
1558 | if ($showDebug) { |
||
1559 | Debug::message("no changes for DataObject"); |
||
1560 | } |
||
1561 | |||
1562 | // Used by DODs to clean up after themselves, eg, Versioned |
||
1563 | $this->invokeWithExtensions('onAfterSkippedWrite'); |
||
1564 | } |
||
1565 | |||
1566 | // Write relations as necessary |
||
1567 | if ($writeComponents) { |
||
1568 | $recursive = true; |
||
1569 | $skip = []; |
||
1570 | if (is_array($writeComponents)) { |
||
1571 | $recursive = isset($writeComponents['recursive']) && $writeComponents['recursive']; |
||
1572 | $skip = isset($writeComponents['skip']) && is_array($writeComponents['skip']) |
||
1573 | ? $writeComponents['skip'] |
||
1574 | : []; |
||
1575 | } |
||
1576 | $this->writeComponents($recursive, $skip); |
||
1577 | } |
||
1578 | |||
1579 | // Clears the cache for this object so get_one returns the correct object. |
||
1580 | $this->flushCache(); |
||
1581 | |||
1582 | return $this->record['ID']; |
||
1583 | } |
||
1584 | |||
1585 | /** |
||
1586 | * Writes cached relation lists to the database, if possible |
||
1587 | */ |
||
1588 | public function writeRelations() |
||
1589 | { |
||
1590 | if (!$this->isInDB()) { |
||
1591 | return; |
||
1592 | } |
||
1593 | |||
1594 | // If there's any relations that couldn't be saved before, save them now (we have an ID here) |
||
1595 | if ($this->unsavedRelations) { |
||
1596 | foreach ($this->unsavedRelations as $name => $list) { |
||
1597 | $list->changeToList($this->$name()); |
||
1598 | } |
||
1599 | $this->unsavedRelations = array(); |
||
1600 | } |
||
1601 | } |
||
1602 | |||
1603 | /** |
||
1604 | * Write the cached components to the database. Cached components could refer to two different instances of the |
||
1605 | * same record. |
||
1606 | * |
||
1607 | * @param bool $recursive Recursively write components |
||
1608 | * @param array $skip List of DataObject references to skip |
||
1609 | * @return DataObject $this |
||
1610 | */ |
||
1611 | public function writeComponents($recursive = false, $skip = []) |
||
1612 | { |
||
1613 | // Make sure we add our current object to the skip list |
||
1614 | $this->skipWriteComponents($recursive, $this, $skip); |
||
1615 | |||
1616 | // All our write calls have the same arguments ... just need make sure the skip list is pass by reference |
||
1617 | $args = [ |
||
1618 | false, false, false, |
||
1619 | $recursive ? ["recursive" => $recursive, "skip" => &$skip] : false |
||
1620 | ]; |
||
1621 | |||
1622 | foreach ($this->components as $component) { |
||
1623 | if (!$this->skipWriteComponents($recursive, $component, $skip)) { |
||
1624 | $component->write(...$args); |
||
1625 | } |
||
1626 | } |
||
1627 | |||
1628 | if ($join = $this->getJoin()) { |
||
1629 | if (!$this->skipWriteComponents($recursive, $join, $skip)) { |
||
1630 | $join->write(...$args); |
||
1631 | } |
||
1632 | } |
||
1633 | |||
1634 | return $this; |
||
1635 | } |
||
1636 | |||
1637 | /** |
||
1638 | * Check if target is in the skip list and add it if it isn't. |
||
1639 | * @param bool $recursive |
||
1640 | * @param DataObject $target |
||
1641 | * @param array $skip |
||
1642 | * @return bool Whether the target is already in the list |
||
1643 | */ |
||
1644 | private function skipWriteComponents($recursive, DataObject $target, array &$skip) |
||
1645 | { |
||
1646 | // We only care about the skip list if our call is meant to be recursive |
||
1647 | if (!$recursive) { |
||
1648 | return false; |
||
1649 | } |
||
1650 | |||
1651 | // Get our Skip array keys |
||
1652 | $classname = get_class($target); |
||
1653 | $id = $target->ID; |
||
1654 | |||
1655 | // Check if the target is in the skip list |
||
1656 | if (isset($skip[$classname])) { |
||
1657 | if (in_array($id, $skip[$classname])) { |
||
1658 | // Skip the object |
||
1659 | return true; |
||
1660 | } |
||
1661 | } else { |
||
1662 | // This is the first object of this class |
||
1663 | $skip[$classname] = []; |
||
1664 | } |
||
1665 | |||
1666 | // Add the target to our skip list |
||
1667 | $skip[$classname][] = $id; |
||
1668 | |||
1669 | return false; |
||
1670 | } |
||
1671 | |||
1672 | /** |
||
1673 | * Delete this data object. |
||
1674 | * $this->onBeforeDelete() gets called. |
||
1675 | * Note that in Versioned objects, both Stage and Live will be deleted. |
||
1676 | * @uses DataExtension->augmentSQL() |
||
1677 | */ |
||
1678 | public function delete() |
||
1679 | { |
||
1680 | $this->brokenOnDelete = true; |
||
1681 | $this->onBeforeDelete(); |
||
1682 | if ($this->brokenOnDelete) { |
||
1683 | user_error(static::class . " has a broken onBeforeDelete() function." |
||
1684 | . " Make sure that you call parent::onBeforeDelete().", E_USER_ERROR); |
||
1685 | } |
||
1686 | |||
1687 | // Deleting a record without an ID shouldn't do anything |
||
1688 | if (!$this->ID) { |
||
1689 | throw new LogicException("DataObject::delete() called on a DataObject without an ID"); |
||
1690 | } |
||
1691 | |||
1692 | // TODO: This is quite ugly. To improve: |
||
1693 | // - move the details of the delete code in the DataQuery system |
||
1694 | // - update the code to just delete the base table, and rely on cascading deletes in the DB to do the rest |
||
1695 | // obviously, that means getting requireTable() to configure cascading deletes ;-) |
||
1696 | $srcQuery = DataList::create(static::class) |
||
1697 | ->filter('ID', $this->ID) |
||
1698 | ->dataQuery() |
||
1699 | ->query(); |
||
1700 | $queriedTables = $srcQuery->queriedTables(); |
||
1701 | $this->extend('updateDeleteTables', $queriedTables, $srcQuery); |
||
1702 | foreach ($queriedTables as $table) { |
||
1703 | $delete = SQLDelete::create("\"$table\"", array('"ID"' => $this->ID)); |
||
1704 | $this->extend('updateDeleteTable', $delete, $table, $queriedTables, $srcQuery); |
||
1705 | $delete->execute(); |
||
1706 | } |
||
1707 | // Remove this item out of any caches |
||
1708 | $this->flushCache(); |
||
1709 | |||
1710 | $this->onAfterDelete(); |
||
1711 | |||
1712 | $this->OldID = $this->ID; |
||
1713 | $this->ID = 0; |
||
1714 | } |
||
1715 | |||
1716 | /** |
||
1717 | * Delete the record with the given ID. |
||
1718 | * |
||
1719 | * @param string $className The class name of the record to be deleted |
||
1720 | * @param int $id ID of record to be deleted |
||
1721 | */ |
||
1722 | public static function delete_by_id($className, $id) |
||
1723 | { |
||
1724 | $obj = DataObject::get_by_id($className, $id); |
||
1725 | if ($obj) { |
||
1726 | $obj->delete(); |
||
1727 | } else { |
||
1728 | user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING); |
||
1729 | } |
||
1730 | } |
||
1731 | |||
1732 | /** |
||
1733 | * Get the class ancestry, including the current class name. |
||
1734 | * The ancestry will be returned as an array of class names, where the 0th element |
||
1735 | * will be the class that inherits directly from DataObject, and the last element |
||
1736 | * will be the current class. |
||
1737 | * |
||
1738 | * @return array Class ancestry |
||
1739 | */ |
||
1740 | public function getClassAncestry() |
||
1741 | { |
||
1742 | return ClassInfo::ancestry(static::class); |
||
1743 | } |
||
1744 | |||
1745 | /** |
||
1746 | * Return a unary component object from a one to one relationship, as a DataObject. |
||
1747 | * If no component is available, an 'empty component' will be returned for |
||
1748 | * non-polymorphic relations, or for polymorphic relations with a class set. |
||
1749 | * |
||
1750 | * @param string $componentName Name of the component |
||
1751 | * @return DataObject The component object. It's exact type will be that of the component. |
||
1752 | * @throws Exception |
||
1753 | */ |
||
1754 | public function getComponent($componentName) |
||
1755 | { |
||
1756 | if (isset($this->components[$componentName])) { |
||
1757 | return $this->components[$componentName]; |
||
1758 | } |
||
1759 | |||
1760 | $schema = static::getSchema(); |
||
1761 | if ($class = $schema->hasOneComponent(static::class, $componentName)) { |
||
1762 | $joinField = $componentName . 'ID'; |
||
1763 | $joinID = $this->getField($joinField); |
||
1764 | |||
1765 | // Extract class name for polymorphic relations |
||
1766 | if ($class === self::class) { |
||
1767 | $class = $this->getField($componentName . 'Class'); |
||
1768 | if (empty($class)) { |
||
1769 | return null; |
||
1770 | } |
||
1771 | } |
||
1772 | |||
1773 | if ($joinID) { |
||
1774 | // Ensure that the selected object originates from the same stage, subsite, etc |
||
1775 | $component = DataObject::get($class) |
||
1776 | ->filter('ID', $joinID) |
||
1777 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
1778 | ->first(); |
||
1779 | } |
||
1780 | |||
1781 | if (empty($component)) { |
||
1782 | $component = Injector::inst()->create($class); |
||
1783 | } |
||
1784 | } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) { |
||
1785 | $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic); |
||
1786 | $joinID = $this->ID; |
||
1787 | |||
1788 | if ($joinID) { |
||
1789 | // Prepare filter for appropriate join type |
||
1790 | if ($polymorphic) { |
||
1791 | $filter = array( |
||
1792 | "{$joinField}ID" => $joinID, |
||
1793 | "{$joinField}Class" => static::class, |
||
1794 | ); |
||
1795 | } else { |
||
1796 | $filter = array( |
||
1797 | $joinField => $joinID |
||
1798 | ); |
||
1799 | } |
||
1800 | |||
1801 | // Ensure that the selected object originates from the same stage, subsite, etc |
||
1802 | $component = DataObject::get($class) |
||
1803 | ->filter($filter) |
||
1804 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
1805 | ->first(); |
||
1806 | } |
||
1807 | |||
1808 | if (empty($component)) { |
||
1809 | $component = Injector::inst()->create($class); |
||
1810 | if ($polymorphic) { |
||
1811 | $component->{$joinField . 'ID'} = $this->ID; |
||
1812 | $component->{$joinField . 'Class'} = static::class; |
||
1813 | } else { |
||
1814 | $component->$joinField = $this->ID; |
||
1815 | } |
||
1816 | } |
||
1817 | } else { |
||
1818 | throw new InvalidArgumentException( |
||
1819 | "DataObject->getComponent(): Could not find component '$componentName'." |
||
1820 | ); |
||
1821 | } |
||
1822 | |||
1823 | $this->components[$componentName] = $component; |
||
1824 | return $component; |
||
1825 | } |
||
1826 | |||
1827 | /** |
||
1828 | * Assign an item to the given component |
||
1829 | * |
||
1830 | * @param string $componentName |
||
1831 | * @param DataObject|null $item |
||
1832 | * @return $this |
||
1833 | */ |
||
1834 | public function setComponent($componentName, $item) |
||
1835 | { |
||
1836 | // Validate component |
||
1837 | $schema = static::getSchema(); |
||
1838 | if ($class = $schema->hasOneComponent(static::class, $componentName)) { |
||
1839 | // Force item to be written if not by this point |
||
1840 | // @todo This could be lazy-written in a beforeWrite hook, but force write here for simplicity |
||
1841 | // https://github.com/silverstripe/silverstripe-framework/issues/7818 |
||
1842 | if ($item && !$item->isInDB()) { |
||
1843 | $item->write(); |
||
1844 | } |
||
1845 | |||
1846 | // Update local ID |
||
1847 | $joinField = $componentName . 'ID'; |
||
1848 | $this->setField($joinField, $item ? $item->ID : null); |
||
1849 | // Update Class (Polymorphic has_one) |
||
1850 | // Extract class name for polymorphic relations |
||
1851 | if ($class === self::class) { |
||
1852 | $this->setField($componentName . 'Class', $item ? get_class($item) : null); |
||
1853 | } |
||
1854 | } elseif ($class = $schema->belongsToComponent(static::class, $componentName)) { |
||
1855 | if ($item) { |
||
1856 | // For belongs_to, add to has_one on other component |
||
1857 | $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic); |
||
1858 | if (!$polymorphic) { |
||
1859 | $joinField = substr($joinField, 0, -2); |
||
1860 | } |
||
1861 | $item->setComponent($joinField, $this); |
||
1862 | } |
||
1863 | } else { |
||
1864 | throw new InvalidArgumentException( |
||
1865 | "DataObject->setComponent(): Could not find component '$componentName'." |
||
1866 | ); |
||
1867 | } |
||
1868 | |||
1869 | $this->components[$componentName] = $item; |
||
1870 | return $this; |
||
1871 | } |
||
1872 | |||
1873 | /** |
||
1874 | * Returns a one-to-many relation as a HasManyList |
||
1875 | * |
||
1876 | * @param string $componentName Name of the component |
||
1877 | * @param int|array $id Optional ID(s) for parent of this relation, if not the current record |
||
1878 | * @return HasManyList|UnsavedRelationList The components of the one-to-many relationship. |
||
1879 | */ |
||
1880 | public function getComponents($componentName, $id = null) |
||
1881 | { |
||
1882 | if (!isset($id)) { |
||
1883 | $id = $this->ID; |
||
1884 | } |
||
1885 | $result = null; |
||
1886 | |||
1887 | $schema = $this->getSchema(); |
||
1888 | $componentClass = $schema->hasManyComponent(static::class, $componentName); |
||
1889 | if (!$componentClass) { |
||
1890 | throw new InvalidArgumentException(sprintf( |
||
1891 | "DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'", |
||
1892 | $componentName, |
||
1893 | static::class |
||
1894 | )); |
||
1895 | } |
||
1896 | |||
1897 | // If we haven't been written yet, we can't save these relations, so use a list that handles this case |
||
1898 | if (!$id) { |
||
1899 | if (!isset($this->unsavedRelations[$componentName])) { |
||
1900 | $this->unsavedRelations[$componentName] = |
||
1901 | new UnsavedRelationList(static::class, $componentName, $componentClass); |
||
1902 | } |
||
1903 | return $this->unsavedRelations[$componentName]; |
||
1904 | } |
||
1905 | |||
1906 | // Determine type and nature of foreign relation |
||
1907 | $joinField = $schema->getRemoteJoinField(static::class, $componentName, 'has_many', $polymorphic); |
||
1908 | /** @var HasManyList $result */ |
||
1909 | if ($polymorphic) { |
||
1910 | $result = PolymorphicHasManyList::create($componentClass, $joinField, static::class); |
||
1911 | } else { |
||
1912 | $result = HasManyList::create($componentClass, $joinField); |
||
1913 | } |
||
1914 | |||
1915 | return $result |
||
1916 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
1917 | ->forForeignID($id); |
||
1918 | } |
||
1919 | |||
1920 | /** |
||
1921 | * Find the foreign class of a relation on this DataObject, regardless of the relation type. |
||
1922 | * |
||
1923 | * @param string $relationName Relation name. |
||
1924 | * @return string Class name, or null if not found. |
||
1925 | */ |
||
1926 | public function getRelationClass($relationName) |
||
1927 | { |
||
1928 | // Parse many_many |
||
1929 | $manyManyComponent = $this->getSchema()->manyManyComponent(static::class, $relationName); |
||
1930 | if ($manyManyComponent) { |
||
1931 | return $manyManyComponent['childClass']; |
||
1932 | } |
||
1933 | |||
1934 | // Go through all relationship configuration fields. |
||
1935 | $config = $this->config(); |
||
1936 | $candidates = array_merge( |
||
1937 | ($relations = $config->get('has_one')) ? $relations : array(), |
||
1938 | ($relations = $config->get('has_many')) ? $relations : array(), |
||
1939 | ($relations = $config->get('belongs_to')) ? $relations : array() |
||
1940 | ); |
||
1941 | |||
1942 | if (isset($candidates[$relationName])) { |
||
1943 | $remoteClass = $candidates[$relationName]; |
||
1944 | |||
1945 | // If dot notation is present, extract just the first part that contains the class. |
||
1946 | if (($fieldPos = strpos($remoteClass, '.')) !== false) { |
||
1947 | return substr($remoteClass, 0, $fieldPos); |
||
1948 | } |
||
1949 | |||
1950 | // Otherwise just return the class |
||
1951 | return $remoteClass; |
||
1952 | } |
||
1953 | |||
1954 | return null; |
||
1955 | } |
||
1956 | |||
1957 | /** |
||
1958 | * Given a relation name, determine the relation type |
||
1959 | * |
||
1960 | * @param string $component Name of component |
||
1961 | * @return string has_one, has_many, many_many, belongs_many_many or belongs_to |
||
1962 | */ |
||
1963 | public function getRelationType($component) |
||
1964 | { |
||
1965 | $types = array('has_one', 'has_many', 'many_many', 'belongs_many_many', 'belongs_to'); |
||
1966 | $config = $this->config(); |
||
1967 | foreach ($types as $type) { |
||
1968 | $relations = $config->get($type); |
||
1969 | if ($relations && isset($relations[$component])) { |
||
1970 | return $type; |
||
1971 | } |
||
1972 | } |
||
1973 | return null; |
||
1974 | } |
||
1975 | |||
1976 | /** |
||
1977 | * Given a relation declared on a remote class, generate a substitute component for the opposite |
||
1978 | * side of the relation. |
||
1979 | * |
||
1980 | * Notes on behaviour: |
||
1981 | * - This can still be used on components that are defined on both sides, but do not need to be. |
||
1982 | * - All has_ones on remote class will be treated as local has_many, even if they are belongs_to |
||
1983 | * - Polymorphic relationships do not have two natural endpoints (only on one side) |
||
1984 | * and thus attempting to infer them will return nothing. |
||
1985 | * - Cannot be used on unsaved objects. |
||
1986 | * |
||
1987 | * @param string $remoteClass |
||
1988 | * @param string $remoteRelation |
||
1989 | * @return DataList|DataObject The component, either as a list or single object |
||
1990 | * @throws BadMethodCallException |
||
1991 | * @throws InvalidArgumentException |
||
1992 | */ |
||
1993 | public function inferReciprocalComponent($remoteClass, $remoteRelation) |
||
1994 | { |
||
1995 | $remote = DataObject::singleton($remoteClass); |
||
1996 | $class = $remote->getRelationClass($remoteRelation); |
||
1997 | $schema = static::getSchema(); |
||
1998 | |||
1999 | // Validate arguments |
||
2000 | if (!$this->isInDB()) { |
||
2001 | throw new BadMethodCallException(__METHOD__ . " cannot be called on unsaved objects"); |
||
2002 | } |
||
2003 | if (empty($class)) { |
||
2004 | throw new InvalidArgumentException(sprintf( |
||
2005 | "%s invoked with invalid relation %s.%s", |
||
2006 | __METHOD__, |
||
2007 | $remoteClass, |
||
2008 | $remoteRelation |
||
2009 | )); |
||
2010 | } |
||
2011 | // If relation is polymorphic, do not infer recriprocal relationship |
||
2012 | if ($class === self::class) { |
||
2013 | return null; |
||
2014 | } |
||
2015 | if (!is_a($this, $class, true)) { |
||
2016 | throw new InvalidArgumentException(sprintf( |
||
2017 | "Relation %s on %s does not refer to objects of type %s", |
||
2018 | $remoteRelation, |
||
2019 | $remoteClass, |
||
2020 | static::class |
||
2021 | )); |
||
2022 | } |
||
2023 | |||
2024 | // Check the relation type to mock |
||
2025 | $relationType = $remote->getRelationType($remoteRelation); |
||
2026 | switch ($relationType) { |
||
2027 | case 'has_one': { |
||
2028 | // Mock has_many |
||
2029 | $joinField = "{$remoteRelation}ID"; |
||
2030 | $componentClass = $schema->classForField($remoteClass, $joinField); |
||
2031 | $result = HasManyList::create($componentClass, $joinField); |
||
2032 | return $result |
||
2033 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
2034 | ->forForeignID($this->ID); |
||
2035 | } |
||
2036 | case 'belongs_to': |
||
2037 | case 'has_many': { |
||
2038 | // These relations must have a has_one on the other end, so find it |
||
2039 | $joinField = $schema->getRemoteJoinField( |
||
2040 | $remoteClass, |
||
2041 | $remoteRelation, |
||
2042 | $relationType, |
||
2043 | $polymorphic |
||
2044 | ); |
||
2045 | // If relation is polymorphic, do not infer recriprocal relationship automatically |
||
2046 | if ($polymorphic) { |
||
2047 | return null; |
||
2048 | } |
||
2049 | $joinID = $this->getField($joinField); |
||
2050 | if (empty($joinID)) { |
||
2051 | return null; |
||
2052 | } |
||
2053 | // Get object by joined ID |
||
2054 | return DataObject::get($remoteClass) |
||
2055 | ->filter('ID', $joinID) |
||
2056 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
2057 | ->first(); |
||
2058 | } |
||
2059 | case 'many_many': |
||
2060 | case 'belongs_many_many': { |
||
2061 | // Get components and extra fields from parent |
||
2062 | $manyMany = $remote->getSchema()->manyManyComponent($remoteClass, $remoteRelation); |
||
2063 | $extraFields = $schema->manyManyExtraFieldsForComponent($remoteClass, $remoteRelation) ?: array(); |
||
2064 | |||
2065 | // Reverse parent and component fields and create an inverse ManyManyList |
||
2066 | /** @var RelationList $result */ |
||
2067 | $result = Injector::inst()->create( |
||
2068 | $manyMany['relationClass'], |
||
2069 | $manyMany['parentClass'], // Substitute parent class for dataClass |
||
2070 | $manyMany['join'], |
||
2071 | $manyMany['parentField'], // Reversed parent / child field |
||
2072 | $manyMany['childField'], // Reversed parent / child field |
||
2073 | $extraFields, |
||
2074 | $manyMany['childClass'], // substitute child class for parentClass |
||
2075 | $remoteClass // In case ManyManyThroughList needs to use PolymorphicHasManyList internally |
||
2076 | ); |
||
2077 | $this->extend('updateManyManyComponents', $result); |
||
2078 | |||
2079 | // If this is called on a singleton, then we return an 'orphaned relation' that can have the |
||
2080 | // foreignID set elsewhere. |
||
2081 | return $result |
||
2082 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
2083 | ->forForeignID($this->ID); |
||
2084 | } |
||
2085 | default: { |
||
2086 | return null; |
||
2087 | } |
||
2088 | } |
||
2089 | } |
||
2090 | |||
2091 | /** |
||
2092 | * Returns a many-to-many component, as a ManyManyList. |
||
2093 | * @param string $componentName Name of the many-many component |
||
2094 | * @param int|array $id Optional ID for parent of this relation, if not the current record |
||
2095 | * @return ManyManyList|UnsavedRelationList The set of components |
||
2096 | */ |
||
2097 | public function getManyManyComponents($componentName, $id = null) |
||
2098 | { |
||
2099 | if (!isset($id)) { |
||
2100 | $id = $this->ID; |
||
2101 | } |
||
2102 | $schema = static::getSchema(); |
||
2103 | $manyManyComponent = $schema->manyManyComponent(static::class, $componentName); |
||
2104 | if (!$manyManyComponent) { |
||
2105 | throw new InvalidArgumentException(sprintf( |
||
2106 | "DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'", |
||
2107 | $componentName, |
||
2108 | static::class |
||
2109 | )); |
||
2110 | } |
||
2111 | |||
2112 | // If we haven't been written yet, we can't save these relations, so use a list that handles this case |
||
2113 | if (!$id) { |
||
2114 | if (!isset($this->unsavedRelations[$componentName])) { |
||
2115 | $this->unsavedRelations[$componentName] = |
||
2116 | new UnsavedRelationList( |
||
2117 | $manyManyComponent['parentClass'], |
||
2118 | $componentName, |
||
2119 | $manyManyComponent['childClass'] |
||
2120 | ); |
||
2121 | } |
||
2122 | return $this->unsavedRelations[$componentName]; |
||
2123 | } |
||
2124 | |||
2125 | $extraFields = $schema->manyManyExtraFieldsForComponent(static::class, $componentName) ?: array(); |
||
2126 | /** @var RelationList $result */ |
||
2127 | $result = Injector::inst()->create( |
||
2128 | $manyManyComponent['relationClass'], |
||
2129 | $manyManyComponent['childClass'], |
||
2130 | $manyManyComponent['join'], |
||
2131 | $manyManyComponent['childField'], |
||
2132 | $manyManyComponent['parentField'], |
||
2133 | $extraFields, |
||
2134 | $manyManyComponent['parentClass'], |
||
2135 | static::class // In case ManyManyThroughList needs to use PolymorphicHasManyList internally |
||
2136 | ); |
||
2137 | |||
2138 | // Store component data in query meta-data |
||
2139 | $result = $result->alterDataQuery(function ($query) use ($extraFields) { |
||
2140 | /** @var DataQuery $query */ |
||
2141 | $query->setQueryParam('Component.ExtraFields', $extraFields); |
||
2142 | }); |
||
2143 | |||
2144 | // If we have a default sort set for our "join" then we should overwrite any default already set. |
||
2145 | $joinSort = Config::inst()->get($manyManyComponent['join'], 'default_sort'); |
||
2146 | if (!empty($joinSort)) { |
||
2147 | $result = $result->sort($joinSort); |
||
2148 | } |
||
2149 | |||
2150 | $this->extend('updateManyManyComponents', $result); |
||
2151 | |||
2152 | // If this is called on a singleton, then we return an 'orphaned relation' that can have the |
||
2153 | // foreignID set elsewhere. |
||
2154 | return $result |
||
2155 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
2156 | ->forForeignID($id); |
||
2157 | } |
||
2158 | |||
2159 | /** |
||
2160 | * Return the class of a one-to-one component. If $component is null, return all of the one-to-one components and |
||
2161 | * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type. |
||
2162 | * |
||
2163 | * @return string|array The class of the one-to-one component, or an array of all one-to-one components and |
||
2164 | * their classes. |
||
2165 | */ |
||
2166 | public function hasOne() |
||
2167 | { |
||
2168 | return (array)$this->config()->get('has_one'); |
||
2169 | } |
||
2170 | |||
2171 | /** |
||
2172 | * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and |
||
2173 | * their class name will be returned. |
||
2174 | * |
||
2175 | * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have |
||
2176 | * the field data stripped off. It defaults to TRUE. |
||
2177 | * @return string|array |
||
2178 | */ |
||
2179 | public function belongsTo($classOnly = true) |
||
2180 | { |
||
2181 | $belongsTo = (array)$this->config()->get('belongs_to'); |
||
2182 | if ($belongsTo && $classOnly) { |
||
2183 | return preg_replace('/(.+)?\..+/', '$1', $belongsTo); |
||
2184 | } else { |
||
2185 | return $belongsTo ? $belongsTo : array(); |
||
2186 | } |
||
2187 | } |
||
2188 | |||
2189 | /** |
||
2190 | * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many |
||
2191 | * relationships and their classes will be returned. |
||
2192 | * |
||
2193 | * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have |
||
2194 | * the field data stripped off. It defaults to TRUE. |
||
2195 | * @return string|array|false |
||
2196 | */ |
||
2197 | public function hasMany($classOnly = true) |
||
2198 | { |
||
2199 | $hasMany = (array)$this->config()->get('has_many'); |
||
2200 | if ($hasMany && $classOnly) { |
||
2201 | return preg_replace('/(.+)?\..+/', '$1', $hasMany); |
||
2202 | } else { |
||
2203 | return $hasMany ? $hasMany : array(); |
||
2204 | } |
||
2205 | } |
||
2206 | |||
2207 | /** |
||
2208 | * Return the many-to-many extra fields specification. |
||
2209 | * |
||
2210 | * If you don't specify a component name, it returns all |
||
2211 | * extra fields for all components available. |
||
2212 | * |
||
2213 | * @return array|null |
||
2214 | */ |
||
2215 | public function manyManyExtraFields() |
||
2216 | { |
||
2217 | return $this->config()->get('many_many_extraFields'); |
||
2218 | } |
||
2219 | |||
2220 | /** |
||
2221 | * Return information about a many-to-many component. |
||
2222 | * The return value is an array of (parentclass, childclass). If $component is null, then all many-many |
||
2223 | * components are returned. |
||
2224 | * |
||
2225 | * @see DataObjectSchema::manyManyComponent() |
||
2226 | * @return array|null An array of (parentclass, childclass), or an array of all many-many components |
||
2227 | */ |
||
2228 | public function manyMany() |
||
2229 | { |
||
2230 | $config = $this->config(); |
||
2231 | $manyManys = (array)$config->get('many_many'); |
||
2232 | $belongsManyManys = (array)$config->get('belongs_many_many'); |
||
2233 | $items = array_merge($manyManys, $belongsManyManys); |
||
2234 | return $items; |
||
2235 | } |
||
2236 | |||
2237 | /** |
||
2238 | * This returns an array (if it exists) describing the database extensions that are required, or false if none |
||
2239 | * |
||
2240 | * This is experimental, and is currently only a Postgres-specific enhancement. |
||
2241 | * |
||
2242 | * @param string $class |
||
2243 | * @return array|false |
||
2244 | */ |
||
2245 | public function database_extensions($class) |
||
2246 | { |
||
2247 | $extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED); |
||
2248 | if ($extensions) { |
||
2249 | return $extensions; |
||
2250 | } else { |
||
2251 | return false; |
||
2252 | } |
||
2253 | } |
||
2254 | |||
2255 | /** |
||
2256 | * Generates a SearchContext to be used for building and processing |
||
2257 | * a generic search form for properties on this object. |
||
2258 | * |
||
2259 | * @return SearchContext |
||
2260 | */ |
||
2261 | public function getDefaultSearchContext() |
||
2262 | { |
||
2263 | return new SearchContext( |
||
2264 | static::class, |
||
2265 | $this->scaffoldSearchFields(), |
||
2266 | $this->defaultSearchFilters() |
||
2267 | ); |
||
2268 | } |
||
2269 | |||
2270 | /** |
||
2271 | * Determine which properties on the DataObject are |
||
2272 | * searchable, and map them to their default {@link FormField} |
||
2273 | * representations. Used for scaffolding a searchform for {@link ModelAdmin}. |
||
2274 | * |
||
2275 | * Some additional logic is included for switching field labels, based on |
||
2276 | * how generic or specific the field type is. |
||
2277 | * |
||
2278 | * Used by {@link SearchContext}. |
||
2279 | * |
||
2280 | * @param array $_params |
||
2281 | * 'fieldClasses': Associative array of field names as keys and FormField classes as values |
||
2282 | * 'restrictFields': Numeric array of a field name whitelist |
||
2283 | * @return FieldList |
||
2284 | */ |
||
2285 | public function scaffoldSearchFields($_params = null) |
||
2286 | { |
||
2287 | $params = array_merge( |
||
2288 | array( |
||
2289 | 'fieldClasses' => false, |
||
2290 | 'restrictFields' => false |
||
2291 | ), |
||
2292 | (array)$_params |
||
2293 | ); |
||
2294 | $fields = new FieldList(); |
||
2295 | foreach ($this->searchableFields() as $fieldName => $spec) { |
||
2296 | if ($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) { |
||
2297 | continue; |
||
2298 | } |
||
2299 | |||
2300 | // If a custom fieldclass is provided as a string, use it |
||
2301 | $field = null; |
||
2302 | if ($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) { |
||
2303 | $fieldClass = $params['fieldClasses'][$fieldName]; |
||
2304 | $field = new $fieldClass($fieldName); |
||
2305 | // If we explicitly set a field, then construct that |
||
2306 | } elseif (isset($spec['field'])) { |
||
2307 | // If it's a string, use it as a class name and construct |
||
2308 | if (is_string($spec['field'])) { |
||
2309 | $fieldClass = $spec['field']; |
||
2310 | $field = new $fieldClass($fieldName); |
||
2311 | |||
2312 | // If it's a FormField object, then just use that object directly. |
||
2313 | } elseif ($spec['field'] instanceof FormField) { |
||
2314 | $field = $spec['field']; |
||
2315 | |||
2316 | // Otherwise we have a bug |
||
2317 | } else { |
||
2318 | user_error("Bad value for searchable_fields, 'field' value: " |
||
2319 | . var_export($spec['field'], true), E_USER_WARNING); |
||
2320 | } |
||
2321 | |||
2322 | // Otherwise, use the database field's scaffolder |
||
2323 | } elseif ($object = $this->relObject($fieldName)) { |
||
2324 | if (is_object($object) && $object->hasMethod('scaffoldSearchField')) { |
||
2325 | $field = $object->scaffoldSearchField(); |
||
2326 | } else { |
||
2327 | throw new Exception(sprintf( |
||
2328 | "SearchField '%s' on '%s' does not return a valid DBField instance.", |
||
2329 | $fieldName, |
||
2330 | get_class($this) |
||
2331 | )); |
||
2332 | } |
||
2333 | } |
||
2334 | |||
2335 | // Allow fields to opt out of search |
||
2336 | if (!$field) { |
||
2337 | continue; |
||
2338 | } |
||
2339 | |||
2340 | if (strstr($fieldName, '.')) { |
||
2341 | $field->setName(str_replace('.', '__', $fieldName)); |
||
2342 | } |
||
2343 | $field->setTitle($spec['title']); |
||
2344 | |||
2345 | $fields->push($field); |
||
2346 | } |
||
2347 | return $fields; |
||
2348 | } |
||
2349 | |||
2350 | /** |
||
2351 | * Scaffold a simple edit form for all properties on this dataobject, |
||
2352 | * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}. |
||
2353 | * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}. |
||
2354 | * |
||
2355 | * @uses FormScaffolder |
||
2356 | * |
||
2357 | * @param array $_params Associative array passing through properties to {@link FormScaffolder}. |
||
2358 | * @return FieldList |
||
2359 | */ |
||
2360 | public function scaffoldFormFields($_params = null) |
||
2361 | { |
||
2362 | $params = array_merge( |
||
2363 | array( |
||
2364 | 'tabbed' => false, |
||
2365 | 'includeRelations' => false, |
||
2366 | 'restrictFields' => false, |
||
2367 | 'fieldClasses' => false, |
||
2368 | 'ajaxSafe' => false |
||
2369 | ), |
||
2370 | (array)$_params |
||
2371 | ); |
||
2372 | |||
2373 | $fs = FormScaffolder::create($this); |
||
2374 | $fs->tabbed = $params['tabbed']; |
||
2375 | $fs->includeRelations = $params['includeRelations']; |
||
2376 | $fs->restrictFields = $params['restrictFields']; |
||
2377 | $fs->fieldClasses = $params['fieldClasses']; |
||
2378 | $fs->ajaxSafe = $params['ajaxSafe']; |
||
2379 | |||
2380 | $this->extend('updateFormScaffolder', $fs, $this); |
||
2381 | |||
2382 | return $fs->getFieldList(); |
||
2383 | } |
||
2384 | |||
2385 | /** |
||
2386 | * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields |
||
2387 | * being called on extensions |
||
2388 | * |
||
2389 | * @param callable $callback The callback to execute |
||
2390 | */ |
||
2391 | protected function beforeUpdateCMSFields($callback) |
||
2392 | { |
||
2393 | $this->beforeExtending('updateCMSFields', $callback); |
||
2394 | } |
||
2395 | |||
2396 | /** |
||
2397 | * Centerpiece of every data administration interface in Silverstripe, |
||
2398 | * which returns a {@link FieldList} suitable for a {@link Form} object. |
||
2399 | * If not overloaded, we're using {@link scaffoldFormFields()} to automatically |
||
2400 | * generate this set. To customize, overload this method in a subclass |
||
2401 | * or extended onto it by using {@link DataExtension->updateCMSFields()}. |
||
2402 | * |
||
2403 | * <code> |
||
2404 | * class MyCustomClass extends DataObject { |
||
2405 | * static $db = array('CustomProperty'=>'Boolean'); |
||
2406 | * |
||
2407 | * function getCMSFields() { |
||
2408 | * $fields = parent::getCMSFields(); |
||
2409 | * $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty')); |
||
2410 | * return $fields; |
||
2411 | * } |
||
2412 | * } |
||
2413 | * </code> |
||
2414 | * |
||
2415 | * @see Good example of complex FormField building: SiteTree::getCMSFields() |
||
2416 | * |
||
2417 | * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms. |
||
2418 | */ |
||
2419 | public function getCMSFields() |
||
2420 | { |
||
2421 | $tabbedFields = $this->scaffoldFormFields(array( |
||
2422 | // Don't allow has_many/many_many relationship editing before the record is first saved |
||
2423 | 'includeRelations' => ($this->ID > 0), |
||
2424 | 'tabbed' => true, |
||
2425 | 'ajaxSafe' => true |
||
2426 | )); |
||
2427 | |||
2428 | $this->extend('updateCMSFields', $tabbedFields); |
||
2429 | |||
2430 | return $tabbedFields; |
||
2431 | } |
||
2432 | |||
2433 | /** |
||
2434 | * need to be overload by solid dataobject, so that the customised actions of that dataobject, |
||
2435 | * including that dataobject's extensions customised actions could be added to the EditForm. |
||
2436 | * |
||
2437 | * @return FieldList an Empty FieldList(); need to be overload by solid subclass |
||
2438 | */ |
||
2439 | public function getCMSActions() |
||
2440 | { |
||
2441 | $actions = new FieldList(); |
||
2442 | $this->extend('updateCMSActions', $actions); |
||
2443 | return $actions; |
||
2444 | } |
||
2445 | |||
2446 | |||
2447 | /** |
||
2448 | * Used for simple frontend forms without relation editing |
||
2449 | * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()} |
||
2450 | * by default. To customize, either overload this method in your |
||
2451 | * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}. |
||
2452 | * |
||
2453 | * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API |
||
2454 | * |
||
2455 | * @param array $params See {@link scaffoldFormFields()} |
||
2456 | * @return FieldList Always returns a simple field collection without TabSet. |
||
2457 | */ |
||
2458 | public function getFrontEndFields($params = null) |
||
2459 | { |
||
2460 | $untabbedFields = $this->scaffoldFormFields($params); |
||
2461 | $this->extend('updateFrontEndFields', $untabbedFields); |
||
2462 | |||
2463 | return $untabbedFields; |
||
2464 | } |
||
2465 | |||
2466 | public function getViewerTemplates($suffix = '') |
||
2467 | { |
||
2468 | return SSViewer::get_templates_by_class(static::class, $suffix, $this->baseClass()); |
||
2469 | } |
||
2470 | |||
2471 | /** |
||
2472 | * Gets the value of a field. |
||
2473 | * Called by {@link __get()} and any getFieldName() methods you might create. |
||
2474 | * |
||
2475 | * @param string $field The name of the field |
||
2476 | * @return mixed The field value |
||
2477 | */ |
||
2478 | public function getField($field) |
||
2479 | { |
||
2480 | // If we already have a value in $this->record, then we should just return that |
||
2481 | if (isset($this->record[$field])) { |
||
2482 | return $this->record[$field]; |
||
2483 | } |
||
2484 | |||
2485 | // Do we have a field that needs to be lazy loaded? |
||
2486 | if (isset($this->record[$field . '_Lazy'])) { |
||
2487 | $tableClass = $this->record[$field . '_Lazy']; |
||
2488 | $this->loadLazyFields($tableClass); |
||
2489 | } |
||
2490 | $schema = static::getSchema(); |
||
2491 | |||
2492 | // Support unary relations as fields |
||
2493 | if ($schema->unaryComponent(static::class, $field)) { |
||
2494 | return $this->getComponent($field); |
||
2495 | } |
||
2496 | |||
2497 | // In case of complex fields, return the DBField object |
||
2498 | if ($schema->compositeField(static::class, $field)) { |
||
2499 | $this->record[$field] = $this->dbObject($field); |
||
2500 | } |
||
2501 | |||
2502 | return isset($this->record[$field]) ? $this->record[$field] : null; |
||
2503 | } |
||
2504 | |||
2505 | /** |
||
2506 | * Loads all the stub fields that an initial lazy load didn't load fully. |
||
2507 | * |
||
2508 | * @param string $class Class to load the values from. Others are joined as required. |
||
2509 | * Not specifying a tableClass will load all lazy fields from all tables. |
||
2510 | * @return bool Flag if lazy loading succeeded |
||
2511 | */ |
||
2512 | protected function loadLazyFields($class = null) |
||
2587 | } |
||
2588 | |||
2589 | /** |
||
2590 | * Return the fields that have changed since the last write. |
||
2591 | * |
||
2592 | * The change level affects what the functions defines as "changed": |
||
2593 | * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones. |
||
2594 | * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes, |
||
2595 | * for example a change from 0 to null would not be included. |
||
2596 | * |
||
2597 | * Example return: |
||
2598 | * <code> |
||
2599 | * array( |
||
2600 | * 'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE) |
||
2601 | * ) |
||
2602 | * </code> |
||
2603 | * |
||
2604 | * @param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true |
||
2605 | * to return all database fields, or an array for an explicit filter. false returns all fields. |
||
2606 | * @param int $changeLevel The strictness of what is defined as change. Defaults to strict |
||
2607 | * @return array |
||
2608 | */ |
||
2609 | public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT) |
||
2610 | { |
||
2611 | $changedFields = array(); |
||
2612 | |||
2613 | // Update the changed array with references to changed obj-fields |
||
2614 | foreach ($this->record as $k => $v) { |
||
2615 | // Prevents DBComposite infinite looping on isChanged |
||
2616 | if (is_array($databaseFieldsOnly) && !in_array($k, $databaseFieldsOnly)) { |
||
2617 | continue; |
||
2618 | } |
||
2619 | if (is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) { |
||
2620 | $this->changed[$k] = self::CHANGE_VALUE; |
||
2621 | } |
||
2622 | } |
||
2623 | |||
2624 | // If change was forced, then derive change data from $this->record |
||
2625 | if ($this->changeForced && $changeLevel <= self::CHANGE_STRICT) { |
||
2626 | $changed = array_combine( |
||
2627 | array_keys($this->record), |
||
2628 | array_fill(0, count($this->record), self::CHANGE_STRICT) |
||
2629 | ); |
||
2630 | // @todo Find better way to allow versioned to write a new version after forceChange |
||
2631 | unset($changed['Version']); |
||
2632 | } else { |
||
2633 | $changed = $this->changed; |
||
2634 | } |
||
2635 | |||
2636 | if (is_array($databaseFieldsOnly)) { |
||
2637 | $fields = array_intersect_key($changed, array_flip($databaseFieldsOnly)); |
||
2638 | } elseif ($databaseFieldsOnly) { |
||
2639 | $fieldsSpecs = static::getSchema()->fieldSpecs(static::class); |
||
2640 | $fields = array_intersect_key($changed, $fieldsSpecs); |
||
2641 | } else { |
||
2642 | $fields = $changed; |
||
2643 | } |
||
2644 | |||
2645 | // Filter the list to those of a certain change level |
||
2646 | if ($changeLevel > self::CHANGE_STRICT) { |
||
2647 | if ($fields) { |
||
2648 | foreach ($fields as $name => $level) { |
||
2649 | if ($level < $changeLevel) { |
||
2650 | unset($fields[$name]); |
||
2651 | } |
||
2652 | } |
||
2653 | } |
||
2654 | } |
||
2655 | |||
2656 | if ($fields) { |
||
2657 | foreach ($fields as $name => $level) { |
||
2658 | $changedFields[$name] = array( |
||
2659 | 'before' => array_key_exists($name, $this->original) ? $this->original[$name] : null, |
||
2660 | 'after' => array_key_exists($name, $this->record) ? $this->record[$name] : null, |
||
2661 | 'level' => $level |
||
2662 | ); |
||
2663 | } |
||
2664 | } |
||
2665 | |||
2666 | return $changedFields; |
||
2667 | } |
||
2668 | |||
2669 | /** |
||
2670 | * Uses {@link getChangedFields()} to determine if fields have been changed |
||
2671 | * since loading them from the database. |
||
2672 | * |
||
2673 | * @param string $fieldName Name of the database field to check, will check for any if not given |
||
2674 | * @param int $changeLevel See {@link getChangedFields()} |
||
2675 | * @return boolean |
||
2676 | */ |
||
2677 | public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT) |
||
2678 | { |
||
2679 | $fields = $fieldName ? array($fieldName) : true; |
||
2680 | $changed = $this->getChangedFields($fields, $changeLevel); |
||
2681 | if (!isset($fieldName)) { |
||
2682 | return !empty($changed); |
||
2683 | } else { |
||
2684 | return array_key_exists($fieldName, $changed); |
||
2685 | } |
||
2686 | } |
||
2687 | |||
2688 | /** |
||
2689 | * Set the value of the field |
||
2690 | * Called by {@link __set()} and any setFieldName() methods you might create. |
||
2691 | * |
||
2692 | * @param string $fieldName Name of the field |
||
2693 | * @param mixed $val New field value |
||
2694 | * @return $this |
||
2695 | */ |
||
2696 | public function setField($fieldName, $val) |
||
2697 | { |
||
2698 | $this->objCacheClear(); |
||
2699 | //if it's a has_one component, destroy the cache |
||
2700 | if (substr($fieldName, -2) == 'ID') { |
||
2701 | unset($this->components[substr($fieldName, 0, -2)]); |
||
2702 | } |
||
2703 | |||
2704 | // If we've just lazy-loaded the column, then we need to populate the $original array |
||
2705 | if (isset($this->record[$fieldName . '_Lazy'])) { |
||
2706 | $tableClass = $this->record[$fieldName . '_Lazy']; |
||
2707 | $this->loadLazyFields($tableClass); |
||
2708 | } |
||
2709 | |||
2710 | // Support component assignent via field setter |
||
2711 | $schema = static::getSchema(); |
||
2712 | if ($schema->unaryComponent(static::class, $fieldName)) { |
||
2713 | unset($this->components[$fieldName]); |
||
2714 | // Assign component directly |
||
2715 | if (is_null($val) || $val instanceof DataObject) { |
||
2716 | return $this->setComponent($fieldName, $val); |
||
2717 | } |
||
2718 | // Assign by ID instead of object |
||
2719 | if (is_numeric($val)) { |
||
2720 | $fieldName .= 'ID'; |
||
2721 | } |
||
2722 | } |
||
2723 | |||
2724 | // Situation 1: Passing an DBField |
||
2725 | if ($val instanceof DBField) { |
||
2726 | $val->setName($fieldName); |
||
2727 | $val->saveInto($this); |
||
2728 | |||
2729 | // Situation 1a: Composite fields should remain bound in case they are |
||
2730 | // later referenced to update the parent dataobject |
||
2731 | if ($val instanceof DBComposite) { |
||
2732 | $val->bindTo($this); |
||
2733 | $this->record[$fieldName] = $val; |
||
2734 | } |
||
2735 | // Situation 2: Passing a literal or non-DBField object |
||
2736 | } else { |
||
2737 | // If this is a proper database field, we shouldn't be getting non-DBField objects |
||
2738 | if (is_object($val) && $schema->fieldSpec(static::class, $fieldName)) { |
||
2739 | throw new InvalidArgumentException('DataObject::setField: passed an object that is not a DBField'); |
||
2740 | } |
||
2741 | |||
2742 | if (!empty($val) && !is_scalar($val)) { |
||
2743 | $dbField = $this->dbObject($fieldName); |
||
2744 | if ($dbField && $dbField->scalarValueOnly()) { |
||
2745 | throw new InvalidArgumentException( |
||
2746 | sprintf( |
||
2747 | 'DataObject::setField: %s only accepts scalars', |
||
2748 | $fieldName |
||
2749 | ) |
||
2750 | ); |
||
2751 | } |
||
2752 | } |
||
2753 | |||
2754 | // if a field is not existing or has strictly changed |
||
2755 | if (!array_key_exists($fieldName, $this->original) || $this->original[$fieldName] !== $val) { |
||
2756 | // TODO Add check for php-level defaults which are not set in the db |
||
2757 | // TODO Add check for hidden input-fields (readonly) which are not set in the db |
||
2758 | // At the very least, the type has changed |
||
2759 | $this->changed[$fieldName] = self::CHANGE_STRICT; |
||
2760 | |||
2761 | if ((!array_key_exists($fieldName, $this->original) && $val) |
||
2762 | || (array_key_exists($fieldName, $this->original) && $this->original[$fieldName] != $val) |
||
2763 | ) { |
||
2764 | // Value has changed as well, not just the type |
||
2765 | $this->changed[$fieldName] = self::CHANGE_VALUE; |
||
2766 | } |
||
2767 | // Value has been restored to its original, remove any record of the change |
||
2768 | } elseif (isset($this->changed[$fieldName])) { |
||
2769 | unset($this->changed[$fieldName]); |
||
2770 | } |
||
2771 | |||
2772 | // Value is saved regardless, since the change detection relates to the last write |
||
2773 | $this->record[$fieldName] = $val; |
||
2774 | } |
||
2775 | return $this; |
||
2776 | } |
||
2777 | |||
2778 | /** |
||
2779 | * Set the value of the field, using a casting object. |
||
2780 | * This is useful when you aren't sure that a date is in SQL format, for example. |
||
2781 | * setCastedField() can also be used, by forms, to set related data. For example, uploaded images |
||
2782 | * can be saved into the Image table. |
||
2783 | * |
||
2784 | * @param string $fieldName Name of the field |
||
2785 | * @param mixed $value New field value |
||
2786 | * @return $this |
||
2787 | */ |
||
2788 | public function setCastedField($fieldName, $value) |
||
2789 | { |
||
2790 | if (!$fieldName) { |
||
2791 | user_error("DataObject::setCastedField: Called without a fieldName", E_USER_ERROR); |
||
2792 | } |
||
2793 | $fieldObj = $this->dbObject($fieldName); |
||
2794 | if ($fieldObj) { |
||
2795 | $fieldObj->setValue($value); |
||
2796 | $fieldObj->saveInto($this); |
||
2797 | } else { |
||
2798 | $this->$fieldName = $value; |
||
2799 | } |
||
2800 | return $this; |
||
2801 | } |
||
2802 | |||
2803 | /** |
||
2804 | * {@inheritdoc} |
||
2805 | */ |
||
2806 | public function castingHelper($field) |
||
2807 | { |
||
2808 | $fieldSpec = static::getSchema()->fieldSpec(static::class, $field); |
||
2809 | if ($fieldSpec) { |
||
2810 | return $fieldSpec; |
||
2811 | } |
||
2812 | |||
2813 | // many_many_extraFields aren't presented by db(), so we check if the source query params |
||
2814 | // provide us with meta-data for a many_many relation we can inspect for extra fields. |
||
2815 | $queryParams = $this->getSourceQueryParams(); |
||
2816 | if (!empty($queryParams['Component.ExtraFields'])) { |
||
2817 | $extraFields = $queryParams['Component.ExtraFields']; |
||
2818 | |||
2819 | if (isset($extraFields[$field])) { |
||
2820 | return $extraFields[$field]; |
||
2821 | } |
||
2822 | } |
||
2823 | |||
2824 | return parent::castingHelper($field); |
||
2825 | } |
||
2826 | |||
2827 | /** |
||
2828 | * Returns true if the given field exists in a database column on any of |
||
2829 | * the objects tables and optionally look up a dynamic getter with |
||
2830 | * get<fieldName>(). |
||
2831 | * |
||
2832 | * @param string $field Name of the field |
||
2833 | * @return boolean True if the given field exists |
||
2834 | */ |
||
2835 | public function hasField($field) |
||
2836 | { |
||
2837 | $schema = static::getSchema(); |
||
2838 | return ( |
||
2839 | array_key_exists($field, $this->record) |
||
2840 | || array_key_exists($field, $this->components) |
||
2841 | || $schema->fieldSpec(static::class, $field) |
||
2842 | || $schema->unaryComponent(static::class, $field) |
||
2843 | || $this->hasMethod("get{$field}") |
||
2844 | ); |
||
2845 | } |
||
2846 | |||
2847 | /** |
||
2848 | * Returns true if the given field exists as a database column |
||
2849 | * |
||
2850 | * @param string $field Name of the field |
||
2851 | * |
||
2852 | * @return boolean |
||
2853 | */ |
||
2854 | public function hasDatabaseField($field) |
||
2855 | { |
||
2856 | $spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY); |
||
2857 | return !empty($spec); |
||
2858 | } |
||
2859 | |||
2860 | /** |
||
2861 | * Returns true if the member is allowed to do the given action. |
||
2862 | * See {@link extendedCan()} for a more versatile tri-state permission control. |
||
2863 | * |
||
2864 | * @param string $perm The permission to be checked, such as 'View'. |
||
2865 | * @param Member $member The member whose permissions need checking. Defaults to the currently logged |
||
2866 | * in user. |
||
2867 | * @param array $context Additional $context to pass to extendedCan() |
||
2868 | * |
||
2869 | * @return boolean True if the the member is allowed to do the given action |
||
2870 | */ |
||
2871 | public function can($perm, $member = null, $context = array()) |
||
2872 | { |
||
2873 | if (!$member) { |
||
2874 | $member = Security::getCurrentUser(); |
||
2875 | } |
||
2876 | |||
2877 | if ($member && Permission::checkMember($member, "ADMIN")) { |
||
2878 | return true; |
||
2879 | } |
||
2880 | |||
2881 | if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) { |
||
2882 | $method = 'can' . ucfirst($perm); |
||
2883 | return $this->$method($member); |
||
2884 | } |
||
2885 | |||
2886 | $results = $this->extendedCan('can', $member); |
||
2887 | if (isset($results)) { |
||
2888 | return $results; |
||
2889 | } |
||
2890 | |||
2891 | return ($member && Permission::checkMember($member, $perm)); |
||
2892 | } |
||
2893 | |||
2894 | /** |
||
2895 | * Process tri-state responses from permission-alterting extensions. The extensions are |
||
2896 | * expected to return one of three values: |
||
2897 | * |
||
2898 | * - false: Disallow this permission, regardless of what other extensions say |
||
2899 | * - true: Allow this permission, as long as no other extensions return false |
||
2900 | * - NULL: Don't affect the outcome |
||
2901 | * |
||
2902 | * This method itself returns a tri-state value, and is designed to be used like this: |
||
2903 | * |
||
2904 | * <code> |
||
2905 | * $extended = $this->extendedCan('canDoSomething', $member); |
||
2906 | * if($extended !== null) return $extended; |
||
2907 | * else return $normalValue; |
||
2908 | * </code> |
||
2909 | * |
||
2910 | * @param string $methodName Method on the same object, e.g. {@link canEdit()} |
||
2911 | * @param Member|int $member |
||
2912 | * @param array $context Optional context |
||
2913 | * @return boolean|null |
||
2914 | */ |
||
2915 | public function extendedCan($methodName, $member, $context = array()) |
||
2916 | { |
||
2917 | $results = $this->extend($methodName, $member, $context); |
||
2918 | if ($results && is_array($results)) { |
||
2919 | // Remove NULLs |
||
2920 | $results = array_filter($results, function ($v) { |
||
2921 | return !is_null($v); |
||
2922 | }); |
||
2923 | // If there are any non-NULL responses, then return the lowest one of them. |
||
2924 | // If any explicitly deny the permission, then we don't get access |
||
2925 | if ($results) { |
||
2926 | return min($results); |
||
2927 | } |
||
2928 | } |
||
2929 | return null; |
||
2930 | } |
||
2931 | |||
2932 | /** |
||
2933 | * @param Member $member |
||
2934 | * @return boolean |
||
2935 | */ |
||
2936 | public function canView($member = null) |
||
2937 | { |
||
2938 | $extended = $this->extendedCan(__FUNCTION__, $member); |
||
2939 | if ($extended !== null) { |
||
2940 | return $extended; |
||
2941 | } |
||
2942 | return Permission::check('ADMIN', 'any', $member); |
||
2943 | } |
||
2944 | |||
2945 | /** |
||
2946 | * @param Member $member |
||
2947 | * @return boolean |
||
2948 | */ |
||
2949 | public function canEdit($member = null) |
||
2950 | { |
||
2951 | $extended = $this->extendedCan(__FUNCTION__, $member); |
||
2952 | if ($extended !== null) { |
||
2953 | return $extended; |
||
2954 | } |
||
2955 | return Permission::check('ADMIN', 'any', $member); |
||
2956 | } |
||
2957 | |||
2958 | /** |
||
2959 | * @param Member $member |
||
2960 | * @return boolean |
||
2961 | */ |
||
2962 | public function canDelete($member = null) |
||
2963 | { |
||
2964 | $extended = $this->extendedCan(__FUNCTION__, $member); |
||
2965 | if ($extended !== null) { |
||
2966 | return $extended; |
||
2967 | } |
||
2968 | return Permission::check('ADMIN', 'any', $member); |
||
2969 | } |
||
2970 | |||
2971 | /** |
||
2972 | * @param Member $member |
||
2973 | * @param array $context Additional context-specific data which might |
||
2974 | * affect whether (or where) this object could be created. |
||
2975 | * @return boolean |
||
2976 | */ |
||
2977 | public function canCreate($member = null, $context = array()) |
||
2978 | { |
||
2979 | $extended = $this->extendedCan(__FUNCTION__, $member, $context); |
||
2980 | if ($extended !== null) { |
||
2981 | return $extended; |
||
2982 | } |
||
2983 | return Permission::check('ADMIN', 'any', $member); |
||
2984 | } |
||
2985 | |||
2986 | /** |
||
2987 | * Debugging used by Debug::show() |
||
2988 | * |
||
2989 | * @return string HTML data representing this object |
||
2990 | */ |
||
2991 | public function debug() |
||
2992 | { |
||
2993 | $class = static::class; |
||
2994 | $val = "<h3>Database record: {$class}</h3>\n<ul>\n"; |
||
2995 | if ($this->record) { |
||
2996 | foreach ($this->record as $fieldName => $fieldVal) { |
||
2997 | $val .= "\t<li>$fieldName: " . Debug::text($fieldVal) . "</li>\n"; |
||
2998 | } |
||
2999 | } |
||
3000 | $val .= "</ul>\n"; |
||
3001 | return $val; |
||
3002 | } |
||
3003 | |||
3004 | /** |
||
3005 | * Return the DBField object that represents the given field. |
||
3006 | * This works similarly to obj() with 2 key differences: |
||
3007 | * - it still returns an object even when the field has no value. |
||
3008 | * - it only matches fields and not methods |
||
3009 | * - it matches foreign keys generated by has_one relationships, eg, "ParentID" |
||
3010 | * |
||
3011 | * @param string $fieldName Name of the field |
||
3012 | * @return DBField The field as a DBField object |
||
3013 | */ |
||
3014 | public function dbObject($fieldName) |
||
3015 | { |
||
3016 | // Check for field in DB |
||
3017 | $schema = static::getSchema(); |
||
3018 | $helper = $schema->fieldSpec(static::class, $fieldName, DataObjectSchema::INCLUDE_CLASS); |
||
3019 | if (!$helper) { |
||
3020 | return null; |
||
3021 | } |
||
3022 | |||
3023 | if (!isset($this->record[$fieldName]) && isset($this->record[$fieldName . '_Lazy'])) { |
||
3024 | $tableClass = $this->record[$fieldName . '_Lazy']; |
||
3025 | $this->loadLazyFields($tableClass); |
||
3026 | } |
||
3027 | |||
3028 | $value = isset($this->record[$fieldName]) |
||
3029 | ? $this->record[$fieldName] |
||
3030 | : null; |
||
3031 | |||
3032 | // If we have a DBField object in $this->record, then return that |
||
3033 | if ($value instanceof DBField) { |
||
3034 | return $value; |
||
3035 | } |
||
3036 | |||
3037 | list($class, $spec) = explode('.', $helper); |
||
3038 | /** @var DBField $obj */ |
||
3039 | $table = $schema->tableName($class); |
||
3040 | $obj = Injector::inst()->create($spec, $fieldName); |
||
3041 | $obj->setTable($table); |
||
3042 | $obj->setValue($value, $this, false); |
||
3043 | return $obj; |
||
3044 | } |
||
3045 | |||
3046 | /** |
||
3047 | * Traverses to a DBField referenced by relationships between data objects. |
||
3048 | * |
||
3049 | * The path to the related field is specified with dot separated syntax |
||
3050 | * (eg: Parent.Child.Child.FieldName). |
||
3051 | * |
||
3052 | * If a relation is blank, this will return null instead. |
||
3053 | * If a relation name is invalid (e.g. non-relation on a parent) this |
||
3054 | * can throw a LogicException. |
||
3055 | * |
||
3056 | * @param string $fieldPath List of paths on this object. All items in this path |
||
3057 | * must be ViewableData implementors |
||
3058 | * |
||
3059 | * @return mixed DBField of the field on the object or a DataList instance. |
||
3060 | * @throws LogicException If accessing invalid relations |
||
3061 | */ |
||
3062 | public function relObject($fieldPath) |
||
3063 | { |
||
3064 | $object = null; |
||
3065 | $component = $this; |
||
3066 | |||
3067 | // Parse all relations |
||
3068 | foreach (explode('.', $fieldPath) as $relation) { |
||
3069 | if (!$component) { |
||
3070 | return null; |
||
3071 | } |
||
3072 | |||
3073 | // Inspect relation type |
||
3074 | if (ClassInfo::hasMethod($component, $relation)) { |
||
3075 | $component = $component->$relation(); |
||
3076 | } elseif ($component instanceof Relation || $component instanceof DataList) { |
||
3077 | // $relation could either be a field (aggregate), or another relation |
||
3078 | $singleton = DataObject::singleton($component->dataClass()); |
||
3079 | $component = $singleton->dbObject($relation) ?: $component->relation($relation); |
||
3080 | } elseif ($component instanceof DataObject && ($dbObject = $component->dbObject($relation))) { |
||
3081 | $component = $dbObject; |
||
3082 | } elseif ($component instanceof ViewableData && $component->hasField($relation)) { |
||
3083 | $component = $component->obj($relation); |
||
3084 | } else { |
||
3085 | throw new LogicException( |
||
3086 | "$relation is not a relation/field on " . get_class($component) |
||
3087 | ); |
||
3088 | } |
||
3089 | } |
||
3090 | return $component; |
||
3091 | } |
||
3092 | |||
3093 | /** |
||
3094 | * Traverses to a field referenced by relationships between data objects, returning the value |
||
3095 | * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName) |
||
3096 | * |
||
3097 | * @param string $fieldName string |
||
3098 | * @return mixed Will return null on a missing value |
||
3099 | */ |
||
3100 | public function relField($fieldName) |
||
3101 | { |
||
3102 | // Navigate to relative parent using relObject() if needed |
||
3103 | $component = $this; |
||
3104 | if (($pos = strrpos($fieldName, '.')) !== false) { |
||
3105 | $relation = substr($fieldName, 0, $pos); |
||
3106 | $fieldName = substr($fieldName, $pos + 1); |
||
3107 | $component = $this->relObject($relation); |
||
3108 | } |
||
3109 | |||
3110 | // Bail if the component is null |
||
3111 | if (!$component) { |
||
3112 | return null; |
||
3113 | } |
||
3114 | if (ClassInfo::hasMethod($component, $fieldName)) { |
||
3115 | return $component->$fieldName(); |
||
3116 | } |
||
3117 | return $component->$fieldName; |
||
3118 | } |
||
3119 | |||
3120 | /** |
||
3121 | * Temporary hack to return an association name, based on class, to get around the mangle |
||
3122 | * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys. |
||
3123 | * |
||
3124 | * @param string $className |
||
3125 | * @return string |
||
3126 | */ |
||
3127 | public function getReverseAssociation($className) |
||
3128 | { |
||
3129 | if (is_array($this->manyMany())) { |
||
3130 | $many_many = array_flip($this->manyMany()); |
||
3131 | if (array_key_exists($className, $many_many)) { |
||
3132 | return $many_many[$className]; |
||
3133 | } |
||
3134 | } |
||
3135 | if (is_array($this->hasMany())) { |
||
3136 | $has_many = array_flip($this->hasMany()); |
||
3137 | if (array_key_exists($className, $has_many)) { |
||
3138 | return $has_many[$className]; |
||
3139 | } |
||
3140 | } |
||
3141 | if (is_array($this->hasOne())) { |
||
3142 | $has_one = array_flip($this->hasOne()); |
||
3143 | if (array_key_exists($className, $has_one)) { |
||
3144 | return $has_one[$className]; |
||
3145 | } |
||
3146 | } |
||
3147 | |||
3148 | return false; |
||
3149 | } |
||
3150 | |||
3151 | /** |
||
3152 | * Return all objects matching the filter |
||
3153 | * sub-classes are automatically selected and included |
||
3154 | * |
||
3155 | * @param string $callerClass The class of objects to be returned |
||
3156 | * @param string|array $filter A filter to be inserted into the WHERE clause. |
||
3157 | * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples. |
||
3158 | * @param string|array $sort A sort expression to be inserted into the ORDER |
||
3159 | * BY clause. If omitted, self::$default_sort will be used. |
||
3160 | * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead. |
||
3161 | * @param string|array $limit A limit expression to be inserted into the LIMIT clause. |
||
3162 | * @param string $containerClass The container class to return the results in. |
||
3163 | * |
||
3164 | * @todo $containerClass is Ignored, why? |
||
3165 | * |
||
3166 | * @return DataList The objects matching the filter, in the class specified by $containerClass |
||
3167 | */ |
||
3168 | public static function get( |
||
3169 | $callerClass = null, |
||
3170 | $filter = "", |
||
3171 | $sort = "", |
||
3172 | $join = "", |
||
3173 | $limit = null, |
||
3174 | $containerClass = DataList::class |
||
3175 | ) { |
||
3176 | // Validate arguments |
||
3177 | if ($callerClass == null) { |
||
3178 | $callerClass = get_called_class(); |
||
3179 | if ($callerClass === self::class) { |
||
3180 | throw new InvalidArgumentException('Call <classname>::get() instead of DataObject::get()'); |
||
3181 | } |
||
3182 | if ($filter || $sort || $join || $limit || ($containerClass !== DataList::class)) { |
||
3183 | throw new InvalidArgumentException('If calling <classname>::get() then you shouldn\'t pass any other' |
||
3184 | . ' arguments'); |
||
3185 | } |
||
3186 | } elseif ($callerClass === self::class) { |
||
3187 | throw new InvalidArgumentException('DataObject::get() cannot query non-subclass DataObject directly'); |
||
3188 | } |
||
3189 | if ($join) { |
||
3190 | throw new InvalidArgumentException( |
||
3191 | 'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.' |
||
3192 | ); |
||
3193 | } |
||
3194 | |||
3195 | // Build and decorate with args |
||
3196 | $result = DataList::create($callerClass); |
||
3197 | if ($filter) { |
||
3198 | $result = $result->where($filter); |
||
3199 | } |
||
3200 | if ($sort) { |
||
3201 | $result = $result->sort($sort); |
||
3202 | } |
||
3203 | if ($limit && strpos($limit, ',') !== false) { |
||
3204 | $limitArguments = explode(',', $limit); |
||
3205 | $result = $result->limit($limitArguments[1], $limitArguments[0]); |
||
3206 | } elseif ($limit) { |
||
3207 | $result = $result->limit($limit); |
||
3208 | } |
||
3209 | |||
3210 | return $result; |
||
3211 | } |
||
3212 | |||
3213 | |||
3214 | /** |
||
3215 | * Return the first item matching the given query. |
||
3216 | * All calls to get_one() are cached. |
||
3217 | * |
||
3218 | * The filter argument supports parameterised queries (see SQLSelect::addWhere() for syntax examples). Because |
||
3219 | * of that (and differently from e.g. DataList::filter()) you need to manually escape the field names: |
||
3220 | * <code> |
||
3221 | * $member = DataObject::get_one('Member', [ '"FirstName"' => 'John' ]); |
||
3222 | * </code> |
||
3223 | * |
||
3224 | * @param string $callerClass The class of objects to be returned |
||
3225 | * @param string|array $filter A filter to be inserted into the WHERE clause. |
||
3226 | * @param boolean $cache Use caching |
||
3227 | * @param string $orderby A sort expression to be inserted into the ORDER BY clause. |
||
3228 | * |
||
3229 | * @return DataObject|null The first item matching the query |
||
3230 | */ |
||
3231 | public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "") |
||
3232 | { |
||
3233 | $SNG = singleton($callerClass); |
||
3234 | |||
3235 | $cacheComponents = array($filter, $orderby, $SNG->extend('cacheKeyComponent')); |
||
3236 | $cacheKey = md5(serialize($cacheComponents)); |
||
3237 | |||
3238 | $item = null; |
||
3239 | if (!$cache || !isset(self::$_cache_get_one[$callerClass][$cacheKey])) { |
||
3240 | $dl = DataObject::get($callerClass)->where($filter)->sort($orderby); |
||
3241 | $item = $dl->first(); |
||
3242 | |||
3243 | if ($cache) { |
||
3244 | self::$_cache_get_one[$callerClass][$cacheKey] = $item; |
||
3245 | if (!self::$_cache_get_one[$callerClass][$cacheKey]) { |
||
3246 | self::$_cache_get_one[$callerClass][$cacheKey] = false; |
||
3247 | } |
||
3248 | } |
||
3249 | } |
||
3250 | |||
3251 | if ($cache) { |
||
3252 | return self::$_cache_get_one[$callerClass][$cacheKey] ?: null; |
||
3253 | } |
||
3254 | |||
3255 | return $item; |
||
3256 | } |
||
3257 | |||
3258 | /** |
||
3259 | * Flush the cached results for all relations (has_one, has_many, many_many) |
||
3260 | * Also clears any cached aggregate data. |
||
3261 | * |
||
3262 | * @param boolean $persistent When true will also clear persistent data stored in the Cache system. |
||
3263 | * When false will just clear session-local cached data |
||
3264 | * @return DataObject $this |
||
3265 | */ |
||
3266 | public function flushCache($persistent = true) |
||
3267 | { |
||
3268 | if (static::class == self::class) { |
||
3269 | self::$_cache_get_one = array(); |
||
3270 | return $this; |
||
3271 | } |
||
3272 | |||
3273 | $classes = ClassInfo::ancestry(static::class); |
||
3274 | foreach ($classes as $class) { |
||
3275 | if (isset(self::$_cache_get_one[$class])) { |
||
3276 | unset(self::$_cache_get_one[$class]); |
||
3277 | } |
||
3278 | } |
||
3279 | |||
3280 | $this->extend('flushCache'); |
||
3281 | |||
3282 | $this->components = array(); |
||
3283 | return $this; |
||
3284 | } |
||
3285 | |||
3286 | /** |
||
3287 | * Flush the get_one global cache and destroy associated objects. |
||
3288 | */ |
||
3289 | public static function flush_and_destroy_cache() |
||
3290 | { |
||
3291 | if (self::$_cache_get_one) { |
||
3292 | foreach (self::$_cache_get_one as $class => $items) { |
||
3293 | if (is_array($items)) { |
||
3294 | foreach ($items as $item) { |
||
3295 | if ($item) { |
||
3296 | $item->destroy(); |
||
3297 | } |
||
3298 | } |
||
3299 | } |
||
3300 | } |
||
3301 | } |
||
3302 | self::$_cache_get_one = array(); |
||
3303 | } |
||
3304 | |||
3305 | /** |
||
3306 | * Reset all global caches associated with DataObject. |
||
3307 | */ |
||
3308 | public static function reset() |
||
3309 | { |
||
3310 | // @todo Decouple these |
||
3311 | DBEnum::flushCache(); |
||
3312 | ClassInfo::reset_db_cache(); |
||
3313 | static::getSchema()->reset(); |
||
3314 | self::$_cache_get_one = array(); |
||
3315 | self::$_cache_field_labels = array(); |
||
3316 | } |
||
3317 | |||
3318 | /** |
||
3319 | * Return the given element, searching by ID. |
||
3320 | * |
||
3321 | * This can be called either via `DataObject::get_by_id(MyClass::class, $id)` |
||
3322 | * or `MyClass::get_by_id($id)` |
||
3323 | * |
||
3324 | * @param string|int $classOrID The class of the object to be returned, or id if called on target class |
||
3325 | * @param int|bool $idOrCache The id of the element, or cache if called on target class |
||
3326 | * @param boolean $cache See {@link get_one()} |
||
3327 | * |
||
3328 | * @return static The element |
||
3329 | */ |
||
3330 | public static function get_by_id($classOrID, $idOrCache = null, $cache = true) |
||
3331 | { |
||
3332 | // Shift arguments if passing id in first or second argument |
||
3333 | list ($class, $id, $cached) = is_numeric($classOrID) |
||
3334 | ? [get_called_class(), $classOrID, isset($idOrCache) ? $idOrCache : $cache] |
||
3335 | : [$classOrID, $idOrCache, $cache]; |
||
3336 | |||
3337 | // Validate class |
||
3338 | if ($class === self::class) { |
||
3339 | throw new InvalidArgumentException('DataObject::get_by_id() cannot query non-subclass DataObject directly'); |
||
3340 | } |
||
3341 | |||
3342 | // Pass to get_one |
||
3343 | $column = static::getSchema()->sqlColumnForField($class, 'ID'); |
||
3344 | return DataObject::get_one($class, [$column => $id], $cached); |
||
3345 | } |
||
3346 | |||
3347 | /** |
||
3348 | * Get the name of the base table for this object |
||
3349 | * |
||
3350 | * @return string |
||
3351 | */ |
||
3352 | public function baseTable() |
||
3353 | { |
||
3354 | return static::getSchema()->baseDataTable($this); |
||
3355 | } |
||
3356 | |||
3357 | /** |
||
3358 | * Get the base class for this object |
||
3359 | * |
||
3360 | * @return string |
||
3361 | */ |
||
3362 | public function baseClass() |
||
3363 | { |
||
3364 | return static::getSchema()->baseDataClass($this); |
||
3365 | } |
||
3366 | |||
3367 | /** |
||
3368 | * @var array Parameters used in the query that built this object. |
||
3369 | * This can be used by decorators (e.g. lazy loading) to |
||
3370 | * run additional queries using the same context. |
||
3371 | */ |
||
3372 | protected $sourceQueryParams; |
||
3373 | |||
3374 | /** |
||
3375 | * @see $sourceQueryParams |
||
3376 | * @return array |
||
3377 | */ |
||
3378 | public function getSourceQueryParams() |
||
3379 | { |
||
3380 | return $this->sourceQueryParams; |
||
3381 | } |
||
3382 | |||
3383 | /** |
||
3384 | * Get list of parameters that should be inherited to relations on this object |
||
3385 | * |
||
3386 | * @return array |
||
3387 | */ |
||
3388 | public function getInheritableQueryParams() |
||
3389 | { |
||
3390 | $params = $this->getSourceQueryParams(); |
||
3391 | $this->extend('updateInheritableQueryParams', $params); |
||
3392 | return $params; |
||
3393 | } |
||
3394 | |||
3395 | /** |
||
3396 | * @see $sourceQueryParams |
||
3397 | * @param array |
||
3398 | */ |
||
3399 | public function setSourceQueryParams($array) |
||
3400 | { |
||
3401 | $this->sourceQueryParams = $array; |
||
3402 | } |
||
3403 | |||
3404 | /** |
||
3405 | * @see $sourceQueryParams |
||
3406 | * @param string $key |
||
3407 | * @param string $value |
||
3408 | */ |
||
3409 | public function setSourceQueryParam($key, $value) |
||
3410 | { |
||
3411 | $this->sourceQueryParams[$key] = $value; |
||
3412 | } |
||
3413 | |||
3414 | /** |
||
3415 | * @see $sourceQueryParams |
||
3416 | * @param string $key |
||
3417 | * @return string |
||
3418 | */ |
||
3419 | public function getSourceQueryParam($key) |
||
3420 | { |
||
3421 | if (isset($this->sourceQueryParams[$key])) { |
||
3422 | return $this->sourceQueryParams[$key]; |
||
3423 | } |
||
3424 | return null; |
||
3425 | } |
||
3426 | |||
3427 | //-------------------------------------------------------------------------------------------// |
||
3428 | |||
3429 | /** |
||
3430 | * Check the database schema and update it as necessary. |
||
3431 | * |
||
3432 | * @uses DataExtension->augmentDatabase() |
||
3433 | */ |
||
3434 | public function requireTable() |
||
3435 | { |
||
3436 | // Only build the table if we've actually got fields |
||
3437 | $schema = static::getSchema(); |
||
3438 | $table = $schema->tableName(static::class); |
||
3439 | $fields = $schema->databaseFields(static::class, false); |
||
3440 | $indexes = $schema->databaseIndexes(static::class, false); |
||
3441 | $extensions = self::database_extensions(static::class); |
||
3442 | |||
3443 | if (empty($table)) { |
||
3444 | throw new LogicException( |
||
3445 | "Class " . static::class . " not loaded by manifest, or no database table configured" |
||
3446 | ); |
||
3447 | } |
||
3448 | |||
3449 | if ($fields) { |
||
3450 | $hasAutoIncPK = get_parent_class($this) === self::class; |
||
3451 | DB::require_table( |
||
3452 | $table, |
||
3453 | $fields, |
||
3454 | $indexes, |
||
3455 | $hasAutoIncPK, |
||
3456 | $this->config()->get('create_table_options'), |
||
3457 | $extensions |
||
3458 | ); |
||
3459 | } else { |
||
3460 | DB::dont_require_table($table); |
||
3461 | } |
||
3462 | |||
3463 | // Build any child tables for many_many items |
||
3464 | if ($manyMany = $this->uninherited('many_many')) { |
||
3465 | $extras = $this->uninherited('many_many_extraFields'); |
||
3466 | foreach ($manyMany as $component => $spec) { |
||
3467 | // Get many_many spec |
||
3468 | $manyManyComponent = $schema->manyManyComponent(static::class, $component); |
||
3469 | $parentField = $manyManyComponent['parentField']; |
||
3470 | $childField = $manyManyComponent['childField']; |
||
3471 | $tableOrClass = $manyManyComponent['join']; |
||
3472 | |||
3473 | // Skip if backed by actual class |
||
3474 | if (class_exists($tableOrClass)) { |
||
3475 | continue; |
||
3476 | } |
||
3477 | |||
3478 | // Build fields |
||
3479 | $manymanyFields = array( |
||
3480 | $parentField => "Int", |
||
3481 | $childField => "Int", |
||
3482 | ); |
||
3483 | if (isset($extras[$component])) { |
||
3484 | $manymanyFields = array_merge($manymanyFields, $extras[$component]); |
||
3485 | } |
||
3486 | |||
3487 | // Build index list |
||
3488 | $manymanyIndexes = [ |
||
3489 | $parentField => [ |
||
3490 | 'type' => 'index', |
||
3491 | 'name' => $parentField, |
||
3492 | 'columns' => [$parentField], |
||
3493 | ], |
||
3494 | $childField => [ |
||
3495 | 'type' => 'index', |
||
3496 | 'name' => $childField, |
||
3497 | 'columns' => [$childField], |
||
3498 | ], |
||
3499 | ]; |
||
3500 | DB::require_table($tableOrClass, $manymanyFields, $manymanyIndexes, true, null, $extensions); |
||
3501 | } |
||
3502 | } |
||
3503 | |||
3504 | // Let any extentions make their own database fields |
||
3505 | $this->extend('augmentDatabase', $dummy); |
||
3506 | } |
||
3507 | |||
3508 | /** |
||
3509 | * Add default records to database. This function is called whenever the |
||
3510 | * database is built, after the database tables have all been created. Overload |
||
3511 | * this to add default records when the database is built, but make sure you |
||
3512 | * call parent::requireDefaultRecords(). |
||
3513 | * |
||
3514 | * @uses DataExtension->requireDefaultRecords() |
||
3515 | */ |
||
3516 | public function requireDefaultRecords() |
||
3517 | { |
||
3518 | $defaultRecords = $this->config()->uninherited('default_records'); |
||
3519 | |||
3520 | if (!empty($defaultRecords)) { |
||
3521 | $hasData = DataObject::get_one(static::class); |
||
3522 | if (!$hasData) { |
||
3523 | $className = static::class; |
||
3524 | foreach ($defaultRecords as $record) { |
||
3525 | $obj = Injector::inst()->create($className, $record); |
||
3526 | $obj->write(); |
||
3527 | } |
||
3528 | DB::alteration_message("Added default records to $className table", "created"); |
||
3529 | } |
||
3530 | } |
||
3531 | |||
3532 | // Let any extentions make their own database default data |
||
3533 | $this->extend('requireDefaultRecords', $dummy); |
||
3534 | } |
||
3535 | |||
3536 | /** |
||
3537 | * Get the default searchable fields for this object, as defined in the |
||
3538 | * $searchable_fields list. If searchable fields are not defined on the |
||
3539 | * data object, uses a default selection of summary fields. |
||
3540 | * |
||
3541 | * @return array |
||
3542 | */ |
||
3543 | public function searchableFields() |
||
3544 | { |
||
3545 | // can have mixed format, need to make consistent in most verbose form |
||
3546 | $fields = $this->config()->get('searchable_fields'); |
||
3547 | $labels = $this->fieldLabels(); |
||
3548 | |||
3549 | // fallback to summary fields (unless empty array is explicitly specified) |
||
3550 | if (!$fields && !is_array($fields)) { |
||
3551 | $summaryFields = array_keys($this->summaryFields()); |
||
3552 | $fields = array(); |
||
3553 | |||
3554 | // remove the custom getters as the search should not include them |
||
3555 | $schema = static::getSchema(); |
||
3556 | if ($summaryFields) { |
||
3557 | foreach ($summaryFields as $key => $name) { |
||
3558 | $spec = $name; |
||
3559 | |||
3560 | // Extract field name in case this is a method called on a field (e.g. "Date.Nice") |
||
3561 | if (($fieldPos = strpos($name, '.')) !== false) { |
||
3562 | $name = substr($name, 0, $fieldPos); |
||
3563 | } |
||
3564 | |||
3565 | if ($schema->fieldSpec($this, $name)) { |
||
3566 | $fields[] = $name; |
||
3567 | } elseif ($this->relObject($spec)) { |
||
3568 | $fields[] = $spec; |
||
3569 | } |
||
3570 | } |
||
3571 | } |
||
3572 | } |
||
3573 | |||
3574 | // we need to make sure the format is unified before |
||
3575 | // augmenting fields, so extensions can apply consistent checks |
||
3576 | // but also after augmenting fields, because the extension |
||
3577 | // might use the shorthand notation as well |
||
3578 | |||
3579 | // rewrite array, if it is using shorthand syntax |
||
3580 | $rewrite = array(); |
||
3581 | foreach ($fields as $name => $specOrName) { |
||
3582 | $identifer = (is_int($name)) ? $specOrName : $name; |
||
3583 | |||
3584 | if (is_int($name)) { |
||
3585 | // Format: array('MyFieldName') |
||
3586 | $rewrite[$identifer] = array(); |
||
3587 | } elseif (is_array($specOrName) && ($relObject = $this->relObject($identifer))) { |
||
3588 | // Format: array('MyFieldName' => array( |
||
3589 | // 'filter => 'ExactMatchFilter', |
||
3590 | // 'field' => 'NumericField', // optional |
||
3591 | // 'title' => 'My Title', // optional |
||
3592 | // )) |
||
3593 | $rewrite[$identifer] = array_merge( |
||
3594 | array('filter' => $relObject->config()->get('default_search_filter_class')), |
||
3595 | (array)$specOrName |
||
3596 | ); |
||
3597 | } else { |
||
3598 | // Format: array('MyFieldName' => 'ExactMatchFilter') |
||
3599 | $rewrite[$identifer] = array( |
||
3600 | 'filter' => $specOrName, |
||
3601 | ); |
||
3602 | } |
||
3603 | if (!isset($rewrite[$identifer]['title'])) { |
||
3604 | $rewrite[$identifer]['title'] = (isset($labels[$identifer])) |
||
3605 | ? $labels[$identifer] : FormField::name_to_label($identifer); |
||
3606 | } |
||
3607 | if (!isset($rewrite[$identifer]['filter'])) { |
||
3608 | /** @skipUpgrade */ |
||
3609 | $rewrite[$identifer]['filter'] = 'PartialMatchFilter'; |
||
3610 | } |
||
3611 | } |
||
3612 | |||
3613 | $fields = $rewrite; |
||
3614 | |||
3615 | // apply DataExtensions if present |
||
3616 | $this->extend('updateSearchableFields', $fields); |
||
3617 | |||
3618 | return $fields; |
||
3619 | } |
||
3620 | |||
3621 | /** |
||
3622 | * Get any user defined searchable fields labels that |
||
3623 | * exist. Allows overriding of default field names in the form |
||
3624 | * interface actually presented to the user. |
||
3625 | * |
||
3626 | * The reason for keeping this separate from searchable_fields, |
||
3627 | * which would be a logical place for this functionality, is to |
||
3628 | * avoid bloating and complicating the configuration array. Currently |
||
3629 | * much of this system is based on sensible defaults, and this property |
||
3630 | * would generally only be set in the case of more complex relationships |
||
3631 | * between data object being required in the search interface. |
||
3632 | * |
||
3633 | * Generates labels based on name of the field itself, if no static property |
||
3634 | * {@link self::field_labels} exists. |
||
3635 | * |
||
3636 | * @uses $field_labels |
||
3637 | * @uses FormField::name_to_label() |
||
3638 | * |
||
3639 | * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields |
||
3640 | * |
||
3641 | * @return array Array of all element labels |
||
3642 | */ |
||
3643 | public function fieldLabels($includerelations = true) |
||
3644 | { |
||
3645 | $cacheKey = static::class . '_' . $includerelations; |
||
3646 | |||
3647 | if (!isset(self::$_cache_field_labels[$cacheKey])) { |
||
3648 | $customLabels = $this->config()->get('field_labels'); |
||
3649 | $autoLabels = array(); |
||
3650 | |||
3651 | // get all translated static properties as defined in i18nCollectStatics() |
||
3652 | $ancestry = ClassInfo::ancestry(static::class); |
||
3653 | $ancestry = array_reverse($ancestry); |
||
3654 | if ($ancestry) { |
||
3655 | foreach ($ancestry as $ancestorClass) { |
||
3656 | if ($ancestorClass === ViewableData::class) { |
||
3657 | break; |
||
3658 | } |
||
3659 | $types = [ |
||
3660 | 'db' => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED) |
||
3661 | ]; |
||
3662 | if ($includerelations) { |
||
3663 | $types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED); |
||
3664 | $types['has_many'] = (array)Config::inst()->get( |
||
3665 | $ancestorClass, |
||
3666 | 'has_many', |
||
3667 | Config::UNINHERITED |
||
3668 | ); |
||
3669 | $types['many_many'] = (array)Config::inst()->get( |
||
3670 | $ancestorClass, |
||
3671 | 'many_many', |
||
3672 | Config::UNINHERITED |
||
3673 | ); |
||
3674 | $types['belongs_many_many'] = (array)Config::inst()->get( |
||
3675 | $ancestorClass, |
||
3676 | 'belongs_many_many', |
||
3677 | Config::UNINHERITED |
||
3678 | ); |
||
3679 | } |
||
3680 | foreach ($types as $type => $attrs) { |
||
3681 | foreach ($attrs as $name => $spec) { |
||
3682 | $autoLabels[$name] = _t( |
||
3683 | "{$ancestorClass}.{$type}_{$name}", |
||
3684 | FormField::name_to_label($name) |
||
3685 | ); |
||
3686 | } |
||
3687 | } |
||
3688 | } |
||
3689 | } |
||
3690 | |||
3691 | $labels = array_merge((array)$autoLabels, (array)$customLabels); |
||
3692 | $this->extend('updateFieldLabels', $labels); |
||
3693 | self::$_cache_field_labels[$cacheKey] = $labels; |
||
3694 | } |
||
3695 | |||
3696 | return self::$_cache_field_labels[$cacheKey]; |
||
3697 | } |
||
3698 | |||
3699 | /** |
||
3700 | * Get a human-readable label for a single field, |
||
3701 | * see {@link fieldLabels()} for more details. |
||
3702 | * |
||
3703 | * @uses fieldLabels() |
||
3704 | * @uses FormField::name_to_label() |
||
3705 | * |
||
3706 | * @param string $name Name of the field |
||
3707 | * @return string Label of the field |
||
3708 | */ |
||
3709 | public function fieldLabel($name) |
||
3710 | { |
||
3711 | $labels = $this->fieldLabels(); |
||
3712 | return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name); |
||
3713 | } |
||
3714 | |||
3715 | /** |
||
3716 | * Get the default summary fields for this object. |
||
3717 | * |
||
3718 | * @todo use the translation apparatus to return a default field selection for the language |
||
3719 | * |
||
3720 | * @return array |
||
3721 | */ |
||
3722 | public function summaryFields() |
||
3723 | { |
||
3724 | $rawFields = $this->config()->get('summary_fields'); |
||
3725 | |||
3726 | // Merge associative / numeric keys |
||
3727 | $fields = []; |
||
3728 | foreach ($rawFields as $key => $value) { |
||
3729 | if (is_int($key)) { |
||
3730 | $key = $value; |
||
3731 | } |
||
3732 | $fields[$key] = $value; |
||
3733 | } |
||
3734 | |||
3735 | if (!$fields) { |
||
3736 | $fields = array(); |
||
3737 | // try to scaffold a couple of usual suspects |
||
3738 | if ($this->hasField('Name')) { |
||
3739 | $fields['Name'] = 'Name'; |
||
3740 | } |
||
3741 | if (static::getSchema()->fieldSpec($this, 'Title')) { |
||
3742 | $fields['Title'] = 'Title'; |
||
3743 | } |
||
3744 | if ($this->hasField('Description')) { |
||
3745 | $fields['Description'] = 'Description'; |
||
3746 | } |
||
3747 | if ($this->hasField('FirstName')) { |
||
3748 | $fields['FirstName'] = 'First Name'; |
||
3749 | } |
||
3750 | } |
||
3751 | $this->extend("updateSummaryFields", $fields); |
||
3752 | |||
3753 | // Final fail-over, just list ID field |
||
3754 | if (!$fields) { |
||
3755 | $fields['ID'] = 'ID'; |
||
3756 | } |
||
3757 | |||
3758 | // Localize fields (if possible) |
||
3759 | foreach ($this->fieldLabels(false) as $name => $label) { |
||
3760 | // only attempt to localize if the label definition is the same as the field name. |
||
3761 | // this will preserve any custom labels set in the summary_fields configuration |
||
3762 | if (isset($fields[$name]) && $name === $fields[$name]) { |
||
3763 | $fields[$name] = $label; |
||
3764 | } |
||
3765 | } |
||
3766 | |||
3767 | return $fields; |
||
3768 | } |
||
3769 | |||
3770 | /** |
||
3771 | * Defines a default list of filters for the search context. |
||
3772 | * |
||
3773 | * If a filter class mapping is defined on the data object, |
||
3774 | * it is constructed here. Otherwise, the default filter specified in |
||
3775 | * {@link DBField} is used. |
||
3776 | * |
||
3777 | * @todo error handling/type checking for valid FormField and SearchFilter subclasses? |
||
3778 | * |
||
3779 | * @return array |
||
3780 | */ |
||
3781 | public function defaultSearchFilters() |
||
3782 | { |
||
3783 | $filters = array(); |
||
3784 | |||
3785 | foreach ($this->searchableFields() as $name => $spec) { |
||
3786 | if (empty($spec['filter'])) { |
||
3787 | /** @skipUpgrade */ |
||
3788 | $filters[$name] = 'PartialMatchFilter'; |
||
3789 | } elseif ($spec['filter'] instanceof SearchFilter) { |
||
3790 | $filters[$name] = $spec['filter']; |
||
3791 | } else { |
||
3792 | $filters[$name] = Injector::inst()->create($spec['filter'], $name); |
||
3793 | } |
||
3794 | } |
||
3795 | |||
3796 | return $filters; |
||
3797 | } |
||
3798 | |||
3799 | /** |
||
3800 | * @return boolean True if the object is in the database |
||
3801 | */ |
||
3802 | public function isInDB() |
||
3803 | { |
||
3804 | return is_numeric($this->ID) && $this->ID > 0; |
||
3805 | } |
||
3806 | |||
3807 | /* |
||
3808 | * @ignore |
||
3809 | */ |
||
3810 | private static $subclass_access = true; |
||
3811 | |||
3812 | /** |
||
3813 | * Temporarily disable subclass access in data object qeur |
||
3814 | */ |
||
3815 | public static function disable_subclass_access() |
||
3816 | { |
||
3817 | self::$subclass_access = false; |
||
3818 | } |
||
3819 | |||
3820 | public static function enable_subclass_access() |
||
3821 | { |
||
3822 | self::$subclass_access = true; |
||
3823 | } |
||
3824 | |||
3825 | //-------------------------------------------------------------------------------------------// |
||
3826 | |||
3827 | /** |
||
3828 | * Database field definitions. |
||
3829 | * This is a map from field names to field type. The field |
||
3830 | * type should be a class that extends . |
||
3831 | * @var array |
||
3832 | * @config |
||
3833 | */ |
||
3834 | private static $db = []; |
||
3835 | |||
3836 | /** |
||
3837 | * Use a casting object for a field. This is a map from |
||
3838 | * field name to class name of the casting object. |
||
3839 | * |
||
3840 | * @var array |
||
3841 | */ |
||
3842 | private static $casting = array( |
||
3843 | "Title" => 'Text', |
||
3844 | ); |
||
3845 | |||
3846 | /** |
||
3847 | * Specify custom options for a CREATE TABLE call. |
||
3848 | * Can be used to specify a custom storage engine for specific database table. |
||
3849 | * All options have to be keyed for a specific database implementation, |
||
3850 | * identified by their class name (extending from {@link SS_Database}). |
||
3851 | * |
||
3852 | * <code> |
||
3853 | * array( |
||
3854 | * 'MySQLDatabase' => 'ENGINE=MyISAM' |
||
3855 | * ) |
||
3856 | * </code> |
||
3857 | * |
||
3858 | * Caution: This API is experimental, and might not be |
||
3859 | * included in the next major release. Please use with care. |
||
3860 | * |
||
3861 | * @var array |
||
3862 | * @config |
||
3863 | */ |
||
3864 | private static $create_table_options = array( |
||
3865 | MySQLSchemaManager::ID => 'ENGINE=InnoDB' |
||
3866 | ); |
||
3867 | |||
3868 | /** |
||
3869 | * If a field is in this array, then create a database index |
||
3870 | * on that field. This is a map from fieldname to index type. |
||
3871 | * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation. |
||
3872 | * |
||
3873 | * @var array |
||
3874 | * @config |
||
3875 | */ |
||
3876 | private static $indexes = null; |
||
3877 | |||
3878 | /** |
||
3879 | * Inserts standard column-values when a DataObject |
||
3880 | * is instantiated. Does not insert default records {@see $default_records}. |
||
3881 | * This is a map from fieldname to default value. |
||
3882 | * |
||
3883 | * - If you would like to change a default value in a sub-class, just specify it. |
||
3884 | * - If you would like to disable the default value given by a parent class, set the default value to 0,'', |
||
3885 | * or false in your subclass. Setting it to null won't work. |
||
3886 | * |
||
3887 | * @var array |
||
3888 | * @config |
||
3889 | */ |
||
3890 | private static $defaults = []; |
||
3891 | |||
3892 | /** |
||
3893 | * Multidimensional array which inserts default data into the database |
||
3894 | * on a db/build-call as long as the database-table is empty. Please use this only |
||
3895 | * for simple constructs, not for SiteTree-Objects etc. which need special |
||
3896 | * behaviour such as publishing and ParentNodes. |
||
3897 | * |
||
3898 | * Example: |
||
3899 | * array( |
||
3900 | * array('Title' => "DefaultPage1", 'PageTitle' => 'page1'), |
||
3901 | * array('Title' => "DefaultPage2") |
||
3902 | * ). |
||
3903 | * |
||
3904 | * @var array |
||
3905 | * @config |
||
3906 | */ |
||
3907 | private static $default_records = null; |
||
3908 | |||
3909 | /** |
||
3910 | * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a |
||
3911 | * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class. |
||
3912 | * |
||
3913 | * Note that you cannot have a has_one and belongs_to relationship with the same name. |
||
3914 | * |
||
3915 | * @var array |
||
3916 | * @config |
||
3917 | */ |
||
3918 | private static $has_one = []; |
||
3919 | |||
3920 | /** |
||
3921 | * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}. |
||
3922 | * |
||
3923 | * This does not actually create any data structures, but allows you to query the other object in a one-to-one |
||
3924 | * relationship from the child object. If you have multiple belongs_to links to another object you can use the |
||
3925 | * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use. |
||
3926 | * |
||
3927 | * Note that you cannot have a has_one and belongs_to relationship with the same name. |
||
3928 | * |
||
3929 | * @var array |
||
3930 | * @config |
||
3931 | */ |
||
3932 | private static $belongs_to = []; |
||
3933 | |||
3934 | /** |
||
3935 | * This defines a one-to-many relationship. It is a map of component name to the remote data class. |
||
3936 | * |
||
3937 | * This relationship type does not actually create a data structure itself - you need to define a matching $has_one |
||
3938 | * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this |
||
3939 | * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show |
||
3940 | * which foreign key to use. |
||
3941 | * |
||
3942 | * @var array |
||
3943 | * @config |
||
3944 | */ |
||
3945 | private static $has_many = []; |
||
3946 | |||
3947 | /** |
||
3948 | * many-many relationship definitions. |
||
3949 | * This is a map from component name to data type. |
||
3950 | * @var array |
||
3951 | * @config |
||
3952 | */ |
||
3953 | private static $many_many = []; |
||
3954 | |||
3955 | /** |
||
3956 | * Extra fields to include on the connecting many-many table. |
||
3957 | * This is a map from field name to field type. |
||
3958 | * |
||
3959 | * Example code: |
||
3960 | * <code> |
||
3961 | * public static $many_many_extraFields = array( |
||
3962 | * 'Members' => array( |
||
3963 | * 'Role' => 'Varchar(100)' |
||
3964 | * ) |
||
3965 | * ); |
||
3966 | * </code> |
||
3967 | * |
||
3968 | * @var array |
||
3969 | * @config |
||
3970 | */ |
||
3971 | private static $many_many_extraFields = []; |
||
3972 | |||
3973 | /** |
||
3974 | * The inverse side of a many-many relationship. |
||
3975 | * This is a map from component name to data type. |
||
3976 | * @var array |
||
3977 | * @config |
||
3978 | */ |
||
3979 | private static $belongs_many_many = []; |
||
3980 | |||
3981 | /** |
||
3982 | * The default sort expression. This will be inserted in the ORDER BY |
||
3983 | * clause of a SQL query if no other sort expression is provided. |
||
3984 | * @var string |
||
3985 | * @config |
||
3986 | */ |
||
3987 | private static $default_sort = null; |
||
3988 | |||
3989 | /** |
||
3990 | * Default list of fields that can be scaffolded by the ModelAdmin |
||
3991 | * search interface. |
||
3992 | * |
||
3993 | * Overriding the default filter, with a custom defined filter: |
||
3994 | * <code> |
||
3995 | * static $searchable_fields = array( |
||
3996 | * "Name" => "PartialMatchFilter" |
||
3997 | * ); |
||
3998 | * </code> |
||
3999 | * |
||
4000 | * Overriding the default form fields, with a custom defined field. |
||
4001 | * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}. |
||
4002 | * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}. |
||
4003 | * <code> |
||
4004 | * static $searchable_fields = array( |
||
4005 | * "Name" => array( |
||
4006 | * "field" => "TextField" |
||
4007 | * ) |
||
4008 | * ); |
||
4009 | * </code> |
||
4010 | * |
||
4011 | * Overriding the default form field, filter and title: |
||
4012 | * <code> |
||
4013 | * static $searchable_fields = array( |
||
4014 | * "Organisation.ZipCode" => array( |
||
4015 | * "field" => "TextField", |
||
4016 | * "filter" => "PartialMatchFilter", |
||
4017 | * "title" => 'Organisation ZIP' |
||
4018 | * ) |
||
4019 | * ); |
||
4020 | * </code> |
||
4021 | * @config |
||
4022 | * @var array |
||
4023 | */ |
||
4024 | private static $searchable_fields = null; |
||
4025 | |||
4026 | /** |
||
4027 | * User defined labels for searchable_fields, used to override |
||
4028 | * default display in the search form. |
||
4029 | * @config |
||
4030 | * @var array |
||
4031 | */ |
||
4032 | private static $field_labels = []; |
||
4033 | |||
4034 | /** |
||
4035 | * Provides a default list of fields to be used by a 'summary' |
||
4036 | * view of this object. |
||
4037 | * @config |
||
4038 | * @var array |
||
4039 | */ |
||
4040 | private static $summary_fields = []; |
||
4041 | |||
4042 | public function provideI18nEntities() |
||
4043 | { |
||
4044 | // Note: see http://guides.rubyonrails.org/i18n.html#pluralization for rules |
||
4045 | // Best guess for a/an rule. Better guesses require overriding in subclasses |
||
4046 | $pluralName = $this->plural_name(); |
||
4047 | $singularName = $this->singular_name(); |
||
4048 | $conjunction = preg_match('/^[aeiou]/i', $singularName) ? 'An ' : 'A '; |
||
4049 | return [ |
||
4050 | static::class . '.SINGULARNAME' => $this->singular_name(), |
||
4051 | static::class . '.PLURALNAME' => $pluralName, |
||
4052 | static::class . '.PLURALS' => [ |
||
4053 | 'one' => $conjunction . $singularName, |
||
4054 | 'other' => '{count} ' . $pluralName |
||
4055 | ] |
||
4056 | ]; |
||
4057 | } |
||
4058 | |||
4059 | /** |
||
4060 | * Returns true if the given method/parameter has a value |
||
4061 | * (Uses the DBField::hasValue if the parameter is a database field) |
||
4062 | * |
||
4063 | * @param string $field The field name |
||
4064 | * @param array $arguments |
||
4065 | * @param bool $cache |
||
4066 | * @return boolean |
||
4067 | */ |
||
4068 | public function hasValue($field, $arguments = null, $cache = true) |
||
4069 | { |
||
4070 | // has_one fields should not use dbObject to check if a value is given |
||
4071 | $hasOne = static::getSchema()->hasOneComponent(static::class, $field); |
||
4072 | if (!$hasOne && ($obj = $this->dbObject($field))) { |
||
4073 | return $obj->exists(); |
||
4074 | } else { |
||
4075 | return parent::hasValue($field, $arguments, $cache); |
||
4076 | } |
||
4077 | } |
||
4078 | |||
4079 | /** |
||
4080 | * If selected through a many_many through relation, this is the instance of the joined record |
||
4081 | * |
||
4082 | * @return DataObject |
||
4083 | */ |
||
4084 | public function getJoin() |
||
4085 | { |
||
4086 | return $this->joinRecord; |
||
4087 | } |
||
4088 | |||
4089 | /** |
||
4090 | * Set joining object |
||
4091 | * |
||
4092 | * @param DataObject $object |
||
4093 | * @param string $alias Alias |
||
4094 | * @return $this |
||
4095 | */ |
||
4096 | public function setJoin(DataObject $object, $alias = null) |
||
4097 | { |
||
4098 | $this->joinRecord = $object; |
||
4099 | if ($alias) { |
||
4100 | if (static::getSchema()->fieldSpec(static::class, $alias)) { |
||
4101 | throw new InvalidArgumentException( |
||
4102 | "Joined record $alias cannot also be a db field" |
||
4103 | ); |
||
4104 | } |
||
4105 | $this->record[$alias] = $object; |
||
4106 | } |
||
4107 | return $this; |
||
4108 | } |
||
4109 | |||
4110 | /** |
||
4111 | * Find objects in the given relationships, merging them into the given list |
||
4112 | * |
||
4113 | * @param string $source Config property to extract relationships from |
||
4114 | * @param bool $recursive True if recursive |
||
4115 | * @param ArrayList $list If specified, items will be added to this list. If not, a new |
||
4116 | * instance of ArrayList will be constructed and returned |
||
4117 | * @return ArrayList The list of related objects |
||
4118 | */ |
||
4119 | public function findRelatedObjects($source, $recursive = true, $list = null) |
||
4158 | } |
||
4159 | |||
4160 | /** |
||
4161 | * Helper method to merge owned/owning items into a list. |
||
4162 | * Items already present in the list will be skipped. |
||
4163 | * |
||
4164 | * @param ArrayList $list Items to merge into |
||
4165 | * @param mixed $items List of new items to merge |
||
4166 | * @return ArrayList List of all newly added items that did not already exist in $list |
||
4167 | */ |
||
4168 | public function mergeRelatedObjects($list, $items) |
||
4169 | { |
||
4170 | $added = new ArrayList(); |
||
4171 | if (!$items) { |
||
4172 | return $added; |
||
4173 | } |
||
4174 | if ($items instanceof DataObject) { |
||
4175 | $items = [$items]; |
||
4176 | } |
||
4177 | |||
4178 | /** @var DataObject $item */ |
||
4179 | foreach ($items as $item) { |
||
4180 | $this->mergeRelatedObject($list, $added, $item); |
||
4181 | } |
||
4182 | return $added; |
||
4183 | } |
||
4184 | |||
4185 | /** |
||
4186 | * Merge single object into a list, but ensures that existing objects are not |
||
4187 | * re-added. |
||
4188 | * |
||
4189 | * @param ArrayList $list Global list |
||
4190 | * @param ArrayList $added Additional list to insert into |
||
4191 | * @param DataObject $item Item to add |
||
4192 | */ |
||
4193 | protected function mergeRelatedObject($list, $added, $item) |
||
4208 | } |
||
4209 | } |
||
4210 | } |
||
4211 |