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