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