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