-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathDefaultController.php
More file actions
1341 lines (1129 loc) · 45.4 KB
/
Copy pathDefaultController.php
File metadata and controls
1341 lines (1129 loc) · 45.4 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
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
/**
* 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 Stefan Heimes <stefan_heimes@hotmail.com>
* @author Tristan Lins <tristan.lins@bit3.de>
* @author Andreas Isaak <andy.jared@googlemail.com>
* @author David Greminger <david.greminger@1up.io>
* @author Oliver Hoff <oliver@hofff.com>
* @author Patrick Kahl <kahl.patrick@googlemail.com>
* @author Stefan Lindecke <github.com@chektrion.de>
* @author Andreas Nölke <zero@brothers-project.de>
* @author David Molineus <david.molineus@netzmacht.de>
* @author Cliff Parnitzky <github@cliff-parnitzky.de>
* @author Sven Baumann <baumann.sv@gmail.com>
* @author Ingolf Steinhardt <info@e-spin.de>
* @author Tim Gatzky <info@tim-gatzky.de>
* @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 Contao\CoreBundle\Intl\Locales;
use Contao\System;
use ContaoCommunityAlliance\DcGeneral\Action;
use ContaoCommunityAlliance\DcGeneral\BaseConfigRegistryInterface;
use ContaoCommunityAlliance\DcGeneral\Clipboard\ClipboardInterface;
use ContaoCommunityAlliance\DcGeneral\Clipboard\Filter;
use ContaoCommunityAlliance\DcGeneral\Clipboard\FilterInterface;
use ContaoCommunityAlliance\DcGeneral\Clipboard\Item;
use ContaoCommunityAlliance\DcGeneral\Clipboard\ItemInterface;
use ContaoCommunityAlliance\DcGeneral\Contao\DataDefinition\Definition\Contao2BackendViewDefinitionInterface;
use ContaoCommunityAlliance\DcGeneral\Contao\View\Contao2BackendView\ViewHelpers;
use ContaoCommunityAlliance\DcGeneral\Data\CollectionInterface;
use ContaoCommunityAlliance\DcGeneral\Data\DataProviderInterface;
use ContaoCommunityAlliance\DcGeneral\Data\DefaultCollection;
use ContaoCommunityAlliance\DcGeneral\Data\LanguageInformationInterface;
use ContaoCommunityAlliance\DcGeneral\Data\ModelId;
use ContaoCommunityAlliance\DcGeneral\Data\ModelIdInterface;
use ContaoCommunityAlliance\DcGeneral\Data\ModelInterface;
use ContaoCommunityAlliance\DcGeneral\Data\ModelManipulator;
use ContaoCommunityAlliance\DcGeneral\Data\MultiLanguageDataProviderInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\ContainerInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Definition\BasicDefinitionInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Definition\Properties\PropertyInterface;
use ContaoCommunityAlliance\DcGeneral\DataDefinition\Definition\View\GroupAndSortingInformationInterface;
use ContaoCommunityAlliance\DcGeneral\DcGeneralEvents;
use ContaoCommunityAlliance\DcGeneral\EnvironmentInterface;
use ContaoCommunityAlliance\DcGeneral\Event\ActionEvent;
use ContaoCommunityAlliance\DcGeneral\Event\PostDuplicateModelEvent;
use ContaoCommunityAlliance\DcGeneral\Event\PostPasteModelEvent;
use ContaoCommunityAlliance\DcGeneral\Event\PreDuplicateModelEvent;
use ContaoCommunityAlliance\DcGeneral\Event\PrePasteModelEvent;
use ContaoCommunityAlliance\DcGeneral\Exception\DcGeneralInvalidArgumentException;
use ContaoCommunityAlliance\DcGeneral\Exception\DcGeneralRuntimeException;
use ContaoCommunityAlliance\DcGeneral\Factory\DcGeneralFactory;
use ContaoCommunityAlliance\Translator\TranslatorInterface;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use UnexpectedValueException;
use function array_keys;
use function in_array;
use function is_int;
use function is_string;
use function trigger_error;
/**
* This class serves as main controller class in dc general.
*
* It holds various methods for data manipulation and retrieval that is non view related.
*
* @SuppressWarnings(PHPMD.ExcessiveClassLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.TooManyFields)
* @SuppressWarnings(PHPMD.TooManyMethods)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @psalm-suppress MissingConstructor
*/
class DefaultController implements ControllerInterface
{
/**
* The attached environment.
*
* @var EnvironmentInterface
*/
private $environment;
/**
* The relationship manager.
*
* @var RelationshipManager
*/
private $relationshipManager;
/**
* The model collector.
*
* @var ModelCollector
*/
private $modelCollector;
/**
* Error message.
*
* @var string
*/
protected $notImplMsg =
'<div style="text-align:center; font-weight:bold; padding:40px;">
The function/view "%s" is not implemented.<br />Please
<a
target="_blank"
style="text-decoration:underline"
href="https://github.com/contao-community-alliance/dc-general/issues">support us</a>
to add this important feature!</div>';
/**
* Throw an exception that an unknown method has been called.
*
* @param string $name Method name.
* @param array $arguments The method arguments.
*
* @return void
*
* @throws DcGeneralRuntimeException Always.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function __call($name, $arguments)
{
throw new DcGeneralRuntimeException('Error Processing Request: ' . $name, 1);
}
/**
* {@inheritDoc}
*/
public function setEnvironment(EnvironmentInterface $environment)
{
$this->environment = $environment;
$definition = $environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
$mode = $definition->getBasicDefinition()->getMode();
assert(is_int($mode));
$this->relationshipManager = new RelationshipManager(
$definition->getModelRelationshipDefinition(),
$mode
);
$this->modelCollector = new ModelCollector($this->environment);
return $this;
}
/**
* {@inheritDoc}
*/
public function getEnvironment()
{
return $this->environment;
}
/**
* {@inheritdoc}
*/
public function handle(Action $action)
{
$event = new ActionEvent($this->getEnvironment(), $action);
$dispatcher = $this->getEnvironment()->getEventDispatcher();
assert($dispatcher instanceof EventDispatcherInterface);
$dispatcher->dispatch($event, DcGeneralEvents::ACTION);
return (string) $event->getResponse();
}
/**
* {@inheritDoc}
*
* @deprecated Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::searchParentOfIn().
*
* @see ModelCollector::searchParentOfIn
*/
public function searchParentOfIn(ModelInterface $model, CollectionInterface $models)
{
// @codingStandardsIgnoreStart
@trigger_error(
'Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::searchParentOfIn().',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$parent = $this->modelCollector->searchParentOfIn($model, $models);
if (null === $parent) {
throw new RuntimeException('Not found');
}
return $parent;
}
/**
* {@inheritDoc}
*
* @throws DcGeneralInvalidArgumentException When a root model has been passed or not in hierarchical mode.
*
* @deprecated Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::searchParentOf().
*
* @see ModelCollector::searchParentOf
*/
public function searchParentOf(ModelInterface $model)
{
// @codingStandardsIgnoreStart
@trigger_error(
'Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::searchParentOf().',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$parent = $this->modelCollector->searchParentOf($model);
if (null === $parent) {
throw new RuntimeException('Not found');
}
return $parent;
}
/**
* {@inheritDoc}
*
* @deprecated Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::collectChildrenOf().
*
* @see ModelCollector::collectChildrenOf
*/
public function assembleAllChildrenFrom($model, $providerName = '')
{
// @codingStandardsIgnoreStart
@trigger_error(
'Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::collectChildrenOf()',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
return $this->modelCollector->collectChildrenOf($model, $providerName);
}
/**
* Retrieve all siblings of a given model.
*
* @param ModelInterface $model The model for which the siblings shall be retrieved from.
* @param null $sortingProperty The property name to use for sorting.
* @param ModelIdInterface|null $parentId The (optional) parent id to use.
*
* @return CollectionInterface
*
* @deprecated Use ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::collectSiblingsOf().
*
* @see ModelCollector::collectSiblingsOf
*/
protected function assembleSiblingsFor(
ModelInterface $model,
$sortingProperty = null,
?ModelIdInterface $parentId = null
) {
// @codingStandardsIgnoreStart
@trigger_error(
'Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::collectSiblingsOf()',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
return $this->modelCollector->collectSiblingsOf($model, $sortingProperty, $parentId);
}
/**
* Retrieve children of a given model.
*
* @param ModelInterface $model The model for which the children shall be retrieved.
* @param string|null $sortingProperty The property name to use for sorting.
*
* @return CollectionInterface
*
* @throws DcGeneralRuntimeException Unable to retrieve children in non-hierarchical mode.
* @throws DcGeneralInvalidArgumentException Invalid configuration. Child condition must be defined.
*/
protected function assembleChildrenFor(ModelInterface $model, $sortingProperty = null)
{
$environment = $this->getEnvironment();
$definition = $environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
$provider = $environment->getDataProvider($model->getProviderName());
assert($provider instanceof DataProviderInterface);
$registry = $environment->getBaseConfigRegistry();
assert($registry instanceof BaseConfigRegistryInterface);
$config = $registry->getBaseConfig();
$relationships = $definition->getModelRelationshipDefinition();
if (BasicDefinitionInterface::MODE_HIERARCHICAL !== $definition->getBasicDefinition()->getMode()) {
throw new DcGeneralRuntimeException('Unable to retrieve children in non hierarchical mode.');
}
$condition = $relationships->getChildCondition($model->getProviderName(), $model->getProviderName());
if (null === $condition) {
throw new DcGeneralInvalidArgumentException(
'Invalid configuration. Child condition must be defined!'
);
}
$config->setFilter($condition->getFilter($model));
if (null !== $sortingProperty) {
$config->setSorting([$sortingProperty => 'ASC']);
}
$childrenCollection = $provider->fetchAll($config);
assert($childrenCollection instanceof CollectionInterface);
return $childrenCollection;
}
/**
* {@inheritDoc}
*/
public function updateModelFromPropertyBag($model, $propertyValues)
{
$environment = $this->getEnvironment();
$definition = $environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
$properties = $definition->getPropertiesDefinition();
ModelManipulator::updateModelFromPropertyBag($properties, $model, $propertyValues);
return $this;
}
/**
* Return all supported languages from the default data data provider.
*
* @param mixed $mixID The id of the item for which to retrieve the valid languages.
*
* @return array
*/
public function getSupportedLanguages($mixID)
{
$environment = $this->getEnvironment();
$dataProvider = $environment->getDataProvider();
// Check if current data provider supports multi language.
if ($dataProvider instanceof MultiLanguageDataProviderInterface) {
$supportedLanguages = $dataProvider->getLanguages($mixID);
} else {
$supportedLanguages = null;
}
// Check if we have some languages.
if (null === $supportedLanguages) {
return [];
}
$translator = $environment->getTranslator();
assert($translator instanceof TranslatorInterface);
// Make an array from the collection.
$languages = [];
$intlLocales = System::getContainer()->get('contao.intl.locales');
assert($intlLocales instanceof Locales);
$labels = $intlLocales->getLocales();
foreach ($supportedLanguages as $value) {
/** @var LanguageInformationInterface $value */
$locale = $value->getLocale();
$languages[$locale] = $labels[$locale];
}
return $languages;
}
/**
* Handle a property in a cloned model.
*
* @param ModelInterface $model The cloned model.
* @param PropertyInterface $property The property to handle.
* @param DataProviderInterface $dataProvider The data provider the model originates from.
*
* @return void
*/
private function handleClonedModelProperty(
ModelInterface $model,
PropertyInterface $property,
DataProviderInterface $dataProvider
) {
$extra = $property->getExtra();
$propName = $property->getName();
// Check doNotCopy.
if (isset($extra['doNotCopy']) && (true === $extra['doNotCopy'])) {
$model->setProperty($propName, null);
return;
}
// Check uniqueness.
if (
isset($extra['unique'])
&& (true === $extra['unique'])
&& !$dataProvider->isUniqueValue($propName, $model->getProperty($propName))
) {
// Implicit "do not copy" unique values, they cannot be unique anymore.
$model->setProperty($propName, null);
}
}
/**
* {@inheritDoc}
*
* @throws DcGeneralRuntimeException For constraint violations.
*/
public function createClonedModel($model)
{
$clone = clone $model;
$clone->setId(null);
$environment = $this->getEnvironment();
$definition = $environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
$properties = $definition->getPropertiesDefinition();
$dataProvider = $environment->getDataProvider($clone->getProviderName());
assert($dataProvider instanceof DataProviderInterface);
foreach (array_keys($clone->getPropertiesAsArray()) as $propName) {
// If the property is not known, remove it.
if (!$properties->hasProperty($propName)) {
continue;
}
$property = $properties->getProperty($propName);
$this->handleClonedModelProperty($clone, $property, $dataProvider);
}
return $clone;
}
/**
* {@inheritDoc}
*
* @throws InvalidArgumentException When the model id is invalid.
*
* @deprecated Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::getModel().
*
* @see ModelCollector::getModel
*/
public function fetchModelFromProvider($modelId, $providerName = null)
{
// @codingStandardsIgnoreStart
@trigger_error(
'Use \ContaoCommunityAlliance\DcGeneral\Controller\ModelCollector::getModel()',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$model = $this->modelCollector->getModel($modelId, $providerName);
if (null === $model) {
throw new RuntimeException('Not found');
}
return $model;
}
/**
* {@inheritDoc}
*/
public function createEmptyModelWithDefaults()
{
$environment = $this->getEnvironment();
$definition = $environment->getDataDefinition();
assert($definition instanceof ContainerInterface);
$dataProvider = $environment->getDataProvider();
assert($dataProvider instanceof DataProviderInterface);
$propertyDefinition = $definition->getPropertiesDefinition();
$properties = $propertyDefinition->getProperties();
$model = $dataProvider->getEmptyModel();
foreach ($properties as $property) {
$propName = $property->getName();
if (null !== $property->getDefaultValue()) {
$model->setProperty($propName, $property->getDefaultValue());
}
}
return $model;
}
/**
* {@inheritDoc}
*/
public function getModelFromClipboardItem(ItemInterface $item)
{
$modelId = $item->getModelId();
if (!$modelId) {
return null;
}
return $this->modelCollector->getModel($modelId);
}
/**
* {@inheritDoc}
*/
public function getModelsFromClipboardItems(array $items)
{
$environment = $this->getEnvironment();
$models = new DefaultCollection();
foreach ($items as $item) {
/** @var ItemInterface $item */
if (null !== ($modelId = $item->getModelId())) {
// Make sure model exists.
if (null !== ($model = $this->modelCollector->getModel($modelId))) {
$models->push($model);
}
continue;
}
$dataProvider = $environment->getDataProvider($item->getDataProviderName());
assert($dataProvider instanceof DataProviderInterface);
$models->push($dataProvider->getEmptyModel());
}
return $models;
}
/**
* {@inheritDoc}
*/
public function getModelsFromClipboard(?ModelIdInterface $parentModelId = null)
{
$environment = $this->getEnvironment();
$dataDefinition = $environment->getDataDefinition();
assert($dataDefinition instanceof ContainerInterface);
$basicDefinition = $dataDefinition->getBasicDefinition();
$modelProviderName = $basicDefinition->getDataProvider();
assert(is_string($modelProviderName));
$clipboard = $environment->getClipboard();
assert($clipboard instanceof ClipboardInterface);
$filter = new Filter();
$filter->andModelIsFromProvider($modelProviderName);
if ($parentModelId) {
$filter->andParentIsFromProvider($parentModelId->getDataProviderName());
} else {
$filter->andHasNoParent();
}
return $this->getModelsFromClipboardItems($clipboard->fetch($filter));
}
/**
* {@inheritDoc}
*/
public function applyClipboardActions(
?ModelIdInterface $source = null,
?ModelIdInterface $after = null,
?ModelIdInterface $into = null,
?ModelIdInterface $parentModelId = null,
?FilterInterface $filter = null,
array &$items = [],
) {
if ($source) {
$actions = $this->getActionsFromSource($source, $parentModelId);
} else {
$actions = $this->fetchModelsFromClipboard($filter, $parentModelId);
}
return $this->doActions($actions, $after, $into, $parentModelId, $items);
}
/**
* Fetch actions from source.
*
* @param ModelIdInterface $source The source id.
* @param ModelIdInterface|null $parentModelId The parent id.
*
* @return array
*
* @throws InvalidArgumentException When the model id is invalid.
*/
private function getActionsFromSource(ModelIdInterface $source, ?ModelIdInterface $parentModelId = null)
{
$definition = $this->getEnvironment()->getDataDefinition();
assert($definition instanceof ContainerInterface);
$basicDefinition = $definition->getBasicDefinition();
assert($basicDefinition instanceof BasicDefinitionInterface);
$dataProvider = $basicDefinition->getDataProvider();
assert(is_string($dataProvider));
$filter = new Filter();
$filter->andModelIsFromProvider($dataProvider);
if (null !== $basicDefinition->getParentDataProvider()) {
$parentDataProvider = $basicDefinition->getDataProvider();
assert(is_string($parentDataProvider));
$filter->andParentIsFromProvider($parentDataProvider);
} else {
$filter->andHasNoParent();
}
$filter->andModelIs($source);
$clipboard = $this->getEnvironment()->getClipboard();
assert($clipboard instanceof ClipboardInterface);
$item = $clipboard->fetch($filter)[0] ?? null;
$action = $item ? $item->getAction() : ItemInterface::CUT;
$model = $this->modelCollector->getModel($source);
assert($model instanceof ModelInterface);
return [
[
'model' => $model,
'item' => new Item($action, $parentModelId, ModelId::fromModel($model))
]
];
}
/**
* Fetch actions from the clipboard.
*
* @param FilterInterface|null $filter The clipboard filter.
* @param ModelIdInterface|null $parentModelId The parent id.
*
* @return array
*/
private function fetchModelsFromClipboard(?FilterInterface $filter = null, ?ModelIdInterface $parentModelId = null)
{
$environment = $this->getEnvironment();
assert($environment instanceof EnvironmentInterface);
$dataDefinition = $environment->getDataDefinition();
assert($dataDefinition instanceof ContainerInterface);
if (!$filter) {
$filter = new Filter();
}
if ($filter instanceof Filter) {
$basicDefinition = $dataDefinition->getBasicDefinition();
$modelProviderName = $basicDefinition->getDataProvider();
assert(is_string($modelProviderName));
$filter->andModelIsFromProvider($modelProviderName);
if ($parentModelId) {
$filter->andParentIsFromProvider($parentModelId->getDataProviderName());
} else {
$filter->andHasNoParent();
}
}
$clipboard = $environment->getClipboard();
assert($clipboard instanceof ClipboardInterface);
$items = $clipboard->fetch($filter);
$actions = [];
foreach ($items as $item) {
$model = null;
if (!$item->isCreate() && null !== ($model = $item->getModelId())) {
$model = $this->modelCollector->getModel((string) $model->getId(), $item->getDataProviderName());
}
$actions[] = [
'model' => $model,
'item' => $item,
];
}
return $actions;
}
/**
* Effectively do the actions.
*
* @param array $actions The action's collection.
* @param ModelIdInterface|null $after The previous model id.
* @param ModelIdInterface|null $into The hierarchical parent model id.
* @param ModelIdInterface|null $parentModelId The parent model id.
* @param array $items Write-back clipboard items.
*
* @return CollectionInterface
*/
private function doActions(
array $actions,
?ModelIdInterface $after = null,
?ModelIdInterface $into = null,
?ModelIdInterface $parentModelId = null,
array &$items = []
) {
if ($parentModelId) {
$parentModel = $this->modelCollector->getModel($parentModelId);
} else {
$parentModel = null;
}
// Holds models, that need deep-copy.
$deepCopyList = [];
// Apply to create and copy actions.
foreach ($actions as &$action) {
$this->applyAction($action, $deepCopyList, $parentModel);
}
unset($action);
// When pasting after another model, apply same grouping information.
$this->ensureSameGrouping($actions, $after);
// Now apply sorting and persist all models.
$models = $this->sortAndPersistModels($actions, $after, $into, $parentModelId, $items);
// At last, go ahead with the deep copy.
$this->doDeepCopy($deepCopyList);
return $models;
}
/**
* Apply the action onto the model.
*
* This will create or clone the model in the action.
*
* @param array $action The action, containing a model and an item.
* @param array $deepCopyList A list of models that need deep copy.
* @param ModelInterface|null $parentModel The parent model.
*
* @return void
*
*/
private function applyAction(array &$action, array &$deepCopyList, ?ModelInterface $parentModel = null)
{
/** @var ModelInterface|null $model */
$model = $action['model'];
/** @var ItemInterface $item */
$item = $action['item'];
$isDeepCopy = false;
if ($item->isCreate()) {
// create new model
$model = $this->createEmptyModelWithDefaults();
} elseif ($item->isCopy() || $isDeepCopy = $item->isDeepCopy()) {
assert($model instanceof ModelInterface);
// copy model
$model = $this->modelCollector->getModel(ModelId::fromModel($model));
assert($model instanceof ModelInterface);
$clonedModel = $this->doCloneAction($model);
if ($isDeepCopy) {
$deepCopyList[] = [
'origin' => $model,
'model' => $clonedModel,
];
}
$model = $clonedModel;
}
if (!$model) {
throw new UnexpectedValueException(
'Invalid clipboard action entry, no model created. ' . $item->getAction()
);
}
if ($parentModel) {
$this->relationshipManager->setParent($model, $parentModel);
}
$action['model'] = $model;
}
/**
* Effectively do the clone action on the model.
*
* @param ModelInterface $model The model to clone.
*
* @return ModelInterface Return the cloned model.
*/
private function doCloneAction(ModelInterface $model)
{
$environment = $this->getEnvironment();
$dispatcher = $environment->getEventDispatcher();
assert($dispatcher instanceof EventDispatcherInterface);
// Make a duplicate.
$clonedModel = $this->createClonedModel($model);
// Trigger the pre duplicate event.
$duplicateEvent = new PreDuplicateModelEvent($environment, $clonedModel, $model);
$dispatcher->dispatch($duplicateEvent, $duplicateEvent::NAME);
// And trigger the post event for it.
$duplicateEvent = new PostDuplicateModelEvent($environment, $clonedModel, $model);
$dispatcher->dispatch($duplicateEvent, $duplicateEvent::NAME);
return $clonedModel;
}
/**
* Ensure all models have the same grouping.
*
* @param array $actions The action's collection.
* @param ModelIdInterface|null $after The previous model id.
*
* @return void
*/
private function ensureSameGrouping(array $actions, ?ModelIdInterface $after = null)
{
$environment = $this->getEnvironment();
$groupingMode = ViewHelpers::getGroupingMode($environment);
if (null !== $groupingMode && null !== $after && $after->getId()) {
// when pasting after another item, inherit the grouping field
$groupingField = $groupingMode['property'];
$previous = $this->modelCollector->getModel($after);
assert($previous instanceof ModelInterface);
$groupingValue = $previous->getProperty($groupingField);
foreach ($actions as $action) {
/** @var ModelInterface $model */
$model = $action['model'];
$model->setProperty($groupingField, $groupingValue);
}
}
}
/**
* Apply sorting and persist all models.
*
* @param array $actions The actions collection.
* @param ModelIdInterface|null $after The previous model id.
* @param ModelIdInterface|null $into The hierarchical parent model id.
* @param ModelIdInterface|null $parentModelId The parent model id.
* @param array $items Write-back clipboard items.
*
* @return DefaultCollection
*
*/
private function sortAndPersistModels(
array $actions,
?ModelIdInterface $after = null,
?ModelIdInterface $into = null,
?ModelIdInterface $parentModelId = null,
array &$items = []
) {
$models = $this->createModelCollectionFromActions($actions, $items);
assert($models instanceof CollectionInterface);
$this->triggerPrePasteModel($models);
$this->processPasteAfter($models, $after);
$this->processPasteInto($models, $into);
$this->processPasteTopWithoutReference($models, $after, $into, $parentModelId);
$this->processPasteTopAfterModel($models, $parentModelId);
if ($models->count()) {
throw new DcGeneralRuntimeException('Invalid parameters.');
}
return $models;
}
/**
* Process paste the collection of models after the a model.
*
* @param CollectionInterface $models The collection of models.
* @param ModelIdInterface|null $after The paste after model.
*
* @return void
*/
private function processPasteAfter(CollectionInterface $models, ?ModelIdInterface $after = null)
{
if ($after && $models->count() && $after->getId()) {
$manualSorting = ViewHelpers::getManualSortingProperty($this->getEnvironment());
assert(is_string($manualSorting));
$model = $this->modelCollector->getModel($after);
assert($model instanceof ModelInterface);
$this->pasteAfter($model, $models, $manualSorting);
$this->triggerPostPasteModel($models);
$this->clearModelCollection($models);
}
}
/**
* Process paste the collection of models into the model.
*
* @param CollectionInterface $models The collection of models.
* @param ModelIdInterface|null $into The paste into model.
*
* @return void
*/
private function processPasteInto(CollectionInterface $models, ?ModelIdInterface $into = null)
{
if ($into && $models->count() && $into->getId()) {
$manualSorting = ViewHelpers::getManualSortingProperty($this->getEnvironment());
assert(is_string($manualSorting));
$model = $this->modelCollector->getModel($into);
assert($model instanceof ModelInterface);
$this->pasteInto($model, $models, $manualSorting);
$this->triggerPostPasteModel($models);
$this->clearModelCollection($models);
}
}
/**
* Process paste the content of the clipboard onto the top after a model without reference.
*
* @param CollectionInterface $models The collection of models.
* @param ModelIdInterface|null $after The previous model id.
* @param ModelIdInterface|null $into The hierarchical parent model id.
* @param ModelIdInterface|null $parent The parent model id.
*
* @return void
*/
private function processPasteTopWithoutReference(
CollectionInterface $models,
?ModelIdInterface $after = null,
?ModelIdInterface $into = null,
?ModelIdInterface $parent = null
) {
if (
$models->count()
&& (($after && (0 === (int) $after->getId()))
|| ($into && (0 === (int) $into->getId())))
) {
$manualSorting = ViewHelpers::getManualSortingProperty($this->getEnvironment());
assert(is_string($manualSorting));
$dataDefinition = $this->getEnvironment()->getDataDefinition();
assert($dataDefinition instanceof ContainerInterface);
if (BasicDefinitionInterface::MODE_HIERARCHICAL === $dataDefinition->getBasicDefinition()->getMode()) {
$this->relationshipManager->setAllRoot($models);
}
$this->pasteTop($models, $manualSorting, $parent);
$this->triggerPostPasteModel($models);
$this->clearModelCollection($models);
}
}
/**
* Process paste the content of the clipboard onto the top after a model.
*
* @param CollectionInterface $models The collection of models.
* @param ModelIdInterface|null $parent The parent model id.
*
* @return void
*/
private function processPasteTopAfterModel(CollectionInterface $models, ?ModelIdInterface $parent = null)
{
if ($parent && $models->count()) {
$manualSorting = ViewHelpers::getManualSortingProperty($this->getEnvironment());
if (null !== $manualSorting) {