-
Notifications
You must be signed in to change notification settings - Fork 824
/
DataObjectSchema.php
1245 lines (1141 loc) · 43.5 KB
/
DataObjectSchema.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace SilverStripe\ORM;
use Exception;
use InvalidArgumentException;
use LogicException;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\TestOnly;
use SilverStripe\ORM\Connect\DBSchemaManager;
use SilverStripe\ORM\FieldType\DBComposite;
use SilverStripe\ORM\FieldType\DBField;
/**
* Provides dataobject and database schema mapping functionality
*/
class DataObjectSchema
{
use Injectable;
use Configurable;
/**
* Default separate for table namespaces. Can be set to any string for
* databases that do not support some characters.
*
* @config
* @var string
*/
private static $table_namespace_separator = '_';
/**
* Cache of database fields
*
* @var array
*/
protected $databaseFields = [];
/**
* Cache of database indexes
*
* @var array
*/
protected $databaseIndexes = [];
/**
* Fields that should be indexed, by class name
*
* @var array
*/
protected $defaultDatabaseIndexes = [];
/**
* Cache of composite database field
*
* @var array
*/
protected $compositeFields = [];
/**
* Cache of table names
*
* @var array
*/
protected $tableNames = [];
/**
* Clear cached table names
*/
public function reset()
{
$this->tableNames = [];
$this->databaseFields = [];
$this->databaseIndexes = [];
$this->defaultDatabaseIndexes = [];
$this->compositeFields = [];
}
/**
* Get all table names
*
* @return array
*/
public function getTableNames()
{
$this->cacheTableNames();
return $this->tableNames;
}
/**
* Given a DataObject class and a field on that class, determine the appropriate SQL for
* selecting / filtering on in a SQL string. Note that $class must be a valid class, not an
* arbitrary table.
*
* The result will be a standard ANSI-sql quoted string in "Table"."Column" format.
*
* @param string $class Class name (not a table).
* @param string $field Name of field that belongs to this class (or a parent class)
* @param string $tablePrefix Optional prefix for table (alias)
*
* @return string The SQL identifier string for the corresponding column for this field
*/
public function sqlColumnForField($class, $field, $tablePrefix = null)
{
$table = $this->tableForField($class, $field);
if (!$table) {
throw new InvalidArgumentException("\"{$field}\" is not a field on class \"{$class}\"");
}
return "\"{$tablePrefix}{$table}\".\"{$field}\"";
}
/**
* Get table name for the given class.
*
* Note that this does not confirm a table actually exists (or should exist), but returns
* the name that would be used if this table did exist.
*
* @param string $class
*
* @return string Returns the table name, or null if there is no table
*/
public function tableName($class)
{
$tables = $this->getTableNames();
$class = ClassInfo::class_name($class);
if (isset($tables[$class])) {
return Convert::raw2sql($tables[$class]);
}
return null;
}
/**
* Returns the root class (the first to extend from DataObject) for the
* passed class.
*
* @param string|object $class
*
* @return string
* @throws InvalidArgumentException
*/
public function baseDataClass($class)
{
$current = $class;
while ($next = get_parent_class($current)) {
if ($next === DataObject::class) {
// Only use ClassInfo::class_name() to format the class if we've not used get_parent_class()
return ($current === $class) ? ClassInfo::class_name($current) : $current;
}
$current = $next;
}
throw new InvalidArgumentException("$class is not a subclass of DataObject");
}
/**
* Get the base table
*
* @param string|object $class
*
* @return string
*/
public function baseDataTable($class)
{
return $this->tableName($this->baseDataClass($class));
}
/**
* fieldSpec should exclude virtual fields (such as composite fields), and only include fields with a db column.
*/
const DB_ONLY = 1;
/**
* fieldSpec should only return fields that belong to this table, and not any ancestors
*/
const UNINHERITED = 2;
/**
* fieldSpec should prefix all field specifications with the class name in RecordClass.Column(spec) format.
*/
const INCLUDE_CLASS = 4;
/**
* Get all DB field specifications for a class, including ancestors and composite fields.
*
* @param string|DataObject $classOrInstance
* @param int $options Bitmask of options
* - UNINHERITED Limit to only this table
* - DB_ONLY Exclude virtual fields (such as composite fields), and only include fields with a db column.
* - INCLUDE_CLASS Prefix the field specification with the class name in RecordClass.Column(spec) format.
*
* @return array List of fields, where the key is the field name and the value is the field specification.
*/
public function fieldSpecs($classOrInstance, $options = 0)
{
$class = ClassInfo::class_name($classOrInstance);
// Validate options
if (!is_int($options)) {
throw new InvalidArgumentException("Invalid options " . var_export($options, true));
}
$uninherited = ($options & self::UNINHERITED) === self::UNINHERITED;
$dbOnly = ($options & self::DB_ONLY) === self::DB_ONLY;
$includeClass = ($options & self::INCLUDE_CLASS) === self::INCLUDE_CLASS;
// Walk class hierarchy
$db = [];
$classes = $uninherited ? [$class] : ClassInfo::ancestry($class);
foreach ($classes as $tableClass) {
// Skip irrelevant parent classes
if (!is_subclass_of($tableClass, DataObject::class)) {
continue;
}
// Find all fields on this class
$fields = $this->databaseFields($tableClass, false);
// Merge with composite fields
if (!$dbOnly) {
$compositeFields = $this->compositeFields($tableClass, false);
$fields = array_merge($fields, $compositeFields);
}
// Record specification
foreach ($fields as $name => $specification) {
$prefix = $includeClass ? "{$tableClass}." : "";
$db[$name] = $prefix . $specification;
}
}
return $db;
}
/**
* Get specifications for a single class field
*
* @param string|DataObject $classOrInstance Name or instance of class
* @param string $fieldName Name of field to retrieve
* @param int $options Bitmask of options
* - UNINHERITED Limit to only this table
* - DB_ONLY Exclude virtual fields (such as composite fields), and only include fields with a db column.
* - INCLUDE_CLASS Prefix the field specification with the class name in RecordClass.Column(spec) format.
*
* @return string|null Field will be a string in FieldClass(args) format, or
* RecordClass.FieldClass(args) format if using INCLUDE_CLASS. Will be null if no field is found.
*/
public function fieldSpec($classOrInstance, $fieldName, $options = 0)
{
$specs = $this->fieldSpecs($classOrInstance, $options);
return isset($specs[$fieldName]) ? $specs[$fieldName] : null;
}
/**
* Find the class for the given table
*
* @param string $table
*
* @return string|null The FQN of the class, or null if not found
*/
public function tableClass($table)
{
$tables = $this->getTableNames();
$class = array_search($table, $tables, true);
if ($class) {
return $class;
}
// If there is no class for this table, strip table modifiers (e.g. _Live / _Versions)
// from the end and re-attempt a search.
if (preg_match('/^(?<class>.+)(_[^_]+)$/i', $table, $matches)) {
$table = $matches['class'];
$class = array_search($table, $tables, true);
if ($class) {
return $class;
}
}
return null;
}
/**
* Cache all table names if necessary
*/
protected function cacheTableNames()
{
if ($this->tableNames) {
return;
}
$this->tableNames = [];
foreach (ClassInfo::subclassesFor(DataObject::class) as $class) {
if ($class === DataObject::class) {
continue;
}
$table = $this->buildTableName($class);
// Check for conflicts
$conflict = array_search($table, $this->tableNames, true);
if ($conflict) {
throw new LogicException(
"Multiple classes (\"{$class}\", \"{$conflict}\") map to the same table: \"{$table}\""
);
}
$this->tableNames[$class] = $table;
}
}
/**
* Generate table name for a class.
*
* Note: some DB schema have a hard limit on table name length. This is not enforced by this method.
* See dev/build errors for details in case of table name violation.
*
* @param string $class
*
* @return string
*/
protected function buildTableName($class)
{
$table = Config::inst()->get($class, 'table_name', Config::UNINHERITED);
// Generate default table name
if ($table) {
return $table;
}
if (strpos($class, '\\') === false) {
return $class;
}
$separator = DataObjectSchema::config()->uninherited('table_namespace_separator');
$table = str_replace('\\', $separator, trim($class, '\\'));
if (!ClassInfo::classImplements($class, TestOnly::class) && $this->classHasTable($class)) {
DBSchemaManager::showTableNameWarning($table, $class);
}
return $table;
}
/**
* Return the complete map of fields to specification on this object, including fixed_fields.
* "ID" will be included on every table.
*
* @param string $class Class name to query from
* @param bool $aggregated Include fields in entire hierarchy, rather than just on this table
*
* @return array Map of fieldname to specification, similar to {@link DataObject::$db}.
*/
public function databaseFields($class, $aggregated = true)
{
$class = ClassInfo::class_name($class);
if ($class === DataObject::class) {
return [];
}
$this->cacheDatabaseFields($class);
$fields = $this->databaseFields[$class];
if (!$aggregated) {
return $fields;
}
// Recursively merge
$parentFields = $this->databaseFields(get_parent_class($class));
return array_merge($fields, array_diff_key($parentFields, $fields));
}
/**
* Gets a single database field.
*
* @param string $class Class name to query from
* @param string $field Field name
* @param bool $aggregated Include fields in entire hierarchy, rather than just on this table
*
* @return string|null Field specification, or null if not a field
*/
public function databaseField($class, $field, $aggregated = true)
{
$fields = $this->databaseFields($class, $aggregated);
return isset($fields[$field]) ? $fields[$field] : null;
}
/**
* @param string $class
* @param bool $aggregated
*
* @return array
*/
public function databaseIndexes($class, $aggregated = true)
{
$class = ClassInfo::class_name($class);
if ($class === DataObject::class) {
return [];
}
$this->cacheDatabaseIndexes($class);
$indexes = $this->databaseIndexes[$class];
if (!$aggregated) {
return $indexes;
}
return array_merge($indexes, $this->databaseIndexes(get_parent_class($class)));
}
/**
* Check if the given class has a table
*
* @param string $class
*
* @return bool
*/
public function classHasTable($class)
{
if (!is_subclass_of($class, DataObject::class)) {
return false;
}
$fields = $this->databaseFields($class, false);
return !empty($fields);
}
/**
* Returns a list of all the composite if the given db field on the class is a composite field.
* Will check all applicable ancestor classes and aggregate results.
*
* Can be called directly on an object. E.g. Member::composite_fields(), or Member::composite_fields(null, true)
* to aggregate.
*
* Includes composite has_one (Polymorphic) fields
*
* @param string $class Name of class to check
* @param bool $aggregated Include fields in entire hierarchy, rather than just on this table
*
* @return array List of composite fields and their class spec
*/
public function compositeFields($class, $aggregated = true)
{
$class = ClassInfo::class_name($class);
if ($class === DataObject::class) {
return [];
}
$this->cacheDatabaseFields($class);
// Get fields for this class
$compositeFields = $this->compositeFields[$class];
if (!$aggregated) {
return $compositeFields;
}
// Recursively merge
$parentFields = $this->compositeFields(get_parent_class($class));
return array_merge($compositeFields, array_diff_key($parentFields, $compositeFields));
}
/**
* Get a composite field for a class
*
* @param string $class Class name to query from
* @param string $field Field name
* @param bool $aggregated Include fields in entire hierarchy, rather than just on this table
*
* @return string|null Field specification, or null if not a field
*/
public function compositeField($class, $field, $aggregated = true)
{
$fields = $this->compositeFields($class, $aggregated);
return isset($fields[$field]) ? $fields[$field] : null;
}
/**
* Cache all database and composite fields for the given class.
* Will do nothing if already cached
*
* @param string $class Class name to cache
*/
protected function cacheDatabaseFields($class)
{
// Skip if already cached
if (isset($this->databaseFields[$class]) && isset($this->compositeFields[$class])) {
return;
}
$compositeFields = [];
$dbFields = [];
// Ensure fixed fields appear at the start
$fixedFields = DataObject::config()->uninherited('fixed_fields');
if (get_parent_class($class) === DataObject::class) {
// Merge fixed with ClassName spec and custom db fields
$dbFields = $fixedFields;
} else {
$dbFields['ID'] = $fixedFields['ID'];
}
// Check each DB value as either a field or composite field
$db = Config::inst()->get($class, 'db', Config::UNINHERITED) ?: [];
foreach ($db as $fieldName => $fieldSpec) {
$fieldClass = strtok($fieldSpec, '(');
if (singleton($fieldClass) instanceof DBComposite) {
$compositeFields[$fieldName] = $fieldSpec;
} else {
$dbFields[$fieldName] = $fieldSpec;
}
}
// Add in all has_ones
$hasOne = Config::inst()->get($class, 'has_one', Config::UNINHERITED) ?: [];
foreach ($hasOne as $fieldName => $hasOneClass) {
if ($hasOneClass === DataObject::class) {
$compositeFields[$fieldName] = 'PolymorphicForeignKey';
} else {
$dbFields["{$fieldName}ID"] = 'ForeignKey';
}
}
// Merge composite fields into DB
foreach ($compositeFields as $fieldName => $fieldSpec) {
$fieldObj = Injector::inst()->create($fieldSpec, $fieldName);
$fieldObj->setTable($class);
$nestedFields = $fieldObj->compositeDatabaseFields();
foreach ($nestedFields as $nestedName => $nestedSpec) {
$dbFields["{$fieldName}{$nestedName}"] = $nestedSpec;
}
}
// Prevent field-less tables with only 'ID'
if (count($dbFields) < 2) {
$dbFields = [];
}
// Return cached results
$this->databaseFields[$class] = $dbFields;
$this->compositeFields[$class] = $compositeFields;
}
/**
* Cache all indexes for the given class. Will do nothing if already cached.
*
* @param $class
*/
protected function cacheDatabaseIndexes($class)
{
if (!array_key_exists($class, $this->databaseIndexes)) {
$this->databaseIndexes[$class] = array_merge(
$this->buildSortDatabaseIndexes($class),
$this->cacheDefaultDatabaseIndexes($class),
$this->buildCustomDatabaseIndexes($class)
);
}
}
/**
* Get "default" database indexable field types
*
* @param string $class
*
* @return array
*/
protected function cacheDefaultDatabaseIndexes($class)
{
if (array_key_exists($class, $this->defaultDatabaseIndexes)) {
return $this->defaultDatabaseIndexes[$class];
}
$this->defaultDatabaseIndexes[$class] = [];
$fieldSpecs = $this->fieldSpecs($class, self::UNINHERITED);
foreach ($fieldSpecs as $field => $spec) {
/** @var DBField $fieldObj */
$fieldObj = Injector::inst()->create($spec, $field);
if ($indexSpecs = $fieldObj->getIndexSpecs()) {
$this->defaultDatabaseIndexes[$class][$field] = $indexSpecs;
}
}
return $this->defaultDatabaseIndexes[$class];
}
/**
* Look for custom indexes declared on the class
*
* @param string $class
*
* @return array
* @throws InvalidArgumentException If an index already exists on the class
* @throws InvalidArgumentException If a custom index format is not valid
*/
protected function buildCustomDatabaseIndexes($class)
{
$indexes = [];
$classIndexes = Config::inst()->get($class, 'indexes', Config::UNINHERITED) ?: [];
foreach ($classIndexes as $indexName => $indexSpec) {
if (array_key_exists($indexName, $indexes)) {
throw new InvalidArgumentException(sprintf(
'Index named "%s" already exists on class %s',
$indexName,
$class
));
}
if (is_array($indexSpec)) {
if (!ArrayLib::is_associative($indexSpec)) {
$indexSpec = [
'columns' => $indexSpec,
];
}
if (!isset($indexSpec['type'])) {
$indexSpec['type'] = 'index';
}
if (!isset($indexSpec['columns'])) {
$indexSpec['columns'] = [$indexName];
} elseif (!is_array($indexSpec['columns'])) {
throw new InvalidArgumentException(sprintf(
'Index %s on %s is not valid. columns should be an array %s given',
var_export($indexName, true),
var_export($class, true),
var_export($indexSpec['columns'], true)
));
}
} else {
$indexSpec = [
'type' => 'index',
'columns' => [$indexName],
];
}
$indexes[$indexName] = $indexSpec;
}
return $indexes;
}
protected function buildSortDatabaseIndexes($class)
{
$sort = Config::inst()->get($class, 'default_sort', Config::UNINHERITED);
$indexes = [];
if ($sort && is_string($sort)) {
$sort = preg_split('/,(?![^()]*+\\))/', $sort);
foreach ($sort as $value) {
try {
list ($table, $column) = $this->parseSortColumn(trim($value));
$table = trim($table, '"');
$column = trim($column, '"');
if ($table && strtolower($table) !== strtolower(self::tableName($class))) {
continue;
}
if ($this->databaseField($class, $column, false)) {
$indexes[$column] = [
'type' => 'index',
'columns' => [$column],
];
}
} catch (InvalidArgumentException $e) {
}
}
}
return $indexes;
}
/**
* Parses a specified column into a sort field and direction
*
* @param string $column String to parse containing the column name
*
* @return array Resolved table and column.
*/
protected function parseSortColumn($column)
{
// Parse column specification, considering possible ansi sql quoting
// Note that table prefix is allowed, but discarded
if (preg_match('/^("?(?<table>[^"\s]+)"?\\.)?"?(?<column>[^"\s]+)"?(\s+(?<direction>((asc)|(desc))(ending)?))?$/i', $column, $match)) {
$table = $match['table'];
$column = $match['column'];
} else {
throw new InvalidArgumentException("Invalid sort() column");
}
return [$table, $column];
}
/**
* Returns the table name in the class hierarchy which contains a given
* field column for a {@link DataObject}. If the field does not exist, this
* will return null.
*
* @param string $candidateClass
* @param string $fieldName
*
* @return string
*/
public function tableForField($candidateClass, $fieldName)
{
$class = $this->classForField($candidateClass, $fieldName);
if ($class) {
return $this->tableName($class);
}
return null;
}
/**
* Returns the class name in the class hierarchy which contains a given
* field column for a {@link DataObject}. If the field does not exist, this
* will return null.
*
* @param string $candidateClass
* @param string $fieldName
*
* @return string
*/
public function classForField($candidateClass, $fieldName)
{
// normalise class name
$candidateClass = ClassInfo::class_name($candidateClass);
if ($candidateClass === DataObject::class) {
return null;
}
// Short circuit for fixed fields
$fixed = DataObject::config()->uninherited('fixed_fields');
if (isset($fixed[$fieldName])) {
return $this->baseDataClass($candidateClass);
}
// Find regular field
while ($candidateClass && $candidateClass !== DataObject::class) {
$fields = $this->databaseFields($candidateClass, false);
if (isset($fields[$fieldName])) {
return $candidateClass;
}
$candidateClass = get_parent_class($candidateClass);
}
return null;
}
/**
* Return information about a specific many_many component. Returns a numeric array.
* The first item in the array will be the class name of the relation.
*
* Standard many_many return type is:
*
* [
* <manyManyClass>, Name of class for relation. E.g. "Categories"
* <classname>, The class that relation is defined in e.g. "Product"
* <candidateName>, The target class of the relation e.g. "Category"
* <parentField>, The field name pointing to <classname>'s table e.g. "ProductID".
* <childField>, The field name pointing to <candidatename>'s table e.g. "CategoryID".
* <joinTableOrRelation> The join table between the two classes e.g. "Product_Categories".
* If the class name is 'ManyManyThroughList' then this is the name of the
* has_many relation.
* ]
*
* @param string $class Name of class to get component for
* @param string $component The component name
*
* @return array|null
*/
public function manyManyComponent($class, $component)
{
$classes = ClassInfo::ancestry($class);
foreach ($classes as $parentClass) {
// Check if the component is defined in many_many on this class
$otherManyMany = Config::inst()->get($parentClass, 'many_many', Config::UNINHERITED);
if (isset($otherManyMany[$component])) {
return $this->parseManyManyComponent($parentClass, $component, $otherManyMany[$component]);
}
// Check if the component is defined in belongs_many_many on this class
$belongsManyMany = Config::inst()->get($parentClass, 'belongs_many_many', Config::UNINHERITED);
if (!isset($belongsManyMany[$component])) {
continue;
}
// Extract class and relation name from dot-notation
$belongs = $this->parseBelongsManyManyComponent(
$parentClass,
$component,
$belongsManyMany[$component]
);
// Build inverse relationship from other many_many, and swap parent/child
$otherManyMany = $this->manyManyComponent($belongs['childClass'], $belongs['relationName']);
return [
'relationClass' => $otherManyMany['relationClass'],
'parentClass' => $otherManyMany['childClass'],
'childClass' => $otherManyMany['parentClass'],
'parentField' => $otherManyMany['childField'],
'childField' => $otherManyMany['parentField'],
'join' => $otherManyMany['join'],
];
}
return null;
}
/**
* Parse a belongs_many_many component to extract class and relationship name
*
* @param string $parentClass Name of class
* @param string $component Name of relation on class
* @param string $specification specification for this belongs_many_many
*
* @return array Array with child class and relation name
*/
protected function parseBelongsManyManyComponent($parentClass, $component, $specification)
{
$childClass = $specification;
$relationName = null;
if (strpos($specification, '.') !== false) {
list($childClass, $relationName) = explode('.', $specification, 2);
}
// Check child class exists
if (!class_exists($childClass)) {
throw new LogicException(
"belongs_many_many relation {$parentClass}.{$component} points to "
. "{$childClass} which does not exist"
);
}
// We need to find the inverse component name, if not explicitly given
if (!$relationName) {
$relationName = $this->getManyManyInverseRelationship($childClass, $parentClass);
}
// Check valid relation found
if (!$relationName) {
throw new LogicException(
"belongs_many_many relation {$parentClass}.{$component} points to "
. "{$specification} without matching many_many"
);
}
// Return relatios
return [
'childClass' => $childClass,
'relationName' => $relationName,
];
}
/**
* Return the many-to-many extra fields specification for a specific component.
*
* @param string $class
* @param string $component
*
* @return array|null
*/
public function manyManyExtraFieldsForComponent($class, $component)
{
// Get directly declared many_many_extraFields
$extraFields = Config::inst()->get($class, 'many_many_extraFields');
if (isset($extraFields[$component])) {
return $extraFields[$component];
}
// If not belongs_many_many then there are no components
while ($class && ($class !== DataObject::class)) {
$belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED);
if (isset($belongsManyMany[$component])) {
// Reverse relationship and find extrafields from child class
$belongs = $this->parseBelongsManyManyComponent(
$class,
$component,
$belongsManyMany[$component]
);
return $this->manyManyExtraFieldsForComponent($belongs['childClass'], $belongs['relationName']);
}
$class = get_parent_class($class);
}
return null;
}
/**
* Return data for a specific has_many component.
*
* @param string $class Parent class
* @param string $component
* @param bool $classOnly If this is TRUE, than any has_many relationships in the form
* "ClassName.Field" will have the field data stripped off. It defaults to TRUE.
*
* @return string|null
*/
public function hasManyComponent($class, $component, $classOnly = true)
{
$hasMany = (array)Config::inst()->get($class, 'has_many');
if (!isset($hasMany[$component])) {
return null;
}
// Remove has_one specifier if given
$hasMany = $hasMany[$component];
$hasManyClass = strtok($hasMany, '.');
// Validate
$this->checkRelationClass($class, $component, $hasManyClass, 'has_many');
return $classOnly ? $hasManyClass : $hasMany;
}
/**
* Return data for a specific has_one component.
*
* @param string $class
* @param string $component
*
* @return string|null
*/
public function hasOneComponent($class, $component)
{
$hasOnes = Config::forClass($class)->get('has_one');
if (!isset($hasOnes[$component])) {
return null;
}
// Validate
$relationClass = $hasOnes[$component];
$this->checkRelationClass($class, $component, $relationClass, 'has_one');
return $relationClass;
}
/**
* Return data for a specific belongs_to component.
*
* @param string $class
* @param string $component
* @param bool $classOnly If this is TRUE, than any has_many relationships in the
* form "ClassName.Field" will have the field data stripped off. It defaults to TRUE.
*
* @return string|null
*/
public function belongsToComponent($class, $component, $classOnly = true)
{
$belongsTo = (array)Config::forClass($class)->get('belongs_to');
if (!isset($belongsTo[$component])) {
return null;
}
// Remove has_one specifier if given
$belongsTo = $belongsTo[$component];
$belongsToClass = strtok($belongsTo, '.');
// Validate
$this->checkRelationClass($class, $component, $belongsToClass, 'belongs_to');
return $classOnly ? $belongsToClass : $belongsTo;
}
/**
* Check class for any unary component
*
* Alias for hasOneComponent() ?: belongsToComponent()
*
* @param string $class
* @param string $component
*
* @return string|null
*/
public function unaryComponent($class, $component)
{
return $this->hasOneComponent($class, $component) ?: $this->belongsToComponent($class, $component);
}
/**
*
* @param string $parentClass Parent class name
* @param string $component ManyMany name
* @param string|array $specification Declaration of many_many relation type
*
* @return array
*/
protected function parseManyManyComponent($parentClass, $component, $specification)
{
// Check if this is many_many_through
if (is_array($specification)) {
// Validate join, parent and child classes
$joinClass = $this->checkManyManyJoinClass($parentClass, $component, $specification);
$parentClass = $this->checkManyManyFieldClass($parentClass, $component, $joinClass, $specification, 'from');
$joinChildClass = $this->checkManyManyFieldClass($parentClass, $component, $joinClass, $specification, 'to');
return [
'relationClass' => ManyManyThroughList::class,
'parentClass' => $parentClass,
'childClass' => $joinChildClass,
/** @internal Polymorphic many_many is experimental */
'parentField' => $specification['from'] . ($parentClass === DataObject::class ? '' : 'ID'),
'childField' => $specification['to'] . 'ID',
'join' => $joinClass,
];
}
// Validate $specification class is valid
$this->checkRelationClass($parentClass, $component, $specification, 'many_many');
// automatic scaffolded many_many table
$classTable = $this->tableName($parentClass);
$parentField = "{$classTable}ID";
if ($parentClass === $specification) {
$childField = "ChildID";
} else {
$candidateTable = $this->tableName($specification);
$childField = "{$candidateTable}ID";
}
$joinTable = "{$classTable}_{$component}";
return [
'relationClass' => ManyManyList::class,
'parentClass' => $parentClass,
'childClass' => $specification,
'parentField' => $parentField,
'childField' => $childField,
'join' => $joinTable,
];
}