-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathModelCollector.php
More file actions
697 lines (609 loc) · 25.5 KB
/
Copy pathModelCollector.php
File metadata and controls
697 lines (609 loc) · 25.5 KB
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
<?php
/**
* This file is part of contao-community-alliance/dc-general.
*
* (c) 2013-2024 Contao Community Alliance.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package contao-community-alliance/dc-general
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @author Sven Baumann <baumann.sv@gmail.com>
* @author Ingolf Steinhardt <info@e-spin.de>
* @author David Molineus <david.molineus@netzmacht.de>
* @author Stefan Heimes <stefan_heimes@hotmail.com>
* @copyright 2013-2024 Contao Community Alliance.
* @license https://github.com/contao-community-alliance/dc-general/blob/master/LICENSE LGPL-3.0-or-later
* @filesource
*/
namespace ContaoCommunityAlliance\DcGeneral\Controller;
use ContaoCommunityAlliance\DcGeneral\BaseConfigRegistryInterface;
use ContaoCommunityAlliance\DcGeneral\Contao\DataDefinition\Definition\Contao2BackendViewDefinitionInterface;
use ContaoCommunityAlliance\DcGeneral\Data\CollectionInterface;
use ContaoCommunityAlliance\DcGeneral\Data\ConfigInterface;
use ContaoCommunityAlliance\DcGeneral\Data\DataProviderInterface;
use ContaoCommunityAlliance\DcGeneral\Data\ModelId;
use ContaoCommunityAlliance\DcGeneral\Data\ModelIdInterface;
use ContaoCommunityAlliance\DcGeneral\Data\ModelInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\ContainerInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Definition\BasicDefinitionInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Definition\ModelRelationshipDefinitionInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\ModelRelationship\RootConditionInterface;
use ContaoCommunityAlliance\DcGeneral\EnvironmentInterface;
use ContaoCommunityAlliance\DcGeneral\Exception\DcGeneralInvalidArgumentException;
use ContaoCommunityAlliance\DcGeneral\Exception\DcGeneralRuntimeException;
/**
* This class provides methods for retrieval of models.
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ModelCollector
{
/**
* The environment.
*
* @var EnvironmentInterface
*/
private $environment;
/**
* The mode the definition is in.
*
* @var int|null
*/
private $definitionMode;
/**
* The relationship information list.
*
* @var ModelRelationshipDefinitionInterface
*/
private $relationships;
/**
* The root condition.
*
* @var RootConditionInterface|null
*/
private $rootCondition;
/**
* The root data provider.
*
* @var DataProviderInterface|null
*/
private $rootProvider;
/**
* The root data provider name.
*
* @var string|null
*/
private $rootProviderName;
/**
* The parent data provider.
*
* @var DataProviderInterface|null
*/
private $parentProvider;
/**
* The parent data provider name.
*
* @var string|null
*/
private $parentProviderName;
/**
* The default data provider name.
*
* @var string|null
*/
private $defaultProviderName;
/**
* Create a new instance.
*
* @param EnvironmentInterface $environment The environment.
*
* @throws DcGeneralRuntimeException When no root condition is specified and running in hierarchical mode.
*/
public function __construct(EnvironmentInterface $environment)
{
$this->environment = $environment;
$definition = $this->environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
$basicDefinition = $definition->getBasicDefinition();
assert($basicDefinition instanceof BasicDefinitionInterface);
$this->definitionMode = $basicDefinition->getMode();
$this->relationships = $definition->getModelRelationshipDefinition();
$this->defaultProviderName = $basicDefinition->getDataProvider();
if (BasicDefinitionInterface::MODE_HIERARCHICAL === $this->definitionMode) {
$this->rootCondition = $this->relationships->getRootCondition();
$this->rootProviderName = $basicDefinition->getRootDataProvider();
$this->rootProvider = $this->environment->getDataProvider($this->rootProviderName);
if (!$this->rootCondition instanceof RootConditionInterface) {
throw new DcGeneralRuntimeException('No root condition specified for hierarchical mode.');
}
if ($this->environment->getParentDataDefinition()) {
$this->parentProviderName = $basicDefinition->getParentDataProvider();
$this->parentProvider = $this->environment->getDataProvider($this->parentProviderName);
}
}
if (BasicDefinitionInterface::MODE_PARENTEDLIST === $this->definitionMode) {
$this->parentProviderName = $basicDefinition->getParentDataProvider();
$this->parentProvider = $this->environment->getDataProvider($this->parentProviderName);
}
}
/**
* Fetch a certain model from its provider.
*
* @param ModelIdInterface|string $modelId This is either the id of the model or a serialized id.
* @param string|null $providerName The name of the provider, if this is empty, the id will be
* deserialized and the provider name will get extracted from there.
*
* @return ModelInterface|null
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
* @throws \InvalidArgumentException When the model id is invalid.
*/
public function getModel($modelId, $providerName = null)
{
if (\is_string($modelId)) {
if (null !== $providerName) {
$modelId = ModelId::fromValues($providerName, $modelId);
} else {
$modelId = ModelId::fromSerialized($modelId);
}
}
if (!($modelId instanceof ModelIdInterface)) {
throw new \InvalidArgumentException('Invalid model id passed: ' . \var_export($modelId, true));
}
$definition = $this->environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
$parentDefinition = $this->environment->getParentDataDefinition();
$dataProvider = $this->environment->getDataProvider($modelId->getDataProviderName());
assert($dataProvider instanceof DataProviderInterface);
$config = $dataProvider->getEmptyConfig();
$config->setId($modelId->getId());
if ($definition->getName() === $modelId->getDataProviderName()) {
$propertyDefinition = $definition->getPropertiesDefinition();
} elseif ($parentDefinition && $parentDefinition->getName() === $modelId->getDataProviderName()) {
$propertyDefinition = $parentDefinition->getPropertiesDefinition();
} else {
$propertyDefinition = null;
}
if (null !== $propertyDefinition) {
$properties = [];
// Filter real properties from the property definition.
foreach ($propertyDefinition->getPropertyNames() as $propertyName) {
if ($dataProvider->fieldExists($propertyName)) {
$properties[] = $propertyName;
continue;
}
// @codingStandardsIgnoreStart
@\trigger_error(
'Only real property is allowed in the property definition.' .
'This will no longer be supported in the future.',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
}
$config->setFields($properties);
}
return $dataProvider->fetch($config);
}
/**
* Search the parent of the passed model in the passed collection.
*
* This recursively tries to load the parent from sub collections in sub providers.
*
* @param ModelInterface $model The model to search the parent for.
* @param CollectionInterface $models The collection to search in.
*
* @return ModelInterface|null
*
* @throws DcGeneralInvalidArgumentException When the model does not originate from the child provider.
*/
public function searchParentOfIn(ModelInterface $model, CollectionInterface $models)
{
$this->guardModelOriginatesFromProvider($model);
foreach ($models as $candidate) {
foreach ($this->relationships->getChildConditions($candidate->getProviderName()) as $condition) {
if ($condition->matches($candidate, $model)) {
return $candidate;
}
$provider = $this->environment->getDataProvider($condition->getDestinationName());
assert($provider instanceof DataProviderInterface);
$config = $provider->getEmptyConfig()->setFilter($condition->getFilter($candidate));
$parentCollection = $provider->fetchAll($config);
assert($parentCollection instanceof CollectionInterface);
$result = $this->searchParentOfIn($model, $parentCollection);
if (null !== $result) {
return $result;
}
}
}
return null;
}
/**
* Search the parent model for the given model.
*
* If the model is part of a hierarchical structure the parent node is determined instead of a possible available
* parent relationship.
*
* @param ModelInterface $model The model for which the parent shall be retrieved.
*
* @return ModelInterface|null
*
* @throws DcGeneralInvalidArgumentException When a root model has been passed or not in hierarchical mode.
* @throws DcGeneralInvalidArgumentException When the model does not originate from the child provider.
*/
public function searchParentOf(ModelInterface $model)
{
switch ($this->definitionMode) {
case BasicDefinitionInterface::MODE_HIERARCHICAL:
return $this->searchParentOfInHierarchical($model);
case BasicDefinitionInterface::MODE_PARENTEDLIST:
return $this->searchParentOfInParentedMode($model);
default:
}
throw new DcGeneralInvalidArgumentException('Invalid condition, not in hierarchical mode!');
}
/**
* Search the parent model from a hierarchical model.
*
* @param ModelInterface $model The hierarchical model for search the parent model.
*
* @return ModelInterface|null
*
* @throws DcGeneralInvalidArgumentException It throws a exception if the configuration not passed.
*/
public function searchParentFromHierarchical(ModelInterface $model): ?ModelInterface
{
if (null === $this->rootProvider) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. The root data provider must be defined!'
);
}
if (null === $this->parentProvider) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. The parent data provider must be defined!'
);
}
if ($this->rootProviderName !== $model->getProviderName()) {
throw new DcGeneralInvalidArgumentException(
'Model originates from ' . $model->getProviderName() .
' but is expected to be from ' . ($this->rootProviderName ?? '') .
' can not determine parent.'
);
}
$parentProviderName = $this->parentProviderName;
assert(\is_string($parentProviderName));
$rootProviderName = $this->rootProviderName;
assert(\is_string($rootProviderName));
$condition = $this->relationships->getChildCondition($parentProviderName, $rootProviderName);
if (null === $condition) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. Child condition must be defined!'
);
}
if (null !== ($inverseFilter = $condition->getInverseFilterFor($model))) {
return $this->parentProvider->fetch($this->parentProvider->getEmptyConfig()->setFilter($inverseFilter));
}
$parentCollection = $this->parentProvider->fetchAll($this->parentProvider->getEmptyConfig());
assert($parentCollection instanceof CollectionInterface);
foreach ($parentCollection as $candidate) {
if ($condition->matches($candidate, $model)) {
return $candidate;
}
}
return null;
}
/**
* Retrieve all siblings of a given model.
*
* @param ModelInterface $model The model for which the siblings shall be retrieved from.
* @param string|null $sortingProperty The property name to use for sorting.
* @param ModelIdInterface|null $parentId The (optional) parent id to use.
*
* @return CollectionInterface
*
*/
public function collectSiblingsOf(
ModelInterface $model,
$sortingProperty = null,
?ModelIdInterface $parentId = null
) {
$registry = $this->environment->getBaseConfigRegistry();
assert($registry instanceof BaseConfigRegistryInterface);
$config = $registry->getBaseConfig($parentId);
// Add the parent filter.
$this->addParentFilter($model, $config);
if (null !== $sortingProperty) {
$config->setSorting([$sortingProperty => 'ASC']);
}
// Handle grouping.
$definition = $this->environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
/** @var Contao2BackendViewDefinitionInterface $viewDefinition */
$viewDefinition = $definition->getDefinition(Contao2BackendViewDefinitionInterface::NAME);
if ($viewDefinition instanceof Contao2BackendViewDefinitionInterface) {
$listingConfig = $viewDefinition->getListingConfig();
/** @psalm-suppress DeprecatedMethod */
$sortingProperties = \array_keys($listingConfig->getDefaultSortingFields());
$sortingPropertyIndex = \array_search($sortingProperty, $sortingProperties);
if (false !== $sortingPropertyIndex && $sortingPropertyIndex > 0) {
$sortingProperties = \array_slice($sortingProperties, 0, $sortingPropertyIndex);
$filters = $config->getFilter();
assert(\is_array($filters));
foreach ($sortingProperties as $propertyName) {
$filters[] = [
'operation' => '=',
'property' => $propertyName,
'value' => $model->getProperty($propertyName)
];
}
$config->setFilter($filters);
}
}
$dataProvider = $this->environment->getDataProvider($model->getProviderName());
assert($dataProvider instanceof DataProviderInterface);
$siblingCollection = $dataProvider->fetchAll($config);
assert($siblingCollection instanceof CollectionInterface);
return $siblingCollection;
}
/**
* Scan for children of a given model.
*
* This method returns all models with child recursion.
*
* @param ModelInterface $model The model to assemble children from.
* @param string $providerName The name of the data provider to fetch children from.
*
* @return array
*/
public function collectChildrenOf(ModelInterface $model, $providerName = '')
{
return $this->internalCollectChildrenOf($model, $providerName, true);
}
/**
* Scan for children of a given model.
*
* This method returns all models without child recursion.
*
* @param ModelInterface $model The model to assemble children from.
* @param string $providerName The name of the data provider to fetch children from.
*
* @return array
*/
public function collectDirectChildrenOf(ModelInterface $model, $providerName = '')
{
return $this->internalCollectChildrenOf($model, $providerName);
}
/**
* Scan for children of a given model.
*
* This method is ready for mixed hierarchy and will return all children and grandchildren for the given table
* (or originating table of the model, if no provider name has been given) for all levels and parent child
* conditions.
*
* @param ModelInterface $model The model to assemble children from.
* @param string $providerName The name of the data provider to fetch children from.
* @param bool $recursive Determine for recursive sampling. For models with included child models.
*
* @return list<string>
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private function internalCollectChildrenOf(
ModelInterface $model,
string $providerName = '',
bool $recursive = false
) {
if ('' === $providerName) {
$providerName = $model->getProviderName();
}
$ids = ($model->getProviderName() === $providerName) ? [$model->getId()] : [];
// Check all data providers for children of the given element.
$childIds = [];
foreach ($this->relationships->getChildConditions($model->getProviderName()) as $condition) {
$provider = $this->environment->getDataProvider($condition->getDestinationName());
assert($provider instanceof DataProviderInterface);
$config = $provider->getEmptyConfig();
$config->setFilter($condition->getFilter($model));
$result = $provider->fetchAll($config);
assert($result instanceof CollectionInterface);
if (!$recursive && $result->length() === 0) {
return [];
}
foreach ($result as $child) {
/** @var ModelInterface $child */
if (!$recursive && $child->getProviderName() === $providerName) {
$ids[] = $child->getId();
}
if (false === $recursive) {
continue;
}
// Head into recursion.
$childIds[] = $this->collectChildrenOf($child, $providerName);
}
}
return \array_values(\array_merge($ids, ...$childIds));
}
/**
* Search the parent of a model in parented mode.
*
* @param ModelInterface $model The model to search the parent of.
*
* @return ModelInterface|null
*
* @throws DcGeneralInvalidArgumentException When the model does not originate from the child provider.
*/
private function searchParentOfInParentedMode(ModelInterface $model)
{
$this->guardParentProviderDefined();
$defaultProviderName = $this->defaultProviderName;
assert(\is_string($defaultProviderName));
$parentProviderName = $this->parentProviderName;
assert(\is_string($parentProviderName));
$condition = $this->relationships->getChildCondition($parentProviderName, $defaultProviderName);
if (null === $condition) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. Child condition must be defined!'
);
}
$parentProvider = $this->parentProvider;
assert($parentProvider instanceof DataProviderInterface);
if (null !== ($inverseFilter = $condition->getInverseFilterFor($model))) {
return $parentProvider->fetch($parentProvider->getEmptyConfig()->setFilter($inverseFilter));
}
$parentCollection = $parentProvider->fetchAll($parentProvider->getEmptyConfig());
assert($parentCollection instanceof CollectionInterface);
foreach ($parentCollection as $candidate) {
if ($condition->matches($candidate, $model)) {
return $candidate;
}
}
return null;
}
/**
* Search the parent of a model in hierarchical mode.
*
* @param ModelInterface $model The model to search the parent of.
*
* @return ModelInterface|null
*
* @throws DcGeneralInvalidArgumentException When a root model has been passed.
*/
private function searchParentOfInHierarchical(ModelInterface $model)
{
$this->guardRootProviderDefined();
foreach ($this->relationships->getChildConditions() as $condition) {
// Skip conditions where the destination is not the provider
if (
$this->defaultProviderName !== $condition->getDestinationName()
|| $this->defaultProviderName !== $condition->getSourceName()
) {
continue;
}
if (null === ($inverseFilter = $condition->getInverseFilterFor($model))) {
continue;
}
$provider = $this->environment->getDataProvider($condition->getSourceName());
assert($provider instanceof DataProviderInterface);
$config = $provider->getEmptyConfig()->setFilter($inverseFilter);
$parent = $provider->fetch($config);
if (null !== $parent) {
return $parent;
}
}
// Start from the root data provider and walk through the whole tree.
// To speed up, some conditions have an inverse filter - we should use them!
$rootProvider = $this->rootProvider;
assert($rootProvider instanceof DataProviderInterface);
$rootCondition = $this->rootCondition;
assert($rootCondition instanceof RootConditionInterface);
$config = $rootProvider->getEmptyConfig()->setFilter($rootCondition->getFilterArray());
$parentCollection = $rootProvider->fetchAll($config);
assert($parentCollection instanceof CollectionInterface);
return $this->searchParentOfIn($model, $parentCollection);
}
/**
* Add the parent filter matching the parent of a model.
*
* @param ModelInterface $model The model to search the parent for.
* @param ConfigInterface $config The configuration to add the parent filter to.
*
* @return void
*
* @throws DcGeneralRuntimeException Parent could not be found, are the parent child conditions correct.
* @throws DcGeneralInvalidArgumentException Invalid configuration. Child condition must be defined.
*/
private function addParentFilter(ModelInterface $model, $config)
{
// Not hierarchical, nothing to do.
if (BasicDefinitionInterface::MODE_HIERARCHICAL !== $this->definitionMode) {
return;
}
// Root model?
if ($this->isRootModel($model)) {
$rootCondition = $this->rootCondition;
assert($rootCondition instanceof RootConditionInterface);
$config->setFilter($rootCondition->getFilterArray());
return;
}
// Determine the hard way now.
$parent = $this->searchParentOf($model);
if (!$parent instanceof ModelInterface) {
throw new DcGeneralRuntimeException(
'Parent could not be found, are the parent child conditions correct?'
);
}
$condition = $this->relationships->getChildCondition($parent->getProviderName(), $model->getProviderName());
if (null === $condition) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. Child condition must be defined!'
);
}
$config->setFilter($condition->getFilter($parent));
}
/**
* Check if the passed model is a root model.
*
* @param ModelInterface $model The model to check.
*
* @return bool
*/
private function isRootModel(ModelInterface $model)
{
return (null !== $this->rootCondition) && $this->rootCondition->matches($model);
}
/**
* Guards that a root provider is defined.
*
* @return void
*
* @throws DcGeneralInvalidArgumentException When not root provider is defined.
*/
private function guardRootProviderDefined(): void
{
if (null === $this->rootProvider) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. The root data provider must be defined!'
);
}
}
/**
* Guards that a parent provider is defined.
*
* @return void
*
* @throws DcGeneralInvalidArgumentException When not root provider is defined.
*/
private function guardParentProviderDefined(): void
{
if (null === $this->parentProvider) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. The parent data provider must be defined!'
);
}
}
/**
* This guard checks if the model belongs to the configured data provider.
*
* @param ModelInterface $model The model to check.
*
* @return void
*
* @throws DcGeneralInvalidArgumentException When model is not for the configured provider.
*/
private function guardModelOriginatesFromProvider(ModelInterface $model): void
{
if ($this->defaultProviderName === $model->getProviderName()) {
return;
}
throw new DcGeneralInvalidArgumentException(
'Model originates from ' . $model->getProviderName() .
' but is expected to be from ' . ($this->defaultProviderName ?? '') .
' can not determine parent.'
);
}
}