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 |
||
82 | class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider { |
||
83 | |||
84 | /** |
||
85 | * Human-readable singular name. |
||
86 | * @var string |
||
87 | * @config |
||
88 | */ |
||
89 | private static $singular_name = null; |
||
90 | |||
91 | /** |
||
92 | * Human-readable plural name |
||
93 | * @var string |
||
94 | * @config |
||
95 | */ |
||
96 | private static $plural_name = null; |
||
97 | |||
98 | /** |
||
99 | * Allow API access to this object? |
||
100 | * @todo Define the options that can be set here |
||
101 | * @config |
||
102 | */ |
||
103 | private static $api_access = false; |
||
104 | |||
105 | /** |
||
106 | * Allows specification of a default value for the ClassName field. |
||
107 | * Configure this value only in subclasses of DataObject. |
||
108 | * |
||
109 | * @config |
||
110 | * @var string |
||
111 | */ |
||
112 | private static $default_classname = null; |
||
113 | |||
114 | /** |
||
115 | * True if this DataObject has been destroyed. |
||
116 | * @var boolean |
||
117 | */ |
||
118 | public $destroyed = false; |
||
119 | |||
120 | /** |
||
121 | * The DataModel from this this object comes |
||
122 | */ |
||
123 | protected $model; |
||
124 | |||
125 | /** |
||
126 | * Data stored in this objects database record. An array indexed by fieldname. |
||
127 | * |
||
128 | * Use {@link toMap()} if you want an array representation |
||
129 | * of this object, as the $record array might contain lazy loaded field aliases. |
||
130 | * |
||
131 | * @var array |
||
132 | */ |
||
133 | protected $record; |
||
134 | |||
135 | /** |
||
136 | * Represents a field that hasn't changed (before === after, thus before == after) |
||
137 | */ |
||
138 | const CHANGE_NONE = 0; |
||
139 | |||
140 | /** |
||
141 | * Represents a field that has changed type, although not the loosely defined value. |
||
142 | * (before !== after && before == after) |
||
143 | * E.g. change 1 to true or "true" to true, but not true to 0. |
||
144 | * Value changes are by nature also considered strict changes. |
||
145 | */ |
||
146 | const CHANGE_STRICT = 1; |
||
147 | |||
148 | /** |
||
149 | * Represents a field that has changed the loosely defined value |
||
150 | * (before != after, thus, before !== after)) |
||
151 | * E.g. change false to true, but not false to 0 |
||
152 | */ |
||
153 | const CHANGE_VALUE = 2; |
||
154 | |||
155 | /** |
||
156 | * An array indexed by fieldname, true if the field has been changed. |
||
157 | * Use {@link getChangedFields()} and {@link isChanged()} to inspect |
||
158 | * the changed state. |
||
159 | * |
||
160 | * @var array |
||
161 | */ |
||
162 | private $changed; |
||
163 | |||
164 | /** |
||
165 | * The database record (in the same format as $record), before |
||
166 | * any changes. |
||
167 | * @var array |
||
168 | */ |
||
169 | protected $original; |
||
170 | |||
171 | /** |
||
172 | * Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete() |
||
173 | * @var boolean |
||
174 | */ |
||
175 | protected $brokenOnDelete = false; |
||
176 | |||
177 | /** |
||
178 | * Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite() |
||
179 | * @var boolean |
||
180 | */ |
||
181 | protected $brokenOnWrite = false; |
||
182 | |||
183 | /** |
||
184 | * @config |
||
185 | * @var boolean Should dataobjects be validated before they are written? |
||
186 | * Caution: Validation can contain safeguards against invalid/malicious data, |
||
187 | * and check permission levels (e.g. on {@link Group}). Therefore it is recommended |
||
188 | * to only disable validation for very specific use cases. |
||
189 | */ |
||
190 | private static $validation_enabled = true; |
||
191 | |||
192 | /** |
||
193 | * Static caches used by relevant functions. |
||
194 | */ |
||
195 | protected static $_cache_has_own_table = array(); |
||
196 | protected static $_cache_get_one; |
||
197 | protected static $_cache_get_class_ancestry; |
||
198 | protected static $_cache_composite_fields = array(); |
||
199 | protected static $_cache_database_fields = array(); |
||
200 | protected static $_cache_field_labels = array(); |
||
201 | |||
202 | /** |
||
203 | * Base fields which are not defined in static $db |
||
204 | * |
||
205 | * @config |
||
206 | * @var array |
||
207 | */ |
||
208 | private static $fixed_fields = array( |
||
209 | 'ID' => 'PrimaryKey', |
||
210 | 'ClassName' => 'DBClassName', |
||
211 | 'LastEdited' => 'SS_Datetime', |
||
212 | 'Created' => 'SS_Datetime', |
||
213 | ); |
||
214 | |||
215 | /** |
||
216 | * Core dataobject extensions |
||
217 | * |
||
218 | * @config |
||
219 | * @var array |
||
220 | */ |
||
221 | private static $extensions = array( |
||
222 | 'AssetControl' => '\\SilverStripe\\Filesystem\\AssetControlExtension' |
||
223 | ); |
||
224 | |||
225 | /** |
||
226 | * Non-static relationship cache, indexed by component name. |
||
227 | */ |
||
228 | protected $components; |
||
229 | |||
230 | /** |
||
231 | * Non-static cache of has_many and many_many relations that can't be written until this object is saved. |
||
232 | */ |
||
233 | protected $unsavedRelations; |
||
234 | |||
235 | /** |
||
236 | * Return the complete map of fields to specification on this object, including fixed_fields. |
||
237 | * "ID" will be included on every table. |
||
238 | * |
||
239 | * Composite DB field specifications are returned by reference if necessary, but not in the return |
||
240 | * array. |
||
241 | * |
||
242 | * Can be called directly on an object. E.g. Member::database_fields() |
||
243 | * |
||
244 | * @param string $class Class name to query from |
||
245 | * @return array Map of fieldname to specification, similiar to {@link DataObject::$db}. |
||
246 | */ |
||
247 | public static function database_fields($class = null) { |
||
248 | if(empty($class)) { |
||
249 | $class = get_called_class(); |
||
250 | } |
||
251 | |||
252 | // Refresh cache |
||
253 | self::cache_database_fields($class); |
||
254 | |||
255 | // Return cached values |
||
256 | return self::$_cache_database_fields[$class]; |
||
257 | } |
||
258 | |||
259 | /** |
||
260 | * Cache all database and composite fields for the given class. |
||
261 | * Will do nothing if already cached |
||
262 | * |
||
263 | * @param string $class Class name to cache |
||
264 | */ |
||
265 | protected static function cache_database_fields($class) { |
||
266 | // Skip if already cached |
||
267 | if( isset(self::$_cache_database_fields[$class]) |
||
268 | && isset(self::$_cache_composite_fields[$class]) |
||
269 | ) { |
||
270 | return; |
||
271 | } |
||
272 | |||
273 | $compositeFields = array(); |
||
274 | $dbFields = array(); |
||
275 | |||
276 | // Ensure fixed fields appear at the start |
||
277 | $fixedFields = self::config()->fixed_fields; |
||
|
|||
278 | if(get_parent_class($class) === 'DataObject') { |
||
279 | // Merge fixed with ClassName spec and custom db fields |
||
280 | $dbFields = $fixedFields; |
||
281 | } else { |
||
282 | $dbFields['ID'] = $fixedFields['ID']; |
||
283 | } |
||
284 | |||
285 | // Check each DB value as either a field or composite field |
||
286 | $db = Config::inst()->get($class, 'db', Config::UNINHERITED) ?: array(); |
||
287 | foreach($db as $fieldName => $fieldSpec) { |
||
288 | $fieldClass = strtok($fieldSpec, '('); |
||
289 | if(singleton($fieldClass) instanceof DBComposite) { |
||
290 | $compositeFields[$fieldName] = $fieldSpec; |
||
291 | } else { |
||
292 | $dbFields[$fieldName] = $fieldSpec; |
||
293 | } |
||
294 | } |
||
295 | |||
296 | // Add in all has_ones |
||
297 | $hasOne = Config::inst()->get($class, 'has_one', Config::UNINHERITED) ?: array(); |
||
298 | foreach($hasOne as $fieldName => $hasOneClass) { |
||
299 | if($hasOneClass === 'DataObject') { |
||
300 | $compositeFields[$fieldName] = 'PolymorphicForeignKey'; |
||
301 | } else { |
||
302 | $dbFields["{$fieldName}ID"] = 'ForeignKey'; |
||
303 | } |
||
304 | } |
||
305 | |||
306 | // Merge composite fields into DB |
||
307 | foreach($compositeFields as $fieldName => $fieldSpec) { |
||
308 | $fieldObj = Object::create_from_string($fieldSpec, $fieldName); |
||
309 | $fieldObj->setTable($class); |
||
310 | $nestedFields = $fieldObj->compositeDatabaseFields(); |
||
311 | foreach($nestedFields as $nestedName => $nestedSpec) { |
||
312 | $dbFields["{$fieldName}{$nestedName}"] = $nestedSpec; |
||
313 | } |
||
314 | } |
||
315 | |||
316 | // Return cached results |
||
317 | self::$_cache_database_fields[$class] = $dbFields; |
||
318 | self::$_cache_composite_fields[$class] = $compositeFields; |
||
319 | } |
||
320 | |||
321 | /** |
||
322 | * Get all database columns explicitly defined on a class in {@link DataObject::$db} |
||
323 | * and {@link DataObject::$has_one}. Resolves instances of {@link DBComposite} |
||
324 | * into the actual database fields, rather than the name of the field which |
||
325 | * might not equate a database column. |
||
326 | * |
||
327 | * Does not include "base fields" like "ID", "ClassName", "Created", "LastEdited", |
||
328 | * see {@link database_fields()}. |
||
329 | * |
||
330 | * Can be called directly on an object. E.g. Member::custom_database_fields() |
||
331 | * |
||
332 | * @uses DBComposite->compositeDatabaseFields() |
||
333 | * |
||
334 | * @param string $class Class name to query from |
||
335 | * @return array Map of fieldname to specification, similiar to {@link DataObject::$db}. |
||
336 | */ |
||
337 | public static function custom_database_fields($class = null) { |
||
338 | if(empty($class)) { |
||
339 | $class = get_called_class(); |
||
340 | } |
||
341 | |||
342 | // Get all fields |
||
343 | $fields = self::database_fields($class); |
||
344 | |||
345 | // Remove fixed fields. This assumes that NO fixed_fields are composite |
||
346 | $fields = array_diff_key($fields, self::config()->fixed_fields); |
||
347 | return $fields; |
||
348 | } |
||
349 | |||
350 | /** |
||
351 | * Returns the field class if the given db field on the class is a composite field. |
||
352 | * Will check all applicable ancestor classes and aggregate results. |
||
353 | * |
||
354 | * @param string $class Class to check |
||
355 | * @param string $name Field to check |
||
356 | * @param boolean $aggregated True if parent classes should be checked, or false to limit to this class |
||
357 | * @return string|false Class spec name of composite field if it exists, or false if not |
||
358 | */ |
||
359 | public static function is_composite_field($class, $name, $aggregated = true) { |
||
363 | |||
364 | /** |
||
365 | * Returns a list of all the composite if the given db field on the class is a composite field. |
||
366 | * Will check all applicable ancestor classes and aggregate results. |
||
367 | * |
||
368 | * Can be called directly on an object. E.g. Member::composite_fields(), or Member::composite_fields(null, true) |
||
369 | * to aggregate. |
||
370 | * |
||
371 | * Includes composite has_one (Polymorphic) fields |
||
372 | * |
||
373 | * @param string $class Name of class to check |
||
374 | * @param bool $aggregated Include fields in entire hierarchy, rather than just on this table |
||
375 | * @return array List of composite fields and their class spec |
||
376 | */ |
||
377 | public static function composite_fields($class = null, $aggregated = true) { |
||
378 | // Check $class |
||
379 | if(empty($class)) { |
||
380 | $class = get_called_class(); |
||
381 | } |
||
382 | if($class === 'DataObject') { |
||
383 | return array(); |
||
384 | } |
||
385 | |||
386 | // Refresh cache |
||
387 | self::cache_database_fields($class); |
||
388 | |||
389 | // Get fields for this class |
||
390 | $compositeFields = self::$_cache_composite_fields[$class]; |
||
391 | if(!$aggregated) { |
||
392 | return $compositeFields; |
||
393 | } |
||
394 | |||
395 | // Recursively merge |
||
396 | return array_merge( |
||
397 | $compositeFields, |
||
398 | self::composite_fields(get_parent_class($class)) |
||
399 | ); |
||
400 | } |
||
401 | |||
402 | /** |
||
403 | * Construct a new DataObject. |
||
404 | * |
||
405 | * @param array|null $record This will be null for a new database record. Alternatively, you can pass an array of |
||
406 | * field values. Normally this contructor is only used by the internal systems that get objects from the database. |
||
407 | * @param boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods. |
||
408 | * Singletons don't have their defaults set. |
||
409 | * @param DataModel $model |
||
410 | * @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects. |
||
411 | */ |
||
412 | public function __construct($record = null, $isSingleton = false, $model = null, $queryParams = array()) { |
||
485 | |||
486 | /** |
||
487 | * Set the DataModel |
||
488 | * @param DataModel $model |
||
489 | * @return DataObject $this |
||
490 | */ |
||
491 | public function setDataModel(DataModel $model) { |
||
495 | |||
496 | /** |
||
497 | * Destroy all of this objects dependant objects and local caches. |
||
498 | * You'll need to call this to get the memory of an object that has components or extensions freed. |
||
499 | */ |
||
500 | public function destroy() { |
||
505 | |||
506 | /** |
||
507 | * Create a duplicate of this node. |
||
508 | * Note: now also duplicates relations. |
||
509 | * |
||
510 | * @param bool $doWrite Perform a write() operation before returning the object. |
||
511 | * If this is true, it will create the duplicate in the database. |
||
512 | * @return DataObject A duplicate of this node. The exact type will be the type of this node. |
||
513 | */ |
||
514 | public function duplicate($doWrite = true) { |
||
528 | |||
529 | /** |
||
530 | * Copies the many_many and belongs_many_many relations from one object to another instance of the name of object |
||
531 | * The destinationObject must be written to the database already and have an ID. Writing is performed |
||
532 | * automatically when adding the new relations. |
||
533 | * |
||
534 | * @param DataObject $sourceObject the source object to duplicate from |
||
535 | * @param DataObject $destinationObject the destination object to populate with the duplicated relations |
||
536 | * @return DataObject with the new many_many relations copied in |
||
537 | */ |
||
538 | protected function duplicateManyManyRelations($sourceObject, $destinationObject) { |
||
539 | if (!$destinationObject || $destinationObject->ID < 1) { |
||
540 | user_error("Can't duplicate relations for an object that has not been written to the database", |
||
541 | E_USER_ERROR); |
||
542 | } |
||
543 | |||
544 | //duplicate complex relations |
||
545 | // DO NOT copy has_many relations, because copying the relation would result in us changing the has_one |
||
546 | // relation on the other side of this relation to point at the copy and no longer the original (being a |
||
547 | // has_one, it can only point at one thing at a time). So, all relations except has_many can and are copied |
||
548 | if ($sourceObject->hasOne()) foreach($sourceObject->hasOne() as $name => $type) { |
||
549 | $this->duplicateRelations($sourceObject, $destinationObject, $name); |
||
550 | } |
||
551 | if ($sourceObject->manyMany()) foreach($sourceObject->manyMany() as $name => $type) { |
||
552 | //many_many include belongs_many_many |
||
553 | $this->duplicateRelations($sourceObject, $destinationObject, $name); |
||
554 | } |
||
555 | |||
556 | return $destinationObject; |
||
557 | } |
||
558 | |||
559 | /** |
||
560 | * Helper function to duplicate relations from one object to another |
||
561 | * @param $sourceObject the source object to duplicate from |
||
562 | * @param $destinationObject the destination object to populate with the duplicated relations |
||
563 | * @param $name the name of the relation to duplicate (e.g. members) |
||
564 | */ |
||
565 | private function duplicateRelations($sourceObject, $destinationObject, $name) { |
||
566 | $relations = $sourceObject->$name(); |
||
567 | if ($relations) { |
||
568 | if ($relations instanceOf RelationList) { //many-to-something relation |
||
569 | if ($relations->Count() > 0) { //with more than one thing it is related to |
||
570 | foreach($relations as $relation) { |
||
571 | $destinationObject->$name()->add($relation); |
||
572 | } |
||
573 | } |
||
574 | } else { //one-to-one relation |
||
575 | $destinationObject->{"{$name}ID"} = $relations->ID; |
||
576 | } |
||
577 | } |
||
578 | } |
||
579 | |||
580 | public function getObsoleteClassName() { |
||
584 | |||
585 | public function getClassName() { |
||
590 | |||
591 | /** |
||
592 | * Set the ClassName attribute. {@link $class} is also updated. |
||
593 | * Warning: This will produce an inconsistent record, as the object |
||
594 | * instance will not automatically switch to the new subclass. |
||
595 | * Please use {@link newClassInstance()} for this purpose, |
||
596 | * or destroy and reinstanciate the record. |
||
597 | * |
||
598 | * @param string $className The new ClassName attribute (a subclass of {@link DataObject}) |
||
599 | * @return DataObject $this |
||
600 | */ |
||
601 | public function setClassName($className) { |
||
609 | |||
610 | /** |
||
611 | * Create a new instance of a different class from this object's record. |
||
612 | * This is useful when dynamically changing the type of an instance. Specifically, |
||
613 | * it ensures that the instance of the class is a match for the className of the |
||
614 | * record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName} |
||
615 | * property manually before calling this method, as it will confuse change detection. |
||
616 | * |
||
617 | * If the new class is different to the original class, defaults are populated again |
||
618 | * because this will only occur automatically on instantiation of a DataObject if |
||
619 | * there is no record, or the record has no ID. In this case, we do have an ID but |
||
620 | * we still need to repopulate the defaults. |
||
621 | * |
||
622 | * @param string $newClassName The name of the new class |
||
623 | * |
||
624 | * @return DataObject The new instance of the new class, The exact type will be of the class name provided. |
||
625 | */ |
||
626 | public function newClassInstance($newClassName) { |
||
644 | |||
645 | /** |
||
646 | * Adds methods from the extensions. |
||
647 | * Called by Object::__construct() once per class. |
||
648 | */ |
||
649 | public function defineMethods() { |
||
688 | |||
689 | /** |
||
690 | * Returns true if this object "exists", i.e., has a sensible value. |
||
691 | * The default behaviour for a DataObject is to return true if |
||
692 | * the object exists in the database, you can override this in subclasses. |
||
693 | * |
||
694 | * @return boolean true if this object exists |
||
695 | */ |
||
696 | public function exists() { |
||
699 | |||
700 | /** |
||
701 | * Returns TRUE if all values (other than "ID") are |
||
702 | * considered empty (by weak boolean comparison). |
||
703 | * |
||
704 | * @return boolean |
||
705 | */ |
||
706 | public function isEmpty() { |
||
724 | |||
725 | /** |
||
726 | * Pluralise this item given a specific count. |
||
727 | * |
||
728 | * E.g. "0 Pages", "1 File", "3 Images" |
||
729 | * |
||
730 | * @param string $count |
||
731 | * @param bool $prependNumber Include number in result. Defaults to true. |
||
732 | * @return string |
||
733 | */ |
||
734 | public function i18n_pluralise($count, $prependNumber = true) { |
||
742 | |||
743 | /** |
||
744 | * Get the user friendly singular name of this DataObject. |
||
745 | * If the name is not defined (by redefining $singular_name in the subclass), |
||
746 | * this returns the class name. |
||
747 | * |
||
748 | * @return string User friendly singular name of this DataObject |
||
749 | */ |
||
750 | public function singular_name() { |
||
757 | |||
758 | /** |
||
759 | * Get the translated user friendly singular name of this DataObject |
||
760 | * same as singular_name() but runs it through the translating function |
||
761 | * |
||
762 | * Translating string is in the form: |
||
763 | * $this->class.SINGULARNAME |
||
764 | * Example: |
||
765 | * Page.SINGULARNAME |
||
766 | * |
||
767 | * @return string User friendly translated singular name of this DataObject |
||
768 | */ |
||
769 | public function i18n_singular_name() { |
||
772 | |||
773 | /** |
||
774 | * Get the user friendly plural name of this DataObject |
||
775 | * If the name is not defined (by renaming $plural_name in the subclass), |
||
776 | * this returns a pluralised version of the class name. |
||
777 | * |
||
778 | * @return string User friendly plural name of this DataObject |
||
779 | */ |
||
780 | public function plural_name() { |
||
792 | |||
793 | /** |
||
794 | * Get the translated user friendly plural name of this DataObject |
||
795 | * Same as plural_name but runs it through the translation function |
||
796 | * Translation string is in the form: |
||
797 | * $this->class.PLURALNAME |
||
798 | * Example: |
||
799 | * Page.PLURALNAME |
||
800 | * |
||
801 | * @return string User friendly translated plural name of this DataObject |
||
802 | */ |
||
803 | public function i18n_plural_name() |
||
808 | |||
809 | /** |
||
810 | * Standard implementation of a title/label for a specific |
||
811 | * record. Tries to find properties 'Title' or 'Name', |
||
812 | * and falls back to the 'ID'. Useful to provide |
||
813 | * user-friendly identification of a record, e.g. in errormessages |
||
814 | * or UI-selections. |
||
815 | * |
||
816 | * Overload this method to have a more specialized implementation, |
||
817 | * e.g. for an Address record this could be: |
||
818 | * <code> |
||
819 | * function getTitle() { |
||
820 | * return "{$this->StreetNumber} {$this->StreetName} {$this->City}"; |
||
821 | * } |
||
822 | * </code> |
||
823 | * |
||
824 | * @return string |
||
825 | */ |
||
826 | public function getTitle() { |
||
832 | |||
833 | /** |
||
834 | * Returns the associated database record - in this case, the object itself. |
||
835 | * This is included so that you can call $dataOrController->data() and get a DataObject all the time. |
||
836 | * |
||
837 | * @return DataObject Associated database record |
||
838 | */ |
||
839 | public function data() { |
||
842 | |||
843 | /** |
||
844 | * Convert this object to a map. |
||
845 | * |
||
846 | * @return array The data as a map. |
||
847 | */ |
||
848 | public function toMap() { |
||
852 | |||
853 | /** |
||
854 | * Return all currently fetched database fields. |
||
855 | * |
||
856 | * This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields. |
||
857 | * Obviously, this makes it a lot faster. |
||
858 | * |
||
859 | * @return array The data as a map. |
||
860 | */ |
||
861 | public function getQueriedDatabaseFields() { |
||
864 | |||
865 | /** |
||
866 | * Update a number of fields on this object, given a map of the desired changes. |
||
867 | * |
||
868 | * The field names can be simple names, or you can use a dot syntax to access $has_one relations. |
||
869 | * For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim". |
||
870 | * |
||
871 | * update() doesn't write the main object, but if you use the dot syntax, it will write() |
||
872 | * the related objects that it alters. |
||
873 | * |
||
874 | * @param array $data A map of field name to data values to update. |
||
875 | * @return DataObject $this |
||
876 | */ |
||
877 | public function update($data) { |
||
924 | |||
925 | /** |
||
926 | * Pass changes as a map, and try to |
||
927 | * get automatic casting for these fields. |
||
928 | * Doesn't write to the database. To write the data, |
||
929 | * use the write() method. |
||
930 | * |
||
931 | * @param array $data A map of field name to data values to update. |
||
932 | * @return DataObject $this |
||
933 | */ |
||
934 | public function castedUpdate($data) { |
||
940 | |||
941 | /** |
||
942 | * Merges data and relations from another object of same class, |
||
943 | * without conflict resolution. Allows to specify which |
||
944 | * dataset takes priority in case its not empty. |
||
945 | * has_one-relations are just transferred with priority 'right'. |
||
946 | * has_many and many_many-relations are added regardless of priority. |
||
947 | * |
||
948 | * Caution: has_many/many_many relations are moved rather than duplicated, |
||
949 | * meaning they are not connected to the merged object any longer. |
||
950 | * Caution: Just saves updated has_many/many_many relations to the database, |
||
951 | * doesn't write the updated object itself (just writes the object-properties). |
||
952 | * Caution: Does not delete the merged object. |
||
953 | * Caution: Does now overwrite Created date on the original object. |
||
954 | * |
||
955 | * @param $obj DataObject |
||
956 | * @param $priority String left|right Determines who wins in case of a conflict (optional) |
||
957 | * @param $includeRelations Boolean Merge any existing relations (optional) |
||
958 | * @param $overwriteWithEmpty Boolean Overwrite existing left values with empty right values. |
||
959 | * Only applicable with $priority='right'. (optional) |
||
960 | * @return Boolean |
||
961 | */ |
||
962 | public function merge($rightObj, $priority = 'right', $includeRelations = true, $overwriteWithEmpty = false) { |
||
1035 | |||
1036 | /** |
||
1037 | * Forces the record to think that all its data has changed. |
||
1038 | * Doesn't write to the database. Only sets fields as changed |
||
1039 | * if they are not already marked as changed. |
||
1040 | * |
||
1041 | * @return DataObject $this |
||
1042 | */ |
||
1043 | public function forceChange() { |
||
1063 | |||
1064 | /** |
||
1065 | * Validate the current object. |
||
1066 | * |
||
1067 | * By default, there is no validation - objects are always valid! However, you can overload this method in your |
||
1068 | * DataObject sub-classes to specify custom validation, or use the hook through DataExtension. |
||
1069 | * |
||
1070 | * Invalid objects won't be able to be written - a warning will be thrown and no write will occur. onBeforeWrite() |
||
1071 | * and onAfterWrite() won't get called either. |
||
1072 | * |
||
1073 | * It is expected that you call validate() in your own application to test that an object is valid before |
||
1074 | * attempting a write, and respond appropriately if it isn't. |
||
1075 | * |
||
1076 | * @see {@link ValidationResult} |
||
1077 | * @return ValidationResult |
||
1078 | */ |
||
1079 | public function validate() { |
||
1084 | |||
1085 | /** |
||
1086 | * Public accessor for {@see DataObject::validate()} |
||
1087 | * |
||
1088 | * @return ValidationResult |
||
1089 | */ |
||
1090 | public function doValidate() { |
||
1094 | |||
1095 | /** |
||
1096 | * Event handler called before writing to the database. |
||
1097 | * You can overload this to clean up or otherwise process data before writing it to the |
||
1098 | * database. Don't forget to call parent::onBeforeWrite(), though! |
||
1099 | * |
||
1100 | * This called after {@link $this->validate()}, so you can be sure that your data is valid. |
||
1101 | * |
||
1102 | * @uses DataExtension->onBeforeWrite() |
||
1103 | */ |
||
1104 | protected function onBeforeWrite() { |
||
1110 | |||
1111 | /** |
||
1112 | * Event handler called after writing to the database. |
||
1113 | * You can overload this to act upon changes made to the data after it is written. |
||
1114 | * $this->changed will have a record |
||
1115 | * database. Don't forget to call parent::onAfterWrite(), though! |
||
1116 | * |
||
1117 | * @uses DataExtension->onAfterWrite() |
||
1118 | */ |
||
1119 | protected function onAfterWrite() { |
||
1123 | |||
1124 | /** |
||
1125 | * Event handler called before deleting from the database. |
||
1126 | * You can overload this to clean up or otherwise process data before delete this |
||
1127 | * record. Don't forget to call parent::onBeforeDelete(), though! |
||
1128 | * |
||
1129 | * @uses DataExtension->onBeforeDelete() |
||
1130 | */ |
||
1131 | protected function onBeforeDelete() { |
||
1137 | |||
1138 | protected function onAfterDelete() { |
||
1141 | |||
1142 | /** |
||
1143 | * Load the default values in from the self::$defaults array. |
||
1144 | * Will traverse the defaults of the current class and all its parent classes. |
||
1145 | * Called by the constructor when creating new records. |
||
1146 | * |
||
1147 | * @uses DataExtension->populateDefaults() |
||
1148 | * @return DataObject $this |
||
1149 | */ |
||
1150 | public function populateDefaults() { |
||
1181 | |||
1182 | /** |
||
1183 | * Determine validation of this object prior to write |
||
1184 | * |
||
1185 | * @return ValidationException Exception generated by this write, or null if valid |
||
1186 | */ |
||
1187 | protected function validateWrite() { |
||
1207 | |||
1208 | /** |
||
1209 | * Prepare an object prior to write |
||
1210 | * |
||
1211 | * @throws ValidationException |
||
1212 | */ |
||
1213 | protected function preWrite() { |
||
1229 | |||
1230 | /** |
||
1231 | * Detects and updates all changes made to this object |
||
1232 | * |
||
1233 | * @param bool $forceChanges If set to true, force all fields to be treated as changed |
||
1234 | * @return bool True if any changes are detected |
||
1235 | */ |
||
1236 | protected function updateChanges($forceChanges = false) { |
||
1253 | |||
1254 | /** |
||
1255 | * Writes a subset of changes for a specific table to the given manipulation |
||
1256 | * |
||
1257 | * @param string $baseTable Base table |
||
1258 | * @param string $now Timestamp to use for the current time |
||
1259 | * @param bool $isNewRecord Whether this should be treated as a new record write |
||
1260 | * @param array $manipulation Manipulation to write to |
||
1261 | * @param string $class Table and Class to select and write to |
||
1262 | */ |
||
1263 | protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class) { |
||
1307 | |||
1308 | /** |
||
1309 | * Ensures that a blank base record exists with the basic fixed fields for this dataobject |
||
1310 | * |
||
1311 | * Does nothing if an ID is already assigned for this record |
||
1312 | * |
||
1313 | * @param string $baseTable Base table |
||
1314 | * @param string $now Timestamp to use for the current time |
||
1315 | */ |
||
1316 | protected function writeBaseRecord($baseTable, $now) { |
||
1328 | |||
1329 | /** |
||
1330 | * Generate and write the database manipulation for all changed fields |
||
1331 | * |
||
1332 | * @param string $baseTable Base table |
||
1333 | * @param string $now Timestamp to use for the current time |
||
1334 | * @param bool $isNewRecord If this is a new record |
||
1335 | */ |
||
1336 | protected function writeManipulation($baseTable, $now, $isNewRecord) { |
||
1357 | |||
1358 | /** |
||
1359 | * Writes all changes to this object to the database. |
||
1360 | * - It will insert a record whenever ID isn't set, otherwise update. |
||
1361 | * - All relevant tables will be updated. |
||
1362 | * - $this->onBeforeWrite() gets called beforehand. |
||
1363 | * - Extensions such as Versioned will ammend the database-write to ensure that a version is saved. |
||
1364 | * |
||
1365 | * @uses DataExtension->augmentWrite() |
||
1366 | * |
||
1367 | * @param boolean $showDebug Show debugging information |
||
1368 | * @param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists |
||
1369 | * @param boolean $forceWrite Write to database even if there are no changes |
||
1370 | * @param boolean $writeComponents Call write() on all associated component instances which were previously |
||
1371 | * retrieved through {@link getComponent()}, {@link getComponents()} or |
||
1372 | * {@link getManyManyComponents()} (Default: false) |
||
1373 | * @return int The ID of the record |
||
1374 | * @throws ValidationException Exception that can be caught and handled by the calling function |
||
1375 | */ |
||
1376 | public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) { |
||
1421 | |||
1422 | /** |
||
1423 | * Writes cached relation lists to the database, if possible |
||
1424 | */ |
||
1425 | public function writeRelations() { |
||
1436 | |||
1437 | /** |
||
1438 | * Write the cached components to the database. Cached components could refer to two different instances of the |
||
1439 | * same record. |
||
1440 | * |
||
1441 | * @param $recursive Recursively write components |
||
1442 | * @return DataObject $this |
||
1443 | */ |
||
1444 | public function writeComponents($recursive = false) { |
||
1452 | |||
1453 | /** |
||
1454 | * Delete this data object. |
||
1455 | * $this->onBeforeDelete() gets called. |
||
1456 | * Note that in Versioned objects, both Stage and Live will be deleted. |
||
1457 | * @uses DataExtension->augmentSQL() |
||
1458 | */ |
||
1459 | public function delete() { |
||
1487 | |||
1488 | /** |
||
1489 | * Delete the record with the given ID. |
||
1490 | * |
||
1491 | * @param string $className The class name of the record to be deleted |
||
1492 | * @param int $id ID of record to be deleted |
||
1493 | */ |
||
1494 | public static function delete_by_id($className, $id) { |
||
1502 | |||
1503 | /** |
||
1504 | * Get the class ancestry, including the current class name. |
||
1505 | * The ancestry will be returned as an array of class names, where the 0th element |
||
1506 | * will be the class that inherits directly from DataObject, and the last element |
||
1507 | * will be the current class. |
||
1508 | * |
||
1509 | * @return array Class ancestry |
||
1510 | */ |
||
1511 | public function getClassAncestry() { |
||
1520 | |||
1521 | /** |
||
1522 | * Return a component object from a one to one relationship, as a DataObject. |
||
1523 | * If no component is available, an 'empty component' will be returned for |
||
1524 | * non-polymorphic relations, or for polymorphic relations with a class set. |
||
1525 | * |
||
1526 | * @param string $componentName Name of the component |
||
1527 | * @return DataObject The component object. It's exact type will be that of the component. |
||
1528 | * @throws Exception |
||
1529 | */ |
||
1530 | public function getComponent($componentName) { |
||
1531 | if(isset($this->components[$componentName])) { |
||
1532 | return $this->components[$componentName]; |
||
1533 | } |
||
1534 | |||
1535 | if($class = $this->hasOneComponent($componentName)) { |
||
1536 | $joinField = $componentName . 'ID'; |
||
1537 | $joinID = $this->getField($joinField); |
||
1538 | |||
1539 | // Extract class name for polymorphic relations |
||
1540 | if($class === 'DataObject') { |
||
1541 | $class = $this->getField($componentName . 'Class'); |
||
1542 | if(empty($class)) return null; |
||
1543 | } |
||
1544 | |||
1545 | if($joinID) { |
||
1546 | // Ensure that the selected object originates from the same stage, subsite, etc |
||
1547 | $component = DataObject::get($class) |
||
1548 | ->filter('ID', $joinID) |
||
1549 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
1550 | ->first(); |
||
1551 | } |
||
1552 | |||
1553 | if(empty($component)) { |
||
1554 | $component = $this->model->$class->newObject(); |
||
1555 | } |
||
1556 | } elseif($class = $this->belongsToComponent($componentName)) { |
||
1557 | $joinField = $this->getRemoteJoinField($componentName, 'belongs_to', $polymorphic); |
||
1558 | $joinID = $this->ID; |
||
1559 | |||
1560 | if($joinID) { |
||
1561 | // Prepare filter for appropriate join type |
||
1562 | if($polymorphic) { |
||
1563 | $filter = array( |
||
1564 | "{$joinField}ID" => $joinID, |
||
1565 | "{$joinField}Class" => $this->class |
||
1566 | ); |
||
1567 | } else { |
||
1568 | $filter = array( |
||
1569 | $joinField => $joinID |
||
1570 | ); |
||
1571 | } |
||
1572 | |||
1573 | // Ensure that the selected object originates from the same stage, subsite, etc |
||
1574 | $component = DataObject::get($class) |
||
1575 | ->filter($filter) |
||
1576 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
1577 | ->first(); |
||
1578 | } |
||
1579 | |||
1580 | if(empty($component)) { |
||
1581 | $component = $this->model->$class->newObject(); |
||
1582 | if($polymorphic) { |
||
1583 | $component->{$joinField.'ID'} = $this->ID; |
||
1584 | $component->{$joinField.'Class'} = $this->class; |
||
1585 | } else { |
||
1586 | $component->$joinField = $this->ID; |
||
1587 | } |
||
1588 | } |
||
1589 | } else { |
||
1590 | throw new InvalidArgumentException( |
||
1591 | "DataObject->getComponent(): Could not find component '$componentName'." |
||
1592 | ); |
||
1593 | } |
||
1594 | |||
1595 | $this->components[$componentName] = $component; |
||
1596 | return $component; |
||
1597 | } |
||
1598 | |||
1599 | /** |
||
1600 | * Returns a one-to-many relation as a HasManyList |
||
1601 | * |
||
1602 | * @param string $componentName Name of the component |
||
1603 | * @return HasManyList The components of the one-to-many relationship. |
||
1604 | */ |
||
1605 | public function getComponents($componentName) { |
||
1606 | $result = null; |
||
1607 | |||
1608 | $componentClass = $this->hasManyComponent($componentName); |
||
1609 | if(!$componentClass) { |
||
1610 | throw new InvalidArgumentException(sprintf( |
||
1611 | "DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'", |
||
1612 | $componentName, |
||
1613 | $this->class |
||
1614 | )); |
||
1615 | } |
||
1616 | |||
1617 | // If we haven't been written yet, we can't save these relations, so use a list that handles this case |
||
1618 | if(!$this->ID) { |
||
1619 | if(!isset($this->unsavedRelations[$componentName])) { |
||
1620 | $this->unsavedRelations[$componentName] = |
||
1621 | new UnsavedRelationList($this->class, $componentName, $componentClass); |
||
1622 | } |
||
1623 | return $this->unsavedRelations[$componentName]; |
||
1624 | } |
||
1625 | |||
1626 | // Determine type and nature of foreign relation |
||
1627 | $joinField = $this->getRemoteJoinField($componentName, 'has_many', $polymorphic); |
||
1628 | /** @var HasManyList $result */ |
||
1629 | if($polymorphic) { |
||
1630 | $result = PolymorphicHasManyList::create($componentClass, $joinField, $this->class); |
||
1631 | } else { |
||
1632 | $result = HasManyList::create($componentClass, $joinField); |
||
1633 | } |
||
1634 | |||
1635 | if($this->model) { |
||
1636 | $result->setDataModel($this->model); |
||
1637 | } |
||
1638 | |||
1639 | return $result |
||
1640 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
1641 | ->forForeignID($this->ID); |
||
1642 | } |
||
1643 | |||
1644 | /** |
||
1645 | * Find the foreign class of a relation on this DataObject, regardless of the relation type. |
||
1646 | * |
||
1647 | * @param string $relationName Relation name. |
||
1648 | * @return string Class name, or null if not found. |
||
1649 | */ |
||
1650 | public function getRelationClass($relationName) { |
||
1651 | // Go through all relationship configuration fields. |
||
1652 | $candidates = array_merge( |
||
1653 | ($relations = Config::inst()->get($this->class, 'has_one')) ? $relations : array(), |
||
1654 | ($relations = Config::inst()->get($this->class, 'has_many')) ? $relations : array(), |
||
1655 | ($relations = Config::inst()->get($this->class, 'many_many')) ? $relations : array(), |
||
1656 | ($relations = Config::inst()->get($this->class, 'belongs_many_many')) ? $relations : array(), |
||
1657 | ($relations = Config::inst()->get($this->class, 'belongs_to')) ? $relations : array() |
||
1658 | ); |
||
1659 | |||
1660 | if (isset($candidates[$relationName])) { |
||
1661 | $remoteClass = $candidates[$relationName]; |
||
1662 | |||
1663 | // If dot notation is present, extract just the first part that contains the class. |
||
1664 | if(($fieldPos = strpos($remoteClass, '.'))!==false) { |
||
1665 | return substr($remoteClass, 0, $fieldPos); |
||
1666 | } |
||
1667 | |||
1668 | // Otherwise just return the class |
||
1669 | return $remoteClass; |
||
1670 | } |
||
1671 | |||
1672 | return null; |
||
1673 | } |
||
1674 | |||
1675 | /** |
||
1676 | * Given a relation name, determine the relation type |
||
1677 | * |
||
1678 | * @param string $component Name of component |
||
1679 | * @return string has_one, has_many, many_many, belongs_many_many or belongs_to |
||
1680 | */ |
||
1681 | public function getRelationType($component) { |
||
1691 | |||
1692 | /** |
||
1693 | * Given a relation declared on a remote class, generate a substitute component for the opposite |
||
1694 | * side of the relation. |
||
1695 | * |
||
1696 | * Notes on behaviour: |
||
1697 | * - This can still be used on components that are defined on both sides, but do not need to be. |
||
1698 | * - All has_ones on remote class will be treated as local has_many, even if they are belongs_to |
||
1699 | * - Cannot be used on polymorphic relationships |
||
1700 | * - Cannot be used on unsaved objects. |
||
1701 | * |
||
1702 | * @param string $remoteClass |
||
1703 | * @param string $remoteRelation |
||
1704 | * @return DataList|DataObject The component, either as a list or single object |
||
1705 | * @throws BadMethodCallException |
||
1706 | * @throws InvalidArgumentException |
||
1707 | */ |
||
1708 | public function inferReciprocalComponent($remoteClass, $remoteRelation) { |
||
1805 | |||
1806 | /** |
||
1807 | * Tries to find the database key on another object that is used to store a |
||
1808 | * relationship to this class. If no join field can be found it defaults to 'ParentID'. |
||
1809 | * |
||
1810 | * If the remote field is polymorphic then $polymorphic is set to true, and the return value |
||
1811 | * is in the form 'Relation' instead of 'RelationID', referencing the composite DBField. |
||
1812 | * |
||
1813 | * @param string $component Name of the relation on the current object pointing to the |
||
1814 | * remote object. |
||
1815 | * @param string $type the join type - either 'has_many' or 'belongs_to' |
||
1816 | * @param boolean $polymorphic Flag set to true if the remote join field is polymorphic. |
||
1817 | * @return string |
||
1818 | * @throws Exception |
||
1819 | */ |
||
1820 | public function getRemoteJoinField($component, $type = 'has_many', &$polymorphic = false) { |
||
1888 | |||
1889 | /** |
||
1890 | * Returns a many-to-many component, as a ManyManyList. |
||
1891 | * @param string $componentName Name of the many-many component |
||
1892 | * @return ManyManyList The set of components |
||
1893 | */ |
||
1894 | public function getManyManyComponents($componentName) { |
||
1895 | $manyManyComponent = $this->manyManyComponent($componentName); |
||
1896 | if(!$manyManyComponent) { |
||
1897 | throw new InvalidArgumentException(sprintf( |
||
1898 | "DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'", |
||
1899 | $componentName, |
||
1900 | $this->class |
||
1901 | )); |
||
1902 | } |
||
1903 | |||
1904 | list($parentClass, $componentClass, $parentField, $componentField, $table) = $manyManyComponent; |
||
1905 | |||
1906 | // If we haven't been written yet, we can't save these relations, so use a list that handles this case |
||
1907 | if(!$this->ID) { |
||
1908 | if(!isset($this->unsavedRelations[$componentName])) { |
||
1909 | $this->unsavedRelations[$componentName] = |
||
1910 | new UnsavedRelationList($parentClass, $componentName, $componentClass); |
||
1911 | } |
||
1912 | return $this->unsavedRelations[$componentName]; |
||
1913 | } |
||
1914 | |||
1915 | $extraFields = $this->manyManyExtraFieldsForComponent($componentName) ?: array(); |
||
1916 | /** @var ManyManyList $result */ |
||
1917 | $result = ManyManyList::create($componentClass, $table, $componentField, $parentField, $extraFields); |
||
1918 | if($this->model) { |
||
1919 | $result->setDataModel($this->model); |
||
1920 | } |
||
1921 | |||
1922 | $this->extend('updateManyManyComponents', $result); |
||
1923 | |||
1924 | // If this is called on a singleton, then we return an 'orphaned relation' that can have the |
||
1925 | // foreignID set elsewhere. |
||
1926 | return $result |
||
1927 | ->setDataQueryParam($this->getInheritableQueryParams()) |
||
1928 | ->forForeignID($this->ID); |
||
1929 | } |
||
1930 | |||
1931 | /** |
||
1932 | * Return the class of a one-to-one component. If $component is null, return all of the one-to-one components and |
||
1933 | * their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type. |
||
1934 | * |
||
1935 | * @return string|array The class of the one-to-one component, or an array of all one-to-one components and |
||
1936 | * their classes. |
||
1937 | */ |
||
1938 | public function hasOne() { |
||
1941 | |||
1942 | /** |
||
1943 | * Return data for a specific has_one component. |
||
1944 | * @param string $component |
||
1945 | * @return string|null |
||
1946 | */ |
||
1947 | public function hasOneComponent($component) { |
||
1948 | $classes = ClassInfo::ancestry($this, true); |
||
1949 | |||
1950 | foreach(array_reverse($classes) as $class) { |
||
1951 | $hasOnes = Config::inst()->get($class, 'has_one', Config::UNINHERITED); |
||
1952 | if(isset($hasOnes[$component])) { |
||
1953 | return $hasOnes[$component]; |
||
1954 | } |
||
1955 | } |
||
1956 | } |
||
1957 | |||
1958 | /** |
||
1959 | * Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and |
||
1960 | * their class name will be returned. |
||
1961 | * |
||
1962 | * @param string $component - Name of component |
||
1963 | * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have |
||
1964 | * the field data stripped off. It defaults to TRUE. |
||
1965 | * @return string|array |
||
1966 | */ |
||
1967 | public function belongsTo($component = null, $classOnly = true) { |
||
1968 | if($component) { |
||
1969 | Deprecation::notice( |
||
1970 | '4.0', |
||
1971 | 'Please use DataObject::belongsToComponent() instead of passing a component name to belongsTo()', |
||
1972 | Deprecation::SCOPE_GLOBAL |
||
1973 | ); |
||
1974 | return $this->belongsToComponent($component, $classOnly); |
||
1975 | } |
||
1976 | |||
1977 | $belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED); |
||
1978 | if($belongsTo && $classOnly) { |
||
1979 | return preg_replace('/(.+)?\..+/', '$1', $belongsTo); |
||
1980 | } else { |
||
1981 | return $belongsTo ? $belongsTo : array(); |
||
1982 | } |
||
1983 | } |
||
1984 | |||
1985 | /** |
||
1986 | * Return data for a specific belongs_to component. |
||
1987 | * @param string $component |
||
1988 | * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have |
||
1989 | * the field data stripped off. It defaults to TRUE. |
||
1990 | * @return string|null |
||
1991 | */ |
||
1992 | public function belongsToComponent($component, $classOnly = true) { |
||
1993 | $belongsTo = (array)Config::inst()->get($this->class, 'belongs_to', Config::INHERITED); |
||
1994 | |||
1995 | if($belongsTo && array_key_exists($component, $belongsTo)) { |
||
1996 | $belongsTo = $belongsTo[$component]; |
||
1997 | } else { |
||
1998 | return null; |
||
1999 | } |
||
2000 | |||
2001 | return ($classOnly) ? preg_replace('/(.+)?\..+/', '$1', $belongsTo) : $belongsTo; |
||
2002 | } |
||
2003 | |||
2004 | /** |
||
2005 | * Return all of the database fields in this object |
||
2006 | * |
||
2007 | * @param string $fieldName Limit the output to a specific field name |
||
2008 | * @param string $includeTable If returning a single column, prefix the column with the table name |
||
2009 | * in Table.Column(spec) format |
||
2010 | * @return array|string|null The database fields, or if searching a single field, just this one field if found |
||
2011 | * Field will be a string in ClassName(args) format, or Table.ClassName(args) format if $includeTable is true |
||
2012 | */ |
||
2013 | public function db($fieldName = null, $includeTable = false) { |
||
2014 | $classes = ClassInfo::ancestry($this, true); |
||
2015 | |||
2016 | // If we're looking for a specific field, we want to hit subclasses first as they may override field types |
||
2017 | if($fieldName) { |
||
2018 | $classes = array_reverse($classes); |
||
2019 | } |
||
2020 | |||
2021 | $db = array(); |
||
2022 | foreach($classes as $class) { |
||
2023 | // Merge fields with new fields and composite fields |
||
2024 | $fields = self::database_fields($class); |
||
2025 | $compositeFields = self::composite_fields($class, false); |
||
2026 | $db = array_merge($db, $fields, $compositeFields); |
||
2027 | |||
2028 | // Check for search field |
||
2029 | if($fieldName && isset($db[$fieldName])) { |
||
2030 | // Return found field |
||
2031 | if(!$includeTable) { |
||
2032 | return $db[$fieldName]; |
||
2033 | } |
||
2034 | |||
2035 | // Set table for the given field |
||
2036 | if(in_array($fieldName, $this->config()->fixed_fields)) { |
||
2037 | $table = $this->baseTable(); |
||
2038 | } else { |
||
2039 | $table = $class; |
||
2040 | } |
||
2041 | return $table . "." . $db[$fieldName]; |
||
2042 | } |
||
2043 | } |
||
2044 | |||
2045 | // At end of search complete |
||
2046 | if($fieldName) { |
||
2047 | return null; |
||
2048 | } else { |
||
2049 | return $db; |
||
2050 | } |
||
2051 | } |
||
2052 | |||
2053 | /** |
||
2054 | * Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many |
||
2055 | * relationships and their classes will be returned. |
||
2056 | * |
||
2057 | * @param string $component Deprecated - Name of component |
||
2058 | * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have |
||
2059 | * the field data stripped off. It defaults to TRUE. |
||
2060 | * @return string|array|false |
||
2061 | */ |
||
2062 | public function hasMany($component = null, $classOnly = true) { |
||
2079 | |||
2080 | /** |
||
2081 | * Return data for a specific has_many component. |
||
2082 | * @param string $component |
||
2083 | * @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have |
||
2084 | * the field data stripped off. It defaults to TRUE. |
||
2085 | * @return string|null |
||
2086 | */ |
||
2087 | public function hasManyComponent($component, $classOnly = true) { |
||
2098 | |||
2099 | /** |
||
2100 | * Return the many-to-many extra fields specification. |
||
2101 | * |
||
2102 | * If you don't specify a component name, it returns all |
||
2103 | * extra fields for all components available. |
||
2104 | * |
||
2105 | * @return array|null |
||
2106 | */ |
||
2107 | public function manyManyExtraFields() { |
||
2108 | return Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED); |
||
2109 | } |
||
2110 | |||
2111 | /** |
||
2112 | * Return the many-to-many extra fields specification for a specific component. |
||
2113 | * @param string $component |
||
2114 | * @return array|null |
||
2115 | */ |
||
2116 | public function manyManyExtraFieldsForComponent($component) { |
||
2117 | // Get all many_many_extraFields defined in this class or parent classes |
||
2118 | $extraFields = (array)Config::inst()->get($this->class, 'many_many_extraFields', Config::INHERITED); |
||
2119 | // Extra fields are immediately available |
||
2120 | if(isset($extraFields[$component])) { |
||
2121 | return $extraFields[$component]; |
||
2122 | } |
||
2123 | |||
2124 | // Check this class' belongs_many_manys to see if any of their reverse associations contain extra fields |
||
2125 | $manyMany = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED); |
||
2126 | $candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null; |
||
2127 | if($candidate) { |
||
2128 | $relationName = null; |
||
2129 | // Extract class and relation name from dot-notation |
||
2130 | if(strpos($candidate, '.') !== false) { |
||
2131 | list($candidate, $relationName) = explode('.', $candidate, 2); |
||
2132 | } |
||
2133 | |||
2134 | // If we've not already found the relation name from dot notation, we need to find a relation that points |
||
2135 | // back to this class. As there's no dot-notation, there can only be one relation pointing to this class, |
||
2136 | // so it's safe to assume that it's the correct one |
||
2137 | if(!$relationName) { |
||
2138 | $candidateManyManys = (array)Config::inst()->get($candidate, 'many_many', Config::UNINHERITED); |
||
2139 | |||
2140 | foreach($candidateManyManys as $relation => $relatedClass) { |
||
2141 | if (is_a($this, $relatedClass)) { |
||
2142 | $relationName = $relation; |
||
2143 | } |
||
2144 | } |
||
2145 | } |
||
2146 | |||
2147 | // If we've found a matching relation on the target class, see if we can find extra fields for it |
||
2148 | $extraFields = (array)Config::inst()->get($candidate, 'many_many_extraFields', Config::UNINHERITED); |
||
2149 | if(isset($extraFields[$relationName])) { |
||
2150 | return $extraFields[$relationName]; |
||
2151 | } |
||
2152 | } |
||
2153 | |||
2154 | return isset($items) ? $items : null; |
||
2155 | } |
||
2156 | |||
2157 | /** |
||
2158 | * Return information about a many-to-many component. |
||
2159 | * The return value is an array of (parentclass, childclass). If $component is null, then all many-many |
||
2160 | * components are returned. |
||
2161 | * |
||
2162 | * @see DataObject::manyManyComponent() |
||
2163 | * @return array|null An array of (parentclass, childclass), or an array of all many-many components |
||
2164 | */ |
||
2165 | public function manyMany() { |
||
2166 | $manyManys = (array)Config::inst()->get($this->class, 'many_many', Config::INHERITED); |
||
2167 | $belongsManyManys = (array)Config::inst()->get($this->class, 'belongs_many_many', Config::INHERITED); |
||
2168 | $items = array_merge($manyManys, $belongsManyManys); |
||
2169 | return $items; |
||
2170 | } |
||
2171 | |||
2172 | /** |
||
2173 | * Return information about a specific many_many component. Returns a numeric array of: |
||
2174 | * array( |
||
2175 | * <classname>, The class that relation is defined in e.g. "Product" |
||
2176 | * <candidateName>, The target class of the relation e.g. "Category" |
||
2177 | * <parentField>, The field name pointing to <classname>'s table e.g. "ProductID" |
||
2178 | * <childField>, The field name pointing to <candidatename>'s table e.g. "CategoryID" |
||
2179 | * <joinTable> The join table between the two classes e.g. "Product_Categories" |
||
2180 | * ) |
||
2181 | * @param string $component The component name |
||
2182 | * @return array|null |
||
2183 | */ |
||
2184 | public function manyManyComponent($component) { |
||
2185 | $classes = $this->getClassAncestry(); |
||
2186 | foreach($classes as $class) { |
||
2187 | $manyMany = Config::inst()->get($class, 'many_many', Config::UNINHERITED); |
||
2188 | // Check if the component is defined in many_many on this class |
||
2189 | $candidate = (isset($manyMany[$component])) ? $manyMany[$component] : null; |
||
2190 | if($candidate) { |
||
2191 | $parentField = $class . "ID"; |
||
2192 | $childField = ($class == $candidate) ? "ChildID" : $candidate . "ID"; |
||
2193 | return array($class, $candidate, $parentField, $childField, "{$class}_$component"); |
||
2194 | } |
||
2195 | |||
2196 | // Check if the component is defined in belongs_many_many on this class |
||
2197 | $belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED); |
||
2198 | $candidate = (isset($belongsManyMany[$component])) ? $belongsManyMany[$component] : null; |
||
2199 | if($candidate) { |
||
2200 | // Extract class and relation name from dot-notation |
||
2201 | if(strpos($candidate, '.') !== false) { |
||
2202 | list($candidate, $relationName) = explode('.', $candidate, 2); |
||
2203 | } |
||
2204 | |||
2205 | $childField = $candidate . "ID"; |
||
2206 | |||
2207 | // We need to find the inverse component name |
||
2208 | $otherManyMany = Config::inst()->get($candidate, 'many_many', Config::UNINHERITED); |
||
2209 | if(!$otherManyMany) { |
||
2210 | throw new LogicException("Inverse component of $candidate not found ({$this->class})"); |
||
2211 | } |
||
2212 | |||
2213 | // If we've got a relation name (extracted from dot-notation), we can already work out |
||
2214 | // the join table and candidate class name... |
||
2215 | if(isset($relationName) && isset($otherManyMany[$relationName])) { |
||
2216 | $candidateClass = $otherManyMany[$relationName]; |
||
2217 | $joinTable = "{$candidate}_{$relationName}"; |
||
2218 | } else { |
||
2219 | // ... otherwise, we need to loop over the many_manys and find a relation that |
||
2220 | // matches up to this class |
||
2221 | foreach($otherManyMany as $inverseComponentName => $candidateClass) { |
||
2222 | if($candidateClass == $class || is_subclass_of($class, $candidateClass)) { |
||
2223 | $joinTable = "{$candidate}_{$inverseComponentName}"; |
||
2224 | break; |
||
2225 | } |
||
2226 | } |
||
2227 | } |
||
2228 | |||
2229 | // If we could work out the join table, we've got all the info we need |
||
2230 | if(isset($joinTable)) { |
||
2231 | $parentField = ($class == $candidate) ? "ChildID" : $candidateClass . "ID"; |
||
2232 | return array($class, $candidate, $parentField, $childField, $joinTable); |
||
2233 | } |
||
2234 | |||
2235 | throw new LogicException("Orphaned \$belongs_many_many value for $this->class.$component"); |
||
2236 | } |
||
2237 | } |
||
2238 | } |
||
2239 | |||
2240 | /** |
||
2241 | * This returns an array (if it exists) describing the database extensions that are required, or false if none |
||
2242 | * |
||
2243 | * This is experimental, and is currently only a Postgres-specific enhancement. |
||
2244 | * |
||
2245 | * @return array or false |
||
2246 | */ |
||
2247 | public function database_extensions($class){ |
||
2255 | |||
2256 | /** |
||
2257 | * Generates a SearchContext to be used for building and processing |
||
2258 | * a generic search form for properties on this object. |
||
2259 | * |
||
2260 | * @return SearchContext |
||
2261 | */ |
||
2262 | public function getDefaultSearchContext() { |
||
2269 | |||
2270 | /** |
||
2271 | * Determine which properties on the DataObject are |
||
2272 | * searchable, and map them to their default {@link FormField} |
||
2273 | * representations. Used for scaffolding a searchform for {@link ModelAdmin}. |
||
2274 | * |
||
2275 | * Some additional logic is included for switching field labels, based on |
||
2276 | * how generic or specific the field type is. |
||
2277 | * |
||
2278 | * Used by {@link SearchContext}. |
||
2279 | * |
||
2280 | * @param array $_params |
||
2281 | * 'fieldClasses': Associative array of field names as keys and FormField classes as values |
||
2282 | * 'restrictFields': Numeric array of a field name whitelist |
||
2283 | * @return FieldList |
||
2284 | */ |
||
2285 | public function scaffoldSearchFields($_params = null) { |
||
2286 | $params = array_merge( |
||
2287 | array( |
||
2288 | 'fieldClasses' => false, |
||
2289 | 'restrictFields' => false |
||
2290 | ), |
||
2291 | (array)$_params |
||
2292 | ); |
||
2293 | $fields = new FieldList(); |
||
2294 | foreach($this->searchableFields() as $fieldName => $spec) { |
||
2295 | if($params['restrictFields'] && !in_array($fieldName, $params['restrictFields'])) continue; |
||
2296 | |||
2297 | // If a custom fieldclass is provided as a string, use it |
||
2298 | if($params['fieldClasses'] && isset($params['fieldClasses'][$fieldName])) { |
||
2299 | $fieldClass = $params['fieldClasses'][$fieldName]; |
||
2300 | $field = new $fieldClass($fieldName); |
||
2301 | // If we explicitly set a field, then construct that |
||
2302 | } else if(isset($spec['field'])) { |
||
2303 | // If it's a string, use it as a class name and construct |
||
2304 | if(is_string($spec['field'])) { |
||
2305 | $fieldClass = $spec['field']; |
||
2306 | $field = new $fieldClass($fieldName); |
||
2307 | |||
2308 | // If it's a FormField object, then just use that object directly. |
||
2309 | } else if($spec['field'] instanceof FormField) { |
||
2310 | $field = $spec['field']; |
||
2311 | |||
2312 | // Otherwise we have a bug |
||
2313 | } else { |
||
2314 | user_error("Bad value for searchable_fields, 'field' value: " |
||
2315 | . var_export($spec['field'], true), E_USER_WARNING); |
||
2316 | } |
||
2317 | |||
2318 | // Otherwise, use the database field's scaffolder |
||
2319 | } else { |
||
2320 | $field = $this->relObject($fieldName)->scaffoldSearchField(); |
||
2321 | } |
||
2322 | |||
2323 | // Allow fields to opt out of search |
||
2324 | if(!$field) { |
||
2325 | continue; |
||
2326 | } |
||
2327 | |||
2328 | if (strstr($fieldName, '.')) { |
||
2329 | $field->setName(str_replace('.', '__', $fieldName)); |
||
2330 | } |
||
2331 | $field->setTitle($spec['title']); |
||
2332 | |||
2333 | $fields->push($field); |
||
2334 | } |
||
2335 | return $fields; |
||
2336 | } |
||
2337 | |||
2338 | /** |
||
2339 | * Scaffold a simple edit form for all properties on this dataobject, |
||
2340 | * based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}. |
||
2341 | * Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}. |
||
2342 | * |
||
2343 | * @uses FormScaffolder |
||
2344 | * |
||
2345 | * @param array $_params Associative array passing through properties to {@link FormScaffolder}. |
||
2346 | * @return FieldList |
||
2347 | */ |
||
2348 | public function scaffoldFormFields($_params = null) { |
||
2369 | |||
2370 | /** |
||
2371 | * Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields |
||
2372 | * being called on extensions |
||
2373 | * |
||
2374 | * @param callable $callback The callback to execute |
||
2375 | */ |
||
2376 | protected function beforeUpdateCMSFields($callback) { |
||
2379 | |||
2380 | /** |
||
2381 | * Centerpiece of every data administration interface in Silverstripe, |
||
2382 | * which returns a {@link FieldList} suitable for a {@link Form} object. |
||
2383 | * If not overloaded, we're using {@link scaffoldFormFields()} to automatically |
||
2384 | * generate this set. To customize, overload this method in a subclass |
||
2385 | * or extended onto it by using {@link DataExtension->updateCMSFields()}. |
||
2386 | * |
||
2387 | * <code> |
||
2388 | * class MyCustomClass extends DataObject { |
||
2389 | * static $db = array('CustomProperty'=>'Boolean'); |
||
2390 | * |
||
2391 | * function getCMSFields() { |
||
2392 | * $fields = parent::getCMSFields(); |
||
2393 | * $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty')); |
||
2394 | * return $fields; |
||
2395 | * } |
||
2396 | * } |
||
2397 | * </code> |
||
2398 | * |
||
2399 | * @see Good example of complex FormField building: SiteTree::getCMSFields() |
||
2400 | * |
||
2401 | * @return FieldList Returns a TabSet for usage within the CMS - don't use for frontend forms. |
||
2402 | */ |
||
2403 | public function getCMSFields() { |
||
2415 | |||
2416 | /** |
||
2417 | * need to be overload by solid dataobject, so that the customised actions of that dataobject, |
||
2418 | * including that dataobject's extensions customised actions could be added to the EditForm. |
||
2419 | * |
||
2420 | * @return an Empty FieldList(); need to be overload by solid subclass |
||
2421 | */ |
||
2422 | public function getCMSActions() { |
||
2427 | |||
2428 | |||
2429 | /** |
||
2430 | * Used for simple frontend forms without relation editing |
||
2431 | * or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()} |
||
2432 | * by default. To customize, either overload this method in your |
||
2433 | * subclass, or extend it by {@link DataExtension->updateFrontEndFields()}. |
||
2434 | * |
||
2435 | * @todo Decide on naming for "website|frontend|site|page" and stick with it in the API |
||
2436 | * |
||
2437 | * @param array $params See {@link scaffoldFormFields()} |
||
2438 | * @return FieldList Always returns a simple field collection without TabSet. |
||
2439 | */ |
||
2440 | public function getFrontEndFields($params = null) { |
||
2446 | |||
2447 | /** |
||
2448 | * Gets the value of a field. |
||
2449 | * Called by {@link __get()} and any getFieldName() methods you might create. |
||
2450 | * |
||
2451 | * @param string $field The name of the field |
||
2452 | * |
||
2453 | * @return mixed The field value |
||
2454 | */ |
||
2455 | public function getField($field) { |
||
2474 | |||
2475 | /** |
||
2476 | * Loads all the stub fields that an initial lazy load didn't load fully. |
||
2477 | * |
||
2478 | * @param string $tableClass Base table to load the values from. Others are joined as required. |
||
2479 | * Not specifying a tableClass will load all lazy fields from all tables. |
||
2480 | */ |
||
2481 | protected function loadLazyFields($tableClass = null) { |
||
2555 | |||
2556 | /** |
||
2557 | * Return the fields that have changed. |
||
2558 | * |
||
2559 | * The change level affects what the functions defines as "changed": |
||
2560 | * - Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones. |
||
2561 | * - Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes, |
||
2562 | * for example a change from 0 to null would not be included. |
||
2563 | * |
||
2564 | * Example return: |
||
2565 | * <code> |
||
2566 | * array( |
||
2567 | * 'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE) |
||
2568 | * ) |
||
2569 | * </code> |
||
2570 | * |
||
2571 | * @param boolean|array $databaseFieldsOnly Filter to determine which fields to return. Set to true |
||
2572 | * to return all database fields, or an array for an explicit filter. false returns all fields. |
||
2573 | * @param int $changeLevel The strictness of what is defined as change. Defaults to strict |
||
2574 | * @return array |
||
2575 | */ |
||
2576 | public function getChangedFields($databaseFieldsOnly = false, $changeLevel = self::CHANGE_STRICT) { |
||
2617 | |||
2618 | /** |
||
2619 | * Uses {@link getChangedFields()} to determine if fields have been changed |
||
2620 | * since loading them from the database. |
||
2621 | * |
||
2622 | * @param string $fieldName Name of the database field to check, will check for any if not given |
||
2623 | * @param int $changeLevel See {@link getChangedFields()} |
||
2624 | * @return boolean |
||
2625 | */ |
||
2626 | public function isChanged($fieldName = null, $changeLevel = self::CHANGE_STRICT) { |
||
2636 | |||
2637 | /** |
||
2638 | * Set the value of the field |
||
2639 | * Called by {@link __set()} and any setFieldName() methods you might create. |
||
2640 | * |
||
2641 | * @param string $fieldName Name of the field |
||
2642 | * @param mixed $val New field value |
||
2643 | * @return DataObject $this |
||
2644 | */ |
||
2645 | public function setField($fieldName, $val) { |
||
2695 | |||
2696 | /** |
||
2697 | * Set the value of the field, using a casting object. |
||
2698 | * This is useful when you aren't sure that a date is in SQL format, for example. |
||
2699 | * setCastedField() can also be used, by forms, to set related data. For example, uploaded images |
||
2700 | * can be saved into the Image table. |
||
2701 | * |
||
2702 | * @param string $fieldName Name of the field |
||
2703 | * @param mixed $value New field value |
||
2704 | * @return $this |
||
2705 | */ |
||
2706 | public function setCastedField($fieldName, $value) { |
||
2719 | |||
2720 | public function castingHelper($field) { |
||
2727 | |||
2728 | /** |
||
2729 | * Returns true if the given field exists in a database column on any of |
||
2730 | * the objects tables and optionally look up a dynamic getter with |
||
2731 | * get<fieldName>(). |
||
2732 | * |
||
2733 | * @param string $field Name of the field |
||
2734 | * @return boolean True if the given field exists |
||
2735 | */ |
||
2736 | public function hasField($field) { |
||
2744 | |||
2745 | /** |
||
2746 | * Returns true if the given field exists as a database column |
||
2747 | * |
||
2748 | * @param string $field Name of the field |
||
2749 | * |
||
2750 | * @return boolean |
||
2751 | */ |
||
2752 | public function hasDatabaseField($field) { |
||
2756 | |||
2757 | /** |
||
2758 | * Returns the field type of the given field, if it belongs to this class, and not a parent. |
||
2759 | * Note that the field type will not include constructor arguments in round brackets, only the classname. |
||
2760 | * |
||
2761 | * @param string $field Name of the field |
||
2762 | * @return string The field type of the given field |
||
2763 | */ |
||
2764 | public function hasOwnTableDatabaseField($field) { |
||
2767 | |||
2768 | /** |
||
2769 | * Returns the field type of the given field, if it belongs to this class, and not a parent. |
||
2770 | * Note that the field type will not include constructor arguments in round brackets, only the classname. |
||
2771 | * |
||
2772 | * @param string $class Class name to check |
||
2773 | * @param string $field Name of the field |
||
2774 | * @return string The field type of the given field |
||
2775 | */ |
||
2776 | public static function has_own_table_database_field($class, $field) { |
||
2786 | |||
2787 | /** |
||
2788 | * Returns true if given class has its own table. Uses the rules for whether the table should exist rather than |
||
2789 | * actually looking in the database. |
||
2790 | * |
||
2791 | * @param string $dataClass |
||
2792 | * @return bool |
||
2793 | */ |
||
2794 | public static function has_own_table($dataClass) { |
||
2809 | |||
2810 | /** |
||
2811 | * Returns true if the member is allowed to do the given action. |
||
2812 | * See {@link extendedCan()} for a more versatile tri-state permission control. |
||
2813 | * |
||
2814 | * @param string $perm The permission to be checked, such as 'View'. |
||
2815 | * @param Member $member The member whose permissions need checking. Defaults to the currently logged |
||
2816 | * in user. |
||
2817 | * @param array $context Additional $context to pass to extendedCan() |
||
2818 | * |
||
2819 | * @return boolean True if the the member is allowed to do the given action |
||
2820 | */ |
||
2821 | public function can($perm, $member = null, $context = array()) { |
||
2880 | |||
2881 | /** |
||
2882 | * Process tri-state responses from permission-alterting extensions. The extensions are |
||
2883 | * expected to return one of three values: |
||
2884 | * |
||
2885 | * - false: Disallow this permission, regardless of what other extensions say |
||
2886 | * - true: Allow this permission, as long as no other extensions return false |
||
2887 | * - NULL: Don't affect the outcome |
||
2888 | * |
||
2889 | * This method itself returns a tri-state value, and is designed to be used like this: |
||
2890 | * |
||
2891 | * <code> |
||
2892 | * $extended = $this->extendedCan('canDoSomething', $member); |
||
2893 | * if($extended !== null) return $extended; |
||
2894 | * else return $normalValue; |
||
2895 | * </code> |
||
2896 | * |
||
2897 | * @param string $methodName Method on the same object, e.g. {@link canEdit()} |
||
2898 | * @param Member|int $member |
||
2899 | * @param array $context Optional context |
||
2900 | * @return boolean|null |
||
2901 | */ |
||
2902 | public function extendedCan($methodName, $member, $context = array()) { |
||
2913 | |||
2914 | /** |
||
2915 | * @param Member $member |
||
2916 | * @return boolean |
||
2917 | */ |
||
2918 | public function canView($member = null) { |
||
2925 | |||
2926 | /** |
||
2927 | * @param Member $member |
||
2928 | * @return boolean |
||
2929 | */ |
||
2930 | public function canEdit($member = null) { |
||
2937 | |||
2938 | /** |
||
2939 | * @param Member $member |
||
2940 | * @return boolean |
||
2941 | */ |
||
2942 | public function canDelete($member = null) { |
||
2949 | |||
2950 | /** |
||
2951 | * @param Member $member |
||
2952 | * @param array $context Additional context-specific data which might |
||
2953 | * affect whether (or where) this object could be created. |
||
2954 | * @return boolean |
||
2955 | */ |
||
2956 | public function canCreate($member = null, $context = array()) { |
||
2963 | |||
2964 | /** |
||
2965 | * Debugging used by Debug::show() |
||
2966 | * |
||
2967 | * @return string HTML data representing this object |
||
2968 | */ |
||
2969 | public function debug() { |
||
2977 | |||
2978 | /** |
||
2979 | * Return the DBField object that represents the given field. |
||
2980 | * This works similarly to obj() with 2 key differences: |
||
2981 | * - it still returns an object even when the field has no value. |
||
2982 | * - it only matches fields and not methods |
||
2983 | * - it matches foreign keys generated by has_one relationships, eg, "ParentID" |
||
2984 | * |
||
2985 | * @param string $fieldName Name of the field |
||
2986 | * @return DBField The field as a DBField object |
||
2987 | */ |
||
2988 | public function dbObject($fieldName) { |
||
3008 | |||
3009 | /** |
||
3010 | * Traverses to a DBField referenced by relationships between data objects. |
||
3011 | * |
||
3012 | * The path to the related field is specified with dot separated syntax |
||
3013 | * (eg: Parent.Child.Child.FieldName). |
||
3014 | * |
||
3015 | * @param string $fieldPath |
||
3016 | * |
||
3017 | * @return mixed DBField of the field on the object or a DataList instance. |
||
3018 | */ |
||
3019 | public function relObject($fieldPath) { |
||
3049 | |||
3050 | /** |
||
3051 | * Traverses to a field referenced by relationships between data objects, returning the value |
||
3052 | * The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName) |
||
3053 | * |
||
3054 | * @param $fieldName string |
||
3055 | * @return string | null - will return null on a missing value |
||
3056 | */ |
||
3057 | public function relField($fieldName) { |
||
3092 | |||
3093 | /** |
||
3094 | * Temporary hack to return an association name, based on class, to get around the mangle |
||
3095 | * of having to deal with reverse lookup of relationships to determine autogenerated foreign keys. |
||
3096 | * |
||
3097 | * @return String |
||
3098 | */ |
||
3099 | public function getReverseAssociation($className) { |
||
3115 | |||
3116 | /** |
||
3117 | * Return all objects matching the filter |
||
3118 | * sub-classes are automatically selected and included |
||
3119 | * |
||
3120 | * @param string $callerClass The class of objects to be returned |
||
3121 | * @param string|array $filter A filter to be inserted into the WHERE clause. |
||
3122 | * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples. |
||
3123 | * @param string|array $sort A sort expression to be inserted into the ORDER |
||
3124 | * BY clause. If omitted, self::$default_sort will be used. |
||
3125 | * @param string $join Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead. |
||
3126 | * @param string|array $limit A limit expression to be inserted into the LIMIT clause. |
||
3127 | * @param string $containerClass The container class to return the results in. |
||
3128 | * |
||
3129 | * @todo $containerClass is Ignored, why? |
||
3130 | * |
||
3131 | * @return DataList The objects matching the filter, in the class specified by $containerClass |
||
3132 | */ |
||
3133 | public static function get($callerClass = null, $filter = "", $sort = "", $join = "", $limit = null, |
||
3170 | |||
3171 | |||
3172 | /** |
||
3173 | * Return the first item matching the given query. |
||
3174 | * All calls to get_one() are cached. |
||
3175 | * |
||
3176 | * @param string $callerClass The class of objects to be returned |
||
3177 | * @param string|array $filter A filter to be inserted into the WHERE clause. |
||
3178 | * Supports parameterised queries. See SQLSelect::addWhere() for syntax examples. |
||
3179 | * @param boolean $cache Use caching |
||
3180 | * @param string $orderby A sort expression to be inserted into the ORDER BY clause. |
||
3181 | * |
||
3182 | * @return DataObject The first item matching the query |
||
3183 | */ |
||
3184 | public static function get_one($callerClass, $filter = "", $cache = true, $orderby = "") { |
||
3210 | |||
3211 | /** |
||
3212 | * Flush the cached results for all relations (has_one, has_many, many_many) |
||
3213 | * Also clears any cached aggregate data. |
||
3214 | * |
||
3215 | * @param boolean $persistent When true will also clear persistent data stored in the Cache system. |
||
3216 | * When false will just clear session-local cached data |
||
3217 | * @return DataObject $this |
||
3218 | */ |
||
3219 | public function flushCache($persistent = true) { |
||
3235 | |||
3236 | /** |
||
3237 | * Flush the get_one global cache and destroy associated objects. |
||
3238 | */ |
||
3239 | public static function flush_and_destroy_cache() { |
||
3247 | |||
3248 | /** |
||
3249 | * Reset all global caches associated with DataObject. |
||
3250 | */ |
||
3251 | public static function reset() { |
||
3260 | |||
3261 | /** |
||
3262 | * Return the given element, searching by ID |
||
3263 | * |
||
3264 | * @param string $callerClass The class of the object to be returned |
||
3265 | * @param int $id The id of the element |
||
3266 | * @param boolean $cache See {@link get_one()} |
||
3267 | * |
||
3268 | * @return DataObject The element |
||
3269 | */ |
||
3270 | public static function get_by_id($callerClass, $id, $cache = true) { |
||
3287 | |||
3288 | /** |
||
3289 | * Get the name of the base table for this object |
||
3290 | */ |
||
3291 | public function baseTable() { |
||
3295 | |||
3296 | /** |
||
3297 | * @var Array Parameters used in the query that built this object. |
||
3298 | * This can be used by decorators (e.g. lazy loading) to |
||
3299 | * run additional queries using the same context. |
||
3300 | */ |
||
3301 | protected $sourceQueryParams; |
||
3302 | |||
3303 | /** |
||
3304 | * @see $sourceQueryParams |
||
3305 | * @return array |
||
3306 | */ |
||
3307 | public function getSourceQueryParams() { |
||
3310 | |||
3311 | /** |
||
3312 | * Get list of parameters that should be inherited to relations on this object |
||
3313 | * |
||
3314 | * @return array |
||
3315 | */ |
||
3316 | public function getInheritableQueryParams() { |
||
3317 | $params = $this->getSourceQueryParams(); |
||
3318 | $this->extend('updateInheritableQueryParams', $params); |
||
3319 | return $params; |
||
3320 | } |
||
3321 | |||
3322 | /** |
||
3323 | * @see $sourceQueryParams |
||
3324 | * @param array |
||
3325 | */ |
||
3326 | public function setSourceQueryParams($array) { |
||
3329 | |||
3330 | /** |
||
3331 | * @see $sourceQueryParams |
||
3332 | * @param array |
||
3333 | */ |
||
3334 | public function setSourceQueryParam($key, $value) { |
||
3337 | |||
3338 | /** |
||
3339 | * @see $sourceQueryParams |
||
3340 | * @return Mixed |
||
3341 | */ |
||
3342 | public function getSourceQueryParam($key) { |
||
3346 | |||
3347 | //-------------------------------------------------------------------------------------------// |
||
3348 | |||
3349 | /** |
||
3350 | * Return the database indexes on this table. |
||
3351 | * This array is indexed by the name of the field with the index, and |
||
3352 | * the value is the type of index. |
||
3353 | */ |
||
3354 | public function databaseIndexes() { |
||
3379 | |||
3380 | /** |
||
3381 | * Check the database schema and update it as necessary. |
||
3382 | * |
||
3383 | * @uses DataExtension->augmentDatabase() |
||
3384 | */ |
||
3385 | public function requireTable() { |
||
3430 | |||
3431 | /** |
||
3432 | * Validate that the configured relations for this class use the correct syntaxes |
||
3433 | * @throws LogicException |
||
3434 | */ |
||
3435 | protected function validateModelDefinitions() { |
||
3466 | |||
3467 | /** |
||
3468 | * Add default records to database. This function is called whenever the |
||
3469 | * database is built, after the database tables have all been created. Overload |
||
3470 | * this to add default records when the database is built, but make sure you |
||
3471 | * call parent::requireDefaultRecords(). |
||
3472 | * |
||
3473 | * @uses DataExtension->requireDefaultRecords() |
||
3474 | */ |
||
3475 | public function requireDefaultRecords() { |
||
3493 | |||
3494 | /** |
||
3495 | * Get the default searchable fields for this object, as defined in the |
||
3496 | * $searchable_fields list. If searchable fields are not defined on the |
||
3497 | * data object, uses a default selection of summary fields. |
||
3498 | * |
||
3499 | * @return array |
||
3500 | */ |
||
3501 | public function searchableFields() { |
||
3575 | |||
3576 | /** |
||
3577 | * Get any user defined searchable fields labels that |
||
3578 | * exist. Allows overriding of default field names in the form |
||
3579 | * interface actually presented to the user. |
||
3580 | * |
||
3581 | * The reason for keeping this separate from searchable_fields, |
||
3582 | * which would be a logical place for this functionality, is to |
||
3583 | * avoid bloating and complicating the configuration array. Currently |
||
3584 | * much of this system is based on sensible defaults, and this property |
||
3585 | * would generally only be set in the case of more complex relationships |
||
3586 | * between data object being required in the search interface. |
||
3587 | * |
||
3588 | * Generates labels based on name of the field itself, if no static property |
||
3589 | * {@link self::field_labels} exists. |
||
3590 | * |
||
3591 | * @uses $field_labels |
||
3592 | * @uses FormField::name_to_label() |
||
3593 | * |
||
3594 | * @param boolean $includerelations a boolean value to indicate if the labels returned include relation fields |
||
3595 | * |
||
3596 | * @return array|string Array of all element labels if no argument given, otherwise the label of the field |
||
3597 | */ |
||
3598 | public function fieldLabels($includerelations = true) { |
||
3599 | $cacheKey = $this->class . '_' . $includerelations; |
||
3600 | |||
3601 | if(!isset(self::$_cache_field_labels[$cacheKey])) { |
||
3602 | $customLabels = $this->stat('field_labels'); |
||
3603 | $autoLabels = array(); |
||
3604 | |||
3605 | // get all translated static properties as defined in i18nCollectStatics() |
||
3606 | $ancestry = ClassInfo::ancestry($this->class); |
||
3607 | $ancestry = array_reverse($ancestry); |
||
3608 | if($ancestry) foreach($ancestry as $ancestorClass) { |
||
3609 | if($ancestorClass == 'ViewableData') break; |
||
3610 | $types = array( |
||
3611 | 'db' => (array)Config::inst()->get($ancestorClass, 'db', Config::UNINHERITED) |
||
3612 | ); |
||
3613 | if($includerelations){ |
||
3614 | $types['has_one'] = (array)Config::inst()->get($ancestorClass, 'has_one', Config::UNINHERITED); |
||
3615 | $types['has_many'] = (array)Config::inst()->get($ancestorClass, 'has_many', Config::UNINHERITED); |
||
3616 | $types['many_many'] = (array)Config::inst()->get($ancestorClass, 'many_many', Config::UNINHERITED); |
||
3617 | $types['belongs_many_many'] = (array)Config::inst()->get($ancestorClass, 'belongs_many_many', Config::UNINHERITED); |
||
3618 | } |
||
3619 | foreach($types as $type => $attrs) { |
||
3620 | foreach($attrs as $name => $spec) { |
||
3621 | $autoLabels[$name] = _t("{$ancestorClass}.{$type}_{$name}",FormField::name_to_label($name)); |
||
3622 | } |
||
3623 | } |
||
3624 | } |
||
3625 | |||
3626 | $labels = array_merge((array)$autoLabels, (array)$customLabels); |
||
3627 | $this->extend('updateFieldLabels', $labels); |
||
3628 | self::$_cache_field_labels[$cacheKey] = $labels; |
||
3629 | } |
||
3630 | |||
3631 | return self::$_cache_field_labels[$cacheKey]; |
||
3632 | } |
||
3633 | |||
3634 | /** |
||
3635 | * Get a human-readable label for a single field, |
||
3636 | * see {@link fieldLabels()} for more details. |
||
3637 | * |
||
3638 | * @uses fieldLabels() |
||
3639 | * @uses FormField::name_to_label() |
||
3640 | * |
||
3641 | * @param string $name Name of the field |
||
3642 | * @return string Label of the field |
||
3643 | */ |
||
3644 | public function fieldLabel($name) { |
||
3648 | |||
3649 | /** |
||
3650 | * Get the default summary fields for this object. |
||
3651 | * |
||
3652 | * @todo use the translation apparatus to return a default field selection for the language |
||
3653 | * |
||
3654 | * @return array |
||
3655 | */ |
||
3656 | public function summaryFields() { |
||
3689 | |||
3690 | /** |
||
3691 | * Defines a default list of filters for the search context. |
||
3692 | * |
||
3693 | * If a filter class mapping is defined on the data object, |
||
3694 | * it is constructed here. Otherwise, the default filter specified in |
||
3695 | * {@link DBField} is used. |
||
3696 | * |
||
3697 | * @todo error handling/type checking for valid FormField and SearchFilter subclasses? |
||
3698 | * |
||
3699 | * @return array |
||
3700 | */ |
||
3701 | public function defaultSearchFilters() { |
||
3722 | |||
3723 | /** |
||
3724 | * @return boolean True if the object is in the database |
||
3725 | */ |
||
3726 | public function isInDB() { |
||
3729 | |||
3730 | /* |
||
3731 | * @ignore |
||
3732 | */ |
||
3733 | private static $subclass_access = true; |
||
3734 | |||
3735 | /** |
||
3736 | * Temporarily disable subclass access in data object qeur |
||
3737 | */ |
||
3738 | public static function disable_subclass_access() { |
||
3744 | |||
3745 | //-------------------------------------------------------------------------------------------// |
||
3746 | |||
3747 | /** |
||
3748 | * Database field definitions. |
||
3749 | * This is a map from field names to field type. The field |
||
3750 | * type should be a class that extends . |
||
3751 | * @var array |
||
3752 | * @config |
||
3753 | */ |
||
3754 | private static $db = null; |
||
3755 | |||
3756 | /** |
||
3757 | * Use a casting object for a field. This is a map from |
||
3758 | * field name to class name of the casting object. |
||
3759 | * |
||
3760 | * @var array |
||
3761 | */ |
||
3762 | private static $casting = array( |
||
3763 | "Title" => 'Text', |
||
3764 | ); |
||
3765 | |||
3766 | /** |
||
3767 | * Specify custom options for a CREATE TABLE call. |
||
3768 | * Can be used to specify a custom storage engine for specific database table. |
||
3769 | * All options have to be keyed for a specific database implementation, |
||
3770 | * identified by their class name (extending from {@link SS_Database}). |
||
3771 | * |
||
3772 | * <code> |
||
3773 | * array( |
||
3774 | * 'MySQLDatabase' => 'ENGINE=MyISAM' |
||
3775 | * ) |
||
3776 | * </code> |
||
3777 | * |
||
3778 | * Caution: This API is experimental, and might not be |
||
3779 | * included in the next major release. Please use with care. |
||
3780 | * |
||
3781 | * @var array |
||
3782 | * @config |
||
3783 | */ |
||
3784 | private static $create_table_options = array( |
||
3785 | 'MySQLDatabase' => 'ENGINE=InnoDB' |
||
3786 | ); |
||
3787 | |||
3788 | /** |
||
3789 | * If a field is in this array, then create a database index |
||
3790 | * on that field. This is a map from fieldname to index type. |
||
3791 | * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation. |
||
3792 | * |
||
3793 | * @var array |
||
3794 | * @config |
||
3795 | */ |
||
3796 | private static $indexes = null; |
||
3797 | |||
3798 | /** |
||
3799 | * Inserts standard column-values when a DataObject |
||
3800 | * is instanciated. Does not insert default records {@see $default_records}. |
||
3801 | * This is a map from fieldname to default value. |
||
3802 | * |
||
3803 | * - If you would like to change a default value in a sub-class, just specify it. |
||
3804 | * - If you would like to disable the default value given by a parent class, set the default value to 0,'', |
||
3805 | * or false in your subclass. Setting it to null won't work. |
||
3806 | * |
||
3807 | * @var array |
||
3808 | * @config |
||
3809 | */ |
||
3810 | private static $defaults = null; |
||
3811 | |||
3812 | /** |
||
3813 | * Multidimensional array which inserts default data into the database |
||
3814 | * on a db/build-call as long as the database-table is empty. Please use this only |
||
3815 | * for simple constructs, not for SiteTree-Objects etc. which need special |
||
3816 | * behaviour such as publishing and ParentNodes. |
||
3817 | * |
||
3818 | * Example: |
||
3819 | * array( |
||
3820 | * array('Title' => "DefaultPage1", 'PageTitle' => 'page1'), |
||
3821 | * array('Title' => "DefaultPage2") |
||
3822 | * ). |
||
3823 | * |
||
3824 | * @var array |
||
3825 | * @config |
||
3826 | */ |
||
3827 | private static $default_records = null; |
||
3828 | |||
3829 | /** |
||
3830 | * One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a |
||
3831 | * true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class. |
||
3832 | * |
||
3833 | * Note that you cannot have a has_one and belongs_to relationship with the same name. |
||
3834 | * |
||
3835 | * @var array |
||
3836 | * @config |
||
3837 | */ |
||
3838 | private static $has_one = null; |
||
3839 | |||
3840 | /** |
||
3841 | * A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}. |
||
3842 | * |
||
3843 | * This does not actually create any data structures, but allows you to query the other object in a one-to-one |
||
3844 | * relationship from the child object. If you have multiple belongs_to links to another object you can use the |
||
3845 | * syntax "ClassName.HasOneName" to specify which foreign has_one key on the other object to use. |
||
3846 | * |
||
3847 | * Note that you cannot have a has_one and belongs_to relationship with the same name. |
||
3848 | * |
||
3849 | * @var array |
||
3850 | * @config |
||
3851 | */ |
||
3852 | private static $belongs_to; |
||
3853 | |||
3854 | /** |
||
3855 | * This defines a one-to-many relationship. It is a map of component name to the remote data class. |
||
3856 | * |
||
3857 | * This relationship type does not actually create a data structure itself - you need to define a matching $has_one |
||
3858 | * relationship on the child class. Also, if the $has_one relationship on the child class has multiple links to this |
||
3859 | * class you can use the syntax "ClassName.HasOneRelationshipName" in the remote data class definition to show |
||
3860 | * which foreign key to use. |
||
3861 | * |
||
3862 | * @var array |
||
3863 | * @config |
||
3864 | */ |
||
3865 | private static $has_many = null; |
||
3866 | |||
3867 | /** |
||
3868 | * many-many relationship definitions. |
||
3869 | * This is a map from component name to data type. |
||
3870 | * @var array |
||
3871 | * @config |
||
3872 | */ |
||
3873 | private static $many_many = null; |
||
3874 | |||
3875 | /** |
||
3876 | * Extra fields to include on the connecting many-many table. |
||
3877 | * This is a map from field name to field type. |
||
3878 | * |
||
3879 | * Example code: |
||
3880 | * <code> |
||
3881 | * public static $many_many_extraFields = array( |
||
3882 | * 'Members' => array( |
||
3883 | * 'Role' => 'Varchar(100)' |
||
3884 | * ) |
||
3885 | * ); |
||
3886 | * </code> |
||
3887 | * |
||
3888 | * @var array |
||
3889 | * @config |
||
3890 | */ |
||
3891 | private static $many_many_extraFields = null; |
||
3892 | |||
3893 | /** |
||
3894 | * The inverse side of a many-many relationship. |
||
3895 | * This is a map from component name to data type. |
||
3896 | * @var array |
||
3897 | * @config |
||
3898 | */ |
||
3899 | private static $belongs_many_many = null; |
||
3900 | |||
3901 | /** |
||
3902 | * The default sort expression. This will be inserted in the ORDER BY |
||
3903 | * clause of a SQL query if no other sort expression is provided. |
||
3904 | * @var string |
||
3905 | * @config |
||
3906 | */ |
||
3907 | private static $default_sort = null; |
||
3908 | |||
3909 | /** |
||
3910 | * Default list of fields that can be scaffolded by the ModelAdmin |
||
3911 | * search interface. |
||
3912 | * |
||
3913 | * Overriding the default filter, with a custom defined filter: |
||
3914 | * <code> |
||
3915 | * static $searchable_fields = array( |
||
3916 | * "Name" => "PartialMatchFilter" |
||
3917 | * ); |
||
3918 | * </code> |
||
3919 | * |
||
3920 | * Overriding the default form fields, with a custom defined field. |
||
3921 | * The 'filter' parameter will be generated from {@link DBField::$default_search_filter_class}. |
||
3922 | * The 'title' parameter will be generated from {@link DataObject->fieldLabels()}. |
||
3923 | * <code> |
||
3924 | * static $searchable_fields = array( |
||
3925 | * "Name" => array( |
||
3926 | * "field" => "TextField" |
||
3927 | * ) |
||
3928 | * ); |
||
3929 | * </code> |
||
3930 | * |
||
3931 | * Overriding the default form field, filter and title: |
||
3932 | * <code> |
||
3933 | * static $searchable_fields = array( |
||
3934 | * "Organisation.ZipCode" => array( |
||
3935 | * "field" => "TextField", |
||
3936 | * "filter" => "PartialMatchFilter", |
||
3937 | * "title" => 'Organisation ZIP' |
||
3938 | * ) |
||
3939 | * ); |
||
3940 | * </code> |
||
3941 | * @config |
||
3942 | */ |
||
3943 | private static $searchable_fields = null; |
||
3944 | |||
3945 | /** |
||
3946 | * User defined labels for searchable_fields, used to override |
||
3947 | * default display in the search form. |
||
3948 | * @config |
||
3949 | */ |
||
3950 | private static $field_labels = null; |
||
3951 | |||
3952 | /** |
||
3953 | * Provides a default list of fields to be used by a 'summary' |
||
3954 | * view of this object. |
||
3955 | * @config |
||
3956 | */ |
||
3957 | private static $summary_fields = null; |
||
3958 | |||
3959 | /** |
||
3960 | * Collect all static properties on the object |
||
3961 | * which contain natural language, and need to be translated. |
||
3962 | * The full entity name is composed from the class name and a custom identifier. |
||
3963 | * |
||
3964 | * @return array A numerical array which contains one or more entities in array-form. |
||
3965 | * Each numeric entity array contains the "arguments" for a _t() call as array values: |
||
3966 | * $entity, $string, $priority, $context. |
||
3967 | */ |
||
3968 | public function provideI18nEntities() { |
||
3986 | |||
3987 | /** |
||
3988 | * Returns true if the given method/parameter has a value |
||
3989 | * (Uses the DBField::hasValue if the parameter is a database field) |
||
3990 | * |
||
3991 | * @param string $field The field name |
||
3992 | * @param array $arguments |
||
3993 | * @param bool $cache |
||
3994 | * @return boolean |
||
3995 | */ |
||
3996 | public function hasValue($field, $arguments = null, $cache = true) { |
||
4004 | |||
4005 | } |
||
4006 |
Since your code implements the magic setter
_set
, this function will be called for any write access on an undefined variable. You can add the@property
annotation to your class or interface to document the existence of this variable.Since the property has write access only, you can use the @property-write annotation instead.
Of course, you may also just have mistyped another name, in which case you should fix the error.
See also the PhpDoc documentation for @property.