-
Notifications
You must be signed in to change notification settings - Fork 8
/
AbstractDataMapper.php
1633 lines (1463 loc) · 57.8 KB
/
AbstractDataMapper.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
declare(strict_types=1);
namespace OliverKlee\Oelib\Mapper;
use Doctrine\DBAL\Driver\ResultStatement;
use OliverKlee\Oelib\DataStructures\Collection;
use OliverKlee\Oelib\Exception\NotFoundException;
use OliverKlee\Oelib\Model\AbstractModel;
use OliverKlee\Oelib\Testing\TestingFramework;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* This class represents a mapper that maps database record to model instances.
*
* @template M of AbstractModel
*
* @phpstan-type DatabaseColumn string|int|float|bool|null
* @phpstan-type DatabaseRow array<string, DatabaseColumn>
*/
abstract class AbstractDataMapper
{
/**
* @var non-empty-string the name of the database table for this mapper
*/
protected $tableName;
/**
* @var class-string<M> the model class name for this mapper
*/
protected $modelClassName;
/**
* @var non-empty-string a comma-separated list of DB column names to retrieve or "*" for all columns
*/
protected $columns = '*';
/**
* @var IdentityMap a map that holds the models that already
* have been retrieved
*/
protected $map = null;
/**
* @var array<int, true> UIDs of models that are memory-only models that must not be saved,
* using the UIDs as keys and TRUE as value
*/
protected $uidsOfMemoryOnlyDummyModels = [];
/**
* @var array<non-empty-string, class-string<AbstractDataMapper<AbstractModel>>>
* the (possible) relations of the created models in the format DB column name => mapper name
*/
protected $relations = [];
/**
* @var array<int, string> the column names of additional string keys
*/
protected $additionalKeys = [];
/**
* The column names of an additional compound key.
* There can only be one compound key per data mapper.
*
* @var string[]
*/
protected $compoundKeyParts = [];
/**
* @var array<string, array<string, M>> two-dimensional cache for the objects by key:
* [key name][key value] => model
*/
private $cacheByKey = [];
/**
* Cache for the objects by compound key:
* [compound key value] => model
* The column values are concatenated via a dot as compound key value.
*
* @var array<string, M>
*/
protected $cacheByCompoundKey = [];
/**
* @var bool whether database access is denied for this mapper
*/
private $denyDatabaseAccess = false;
/**
* @var TestingFramework|null
*/
protected $testingFramework = null;
/**
* The constructor.
*/
public function __construct()
{
// @phpstan-ignore-next-line We are explicitly testing for a contract violation here.
if ($this->getTableName() === '') {
throw new \InvalidArgumentException(\get_class($this) . '::tableName must not be empty.', 1331319361);
}
// @phpstan-ignore-next-line We are explicitly testing for a contract violation here.
if ($this->columns === '') {
throw new \InvalidArgumentException(\get_class($this) . '::columns must not be empty.', 1331319374);
}
if (!\is_string($this->modelClassName)) {
throw new \InvalidArgumentException(\get_class($this) . '::modelClassName must not be empty.', 1331319378);
}
$this->map = new IdentityMap();
foreach ($this->additionalKeys as $key) {
$this->cacheByKey[$key] = [];
}
}
/**
* Sets the testing framework. During functional tests, this makes sure that records created with this mapper
* will be deleted during cleanUp again.
*/
public function setTestingFramework(TestingFramework $testingFramework): void
{
$this->testingFramework = $testingFramework;
}
/**
* Retrieves a model for the record with the UID $uid. If that particular
* model already is cached in memory, the cached instance is returned.
*
* The model may still be a ghost which will get fully initialized once its
* data is accessed.
*
* Note: This function does not check that a record with the UID $uid
* actually exists in the database.
*
* @param int $uid the UID of the record to retrieve, must be > 0
*
* @return M the model with the UID $uid
*/
public function find(int $uid): AbstractModel
{
try {
/** @var M $model */
$model = $this->map->get($uid);
} catch (NotFoundException $exception) {
$model = $this->createGhost($uid);
}
return $model;
}
/**
* Returns a model for the provided array. If the UID provided with the
* array is already mapped, this yet existing model will be returned
* irrespective of the other provided data, otherwise the model will be
* loaded with the provided data.
*
* @param DatabaseRow $data data for the model to return, must at least contain the UID
*
* @return M model for the given UID, filled with data provided in case it did not have any data in memory before
*/
public function getModel(array $data): AbstractModel
{
if (!isset($data['uid'])) {
throw new \InvalidArgumentException('$data must contain an element "uid".', 1331319491);
}
$model = $this->find((int)$data['uid']);
if ($model->isGhost()) {
$this->fillModel($model, $data);
}
return $model;
}
/**
* Returns a list of models for the provided two-dimensional array with model data.
*
* @param DatabaseRow[] $dataOfModels two-dimensional array,
* each inner array must at least contain the element "uid", may be empty
*
* @return Collection<M>
* Models with the UIDs provided. The models will be filled with the
* data provided in case they did not have any data before,
* otherwise the already loaded data will be used. If $dataOfModels
* was empty, an empty list will be returned.
*
* @see getModel()
*/
public function getListOfModels(array $dataOfModels): Collection
{
/** @var Collection<M> $list */
$list = new Collection();
foreach ($dataOfModels as $modelRecord) {
$list->add($this->getModel($modelRecord));
}
return $list;
}
/**
* Retrieves a model based on the WHERE clause given in the parameter
* $whereClauseParts. Hidden records will be retrieved as well.
*
* @param non-empty-array<string, string|int> $whereClauseParts WHERE clause parts for the record to retrieve,
* each element must consist of a column name as key and a value to search for as value
* (will automatically get quoted), must not be empty
*
* @return M the model
*
* @throws NotFoundException if there is no record in the DB which matches the WHERE clause
*/
protected function findSingleByWhereClause(array $whereClauseParts): AbstractModel
{
// @phpstan-ignore-next-line We are explicitly testing for a contract violation here.
if (empty($whereClauseParts)) {
throw new \InvalidArgumentException('The parameter $whereClauseParts must not be empty.', 1331319506);
}
return $this->getModel($this->retrieveRecord($whereClauseParts));
}
/**
* Checks whether a model with a certain UID actually exists in the database
* and could be loaded.
*
* @param int $uid the UID of the record to retrieve, must be > 0
* @param bool $allowHidden whether hidden records should be allowed to be retrieved
*
* @return bool TRUE if a model with the UID $uid exists in the database,
* FALSE otherwise
*/
public function existsModel(int $uid, bool $allowHidden = false): bool
{
$model = $this->find($uid);
if ($model->isGhost()) {
$this->load($model);
}
return $model->isLoaded() && (!$model->isHidden() || $allowHidden);
}
/**
* Loads a model's data from the database (retrieved by using the
* model's UID) and fills the model with it.
*
* If a model's data cannot be retrieved from the DB, the model will be set
* to the "dead" state.
*
* Note: This method may only be called at most once per model instance.
*
* @param M $model the model to fill, must already have a UID
*
* @throws \InvalidArgumentException if $model has no UID or has been created via getNewGhost
*/
public function load(AbstractModel $model): void
{
if ($this->isModelAMemoryOnlyDummy($model)) {
throw new \InvalidArgumentException(
'This ghost was created via getNewGhost and must not be loaded.',
1331319529
);
}
if (!$model->hasUid()) {
throw new \InvalidArgumentException(
'load must only be called with models that already have a UID.',
1331319554
);
}
try {
$data = $this->retrieveRecordByUid($model->getUid());
$this->fillModel($model, $data);
} catch (NotFoundException $exception) {
$model->markAsDead();
}
}
/**
* Reloads a model's data from the database (retrieved by using the
* model's UID) and fills the model with it.
*
* If the model already has been loaded, any data in it will be overwritten
* (even it the data has not been persisted yet).
*
* If a model's data cannot be retrieved from the DB, the model will be set
* to the "dead" state.
*
* This method may be called more than once per model instance.
*
* @param M $model the model to fill, must already have a UID
*
* @throws \InvalidArgumentException if $model has no UID or has been created via getNewGhost
*/
public function reload(AbstractModel $model): void
{
if ($this->isModelAMemoryOnlyDummy($model)) {
throw new \InvalidArgumentException(
'This ghost was created via getNewGhost and must not be loaded.',
1498659785232
);
}
if (!$model->hasUid()) {
throw new \InvalidArgumentException(
'load must only be called with models that already have a UID.',
1498659789105
);
}
try {
$data = $this->retrieveRecordByUid($model->getUid());
$this->refillModel($model, $data);
} catch (NotFoundException $exception) {
$model->markAsDead();
}
}
/**
* Fills a model with data, including the relations.
*
* This function also updates the cache-by-key.
*
* This method must be called at most once per model instance.
*
* @param M $model the model to fill, needs to have a UID
* @param DatabaseRow $data the model data to process as it comes from the DB
*/
private function fillModel(AbstractModel $model, array $data): void
{
$this->cacheModelByKeys($model, $data);
$this->createRelations($data, $model);
$model->setData($data);
}
/**
* Fills a model with data, including the relations.
*
* This function also updates the cache-by-key.
*
* This method may be called more than once per model instance.
*
* @param M $model the model to fill, needs to have a UID
* @param DatabaseRow $data the model data to process as it comes from the DB
*/
private function refillModel(AbstractModel $model, array $data): void
{
$this->cacheModelByKeys($model, $data);
$this->createRelations($data, $model);
$model->resetData($data);
}
/**
* Processes a model's data and creates any relations that are hidden within
* it using foreign key mapping.
*
* @param array<string, string|int> $data the model data to process, might be modified
* @param M $model the model to create the relations for
*/
protected function createRelations(array &$data, AbstractModel $model): void
{
foreach (array_keys($this->relations) as $key) {
if ($this->isOneToManyRelationConfigured($key)) {
$this->createOneToManyRelation($data, $key, $model);
} elseif ($this->isManyToOneRelationConfigured($key)) {
$this->createManyToOneRelation($data, $key);
} elseif ($this->isManyToManyRelationConfigured($key)) {
$this->createMToNRelation($data, $key, $model);
} else {
$this->createCommaSeparatedRelation($data, $key, $model);
}
}
}
/**
* Retrieves the configuration of a relation from the TCA.
*
* @param non-empty-string $key the key of the relation to retrieve
*
* @return array<string, string> configuration for that relation, will not be empty if the TCA is valid
*
* @throws \BadMethodCallException
*/
private function getRelationConfigurationFromTca(string $key): array
{
$tca = $this->getTcaForTable($this->getTableName());
if (!isset($tca['columns'][$key])) {
throw new \BadMethodCallException(
'In the table ' . $this->getTableName() . ', the column ' . $key . ' does not have a TCA entry.',
1331319627
);
}
return $tca['columns'][$key]['config'];
}
/**
* Checks whether the relation is configured in the TCA to be an 1:n
* relation.
*
* @param non-empty-string $key key of the relation
*
* @return bool TRUE if the relation is an 1:n relation, FALSE otherwise
*/
private function isOneToManyRelationConfigured(string $key): bool
{
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
return isset($relationConfiguration['foreign_field'], $relationConfiguration['foreign_table'])
&& $this->possiblyAllowsMultipleSelectionByType($key);
}
/**
* Checks whether the relation is configured in the TCA to be an n:1
* relation.
*
* @param non-empty-string $key key of the relation
*
* @return bool TRUE if the relation is an n:1 relation, FALSE otherwise
*/
private function isManyToOneRelationConfigured(string $key): bool
{
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
$cardinality = (int)($relationConfiguration['maxitems'] ?? 0);
if ($cardinality === 0) {
$cardinality = $this->possiblyAllowsMultipleSelectionByType($key) ? 99999 : 1;
}
return $cardinality === 1;
}
/**
* Checks whether there is a table for an m:n relation configured in the
* TCA.
*
* @param non-empty-string $key key of the relation
*
* @return bool TRUE if the relation's configuration provides an m:n table, FALSE otherwise
*/
private function isManyToManyRelationConfigured(string $key): bool
{
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
return isset($relationConfiguration['MM']);
}
/**
* @param non-empty-string $key
*/
private function possiblyAllowsMultipleSelectionByType(string $key): bool
{
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
if (!\in_array($relationConfiguration['type'], ['select', 'inline', 'group'], true)) {
return false;
}
$renderType = ($relationConfiguration['renderType'] ?? '');
return $renderType !== 'selectSingle';
}
/**
* Creates an 1:n relation using foreign field mapping.
*
* @param array<string, mixed> $data the model data to process, will be modified
* @param non-empty-string $key the key of the data item for which the relation should be created
* @param M $model the model to create the relation for
*
* @throws \UnexpectedValueException
*/
private function createOneToManyRelation(array &$data, string $key, AbstractModel $model): void
{
$modelData = [];
if ((int)$data[$key] > 0) {
if ($this->isModelAMemoryOnlyDummy($model)) {
throw new \InvalidArgumentException(
'This is a memory-only dummy which must not load any one-to-many relations from the database.',
1331319658
);
}
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
$foreignTable = $relationConfiguration['foreign_table'] ?? '';
if ($foreignTable === '') {
throw new \UnexpectedValueException('"foreign_table" is missing in the TCA.', 1646234422);
}
$foreignField = $relationConfiguration['foreign_field'] ?? '';
if (!empty($relationConfiguration['foreign_sortby'])) {
$sortingField = $relationConfiguration['foreign_sortby'];
} elseif (!empty($relationConfiguration['foreign_default_sortby'])) {
$sortingField = $relationConfiguration['foreign_default_sortby'];
} else {
$sortingField = '';
}
$orderBy = $sortingField !== '' ? [$sortingField => 'ASC'] : [];
$queryResult = $this->getConnectionForTable($foreignTable)
->select(['*'], $foreignTable, [$foreignField => (int)$data['uid']], [], $orderBy);
if (\method_exists($queryResult, 'fetchAllAssociative')) {
/** @var DatabaseRow[] $modelData */
$modelData = $queryResult->fetchAllAssociative();
} else {
/** @var DatabaseRow[] $modelData */
$modelData = $queryResult->fetchAll();
}
}
/** @var Collection<AbstractModel> $models */
$models = MapperRegistry::get($this->relations[$key])->getListOfModels($modelData);
$models->setParentModel($model);
$models->markAsOwnedByParent();
$data[$key] = $models;
}
/**
* Creates an n:1 relation using foreign key mapping.
*
* @param array<string, mixed> $data the model data to process, will be modified
* @param string $key the key of the data item for which the relation should be created, must not be empty
*/
private function createManyToOneRelation(array &$data, string $key): void
{
$uid = isset($data[$key]) ? (int)$data[$key] : 0;
$data[$key] = ($uid > 0)
? MapperRegistry::get($this->relations[$key])->find($uid)
: null;
}
/**
* Creates an n:1 relation using a comma-separated list of UIDs.
*
* @param array<string, mixed> $data the model data to process, will be modified
* @param string $key the key of the data item for which the relation should be created, must not be empty
* @param M $model the model to create the relation for
*/
private function createCommaSeparatedRelation(array &$data, string $key, AbstractModel $model): void
{
$list = new Collection();
$list->setParentModel($model);
$uidList = isset($data[$key]) ? trim((string)$data[$key]) : '';
if ($uidList !== '') {
$mapper = MapperRegistry::get($this->relations[$key]);
foreach (GeneralUtility::intExplode(',', $uidList, true) as $uid) {
// Some relations might have a junk 0 in it. We ignore it to avoid crashing.
if ($uid === 0) {
continue;
}
$list->add($mapper->find($uid));
}
}
$data[$key] = $list;
}
/**
* Creates an m:n relation using an m:n table.
*
* Note: This doesn't work for the reverse direction of bidirectional
* relations yet.
*
* @param array<string, mixed> $data the model data to process, will be modified
* @param non-empty-string $key the key of the data item for which the relation should be created
* @param M $model the model to create the relation for
*/
private function createMToNRelation(array &$data, string $key, AbstractModel $model): void
{
$list = new Collection();
$list->setParentModel($model);
if ((int)$data[$key] > 0) {
$mapper = MapperRegistry::get($this->relations[$key]);
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
$mnTable = $relationConfiguration['MM'] ?? '';
if ($mnTable === '') {
throw new \UnexpectedValueException('MM relation information missing.', 1646236363);
}
$rightUid = (int)$data['uid'];
if (isset($relationConfiguration['MM_opposite_field'])) {
$leftColumn = 'uid_local';
$rightColumn = 'uid_foreign';
$orderBy = 'uid_local';
} else {
$leftColumn = 'uid_foreign';
$rightColumn = 'uid_local';
$orderBy = 'sorting';
}
$queryResult = $this->getConnectionForTable($mnTable)
->select([$leftColumn], $mnTable, [$rightColumn => $rightUid], [], [$orderBy => 'ASC']);
if (\method_exists($queryResult, 'fetchAllAssociative')) {
$resultRows = $queryResult->fetchAllAssociative();
} else {
$resultRows = $queryResult->fetchAll();
}
foreach (\array_column($resultRows, $leftColumn) as $relationUid) {
// Some relations might have a junk 0 in it. We ignore it to avoid crashing.
if ((int)$relationUid === 0) {
continue;
}
$list->add($mapper->find((int)$relationUid));
}
}
$data[$key] = $list;
}
/**
* Reads a record from the database (from this mapper's table) by the
* WHERE clause provided. Hidden records will be retrieved as well.
*
* @param array<string, string|int> $whereClauseParts
* WHERE clause parts for the record to retrieve, each element must consist of a column name as key and a
* value to search for as value (will automatically get quoted), must not be empty
*
* @return DatabaseRow the record from the database, will not be empty
*
* @throws NotFoundException if there is no record in the DB which matches the WHERE clause
* @throws NotFoundException if database access is disabled
*/
protected function retrieveRecord(array $whereClauseParts): array
{
if (!$this->hasDatabaseAccess()) {
throw new NotFoundException(
'No record can be retrieved from the database because database' .
' access is disabled for this mapper instance.'
);
}
$tableName = $this->getTableName();
$query = $this->getQueryBuilderForTable($tableName);
$query->getRestrictions()->removeByType(HiddenRestriction::class);
$query->select('*')->from($tableName);
foreach ($whereClauseParts as $identifier => $value) {
$query->andWhere($query->expr()->eq($identifier, $query->createNamedParameter($value)));
}
$result = $query->execute();
if (!$result instanceof ResultStatement) {
throw new \UnexpectedValueException('Expected ResultStatement, got int instead.', 1646321598);
}
if (\method_exists($result, 'fetchAssociative')) {
$data = $result->fetchAssociative();
} else {
$data = $result->fetch();
}
if ($data === false) {
throw new NotFoundException(
'No records found in the table "' . $tableName . '" matching: ' . \json_encode($whereClauseParts)
);
}
return $data;
}
/**
* Reads a record from the database by UID (from this mapper's table).
* Hidden records will be retrieved as well.
*
* @param int $uid the UID of the record to retrieve, must be > 0
*
* @return DatabaseRow the record from the database, will not be empty
*
* @throws NotFoundException if there is no record in the DB with the UID $uid
*/
protected function retrieveRecordByUid(int $uid): array
{
return $this->retrieveRecord(['uid' => $uid]);
}
/**
* Creates a new ghost model with the UID $uid and registers it.
*
* @param int $uid the UID of the to-create ghost
*
* @return M a ghost model with the UID $uid
*/
protected function createGhost(int $uid): AbstractModel
{
$model = GeneralUtility::makeInstance($this->modelClassName);
$model->setUid($uid);
$callback = function (AbstractModel $model): void {
/** @var M $model */
$this->load($model);
};
$model->setLoadCallback($callback);
$this->map->add($model);
return $model;
}
/**
* Creates a new registered ghost with a UID that has not been used in this
* data mapper yet.
*
* Important: As this ghost's UID has nothing to do with the real UIDs in
* the database, this ghost must not be loaded or saved.
*
* @return M a new ghost
*/
public function getNewGhost(): AbstractModel
{
$model = $this->createGhost($this->map->getNewUid());
$this->registerModelAsMemoryOnlyDummy($model);
return $model;
}
/**
* Creates a new registered model with a UID that has not been used in this
* data mapper yet and loads it with the data provided in $data.
*
* The data is considered to be in the same format as in the database,
* eg. m:1 relations are provided as the foreign UID, not as the constituded
* model.
*
* (AbstractModel::setData works differently: There you need to provide the
* data with the relations already being the model/list objects.)
*
* This function should only be used in unit tests for mappers (to avoid
* creating records in the DB when the DB access itself needs not be
* tested).
*
* To use this function for testing relations to the same mapper, the mapper
* needs to be accessed via the mapper registry so object identity is
* ensured.
*
* Important: As this model's UID has nothing to do with the real UIDs in
* the database, this model must not be saved.
*
* @param array<string, string|int> $data the data as it would come from the database, may be empty
*
* @return M a new model loaded with $data
*/
public function getLoadedTestingModel(array $data): AbstractModel
{
$model = $this->getNewGhost();
$this->fillModel($model, $data);
return $model;
}
/**
* Disables all database querying, so model data can only be fetched from memory.
*
* This function is for testing purposes only. For testing, it should be used whenever possible.
*/
public function disableDatabaseAccess(): void
{
$this->denyDatabaseAccess = true;
}
/**
* Checks whether the database may be accessed.
*
* @return bool TRUE is database access is granted, FALSE otherwise
*/
public function hasDatabaseAccess(): bool
{
return !$this->denyDatabaseAccess;
}
/**
* Writes a model to the database. Does nothing if database access is
* denied, if the model is clean, if the model has status dead, virgin or
* ghost, if the model is read-only or if there is no data to set.
*
* @param M $model the model to write to the database
*/
public function save(AbstractModel $model): void
{
if ($this->isModelAMemoryOnlyDummy($model)) {
throw new \InvalidArgumentException(
'This model is a memory-only dummy that must not be saved.',
1331319682
);
}
if (
!$this->hasDatabaseAccess()
|| !$model->isDirty()
|| !$model->isLoaded()
|| $model->isReadOnly()
) {
return;
}
$data = $this->getPreparedModelData($model);
$this->cacheModelByKeys($model, $data);
if ($model->hasUid()) {
$this->getConnection()->update($this->getTableName(), $data, ['uid' => $model->getUid()]);
$this->deleteManyToManyRelationIntermediateRecords($model);
} else {
$this->prepareDataForNewRecord($data);
$tableName = $this->getTableName();
$this->getConnection()->insert($tableName, $data);
$model->setUid((int)$this->getConnection()->lastInsertId($tableName));
$this->map->add($model);
}
if ($model->isDeleted()) {
$model->markAsDead();
} else {
$model->markAsClean();
// We save the 1:n relations after marking this model as clean
// in order to avoid infinite loops when the foreign model tries
// to save this parent.
$this->saveOneToManyRelationRecords($model);
$this->createManyToManyRelationIntermediateRecords($model);
}
}
/**
* Prepares the model's data for the database. Changes the relations into a
* database-applicable format. Sets the timestamp and sets the "crdate" for
* new models.
*
* @param M $model the model to write to the database
*
* @return DatabaseRow the model's data prepared for the database, will not be empty
*/
private function getPreparedModelData(AbstractModel $model): array
{
if (!$model->hasUid()) {
$model->setCreationDate();
}
$model->setTimestamp();
$data = $model->getData();
foreach ($this->relations as $key => $relation) {
if ($this->isOneToManyRelationConfigured($key)) {
$methodName = 'count';
} elseif ($this->isManyToOneRelationConfigured($key)) {
$methodName = 'getUid';
if ($data[$key] instanceof AbstractModel) {
$this->saveManyToOneRelatedModels($data[$key], MapperRegistry::get($relation));
}
} else {
if ($this->isManyToManyRelationConfigured($key)) {
$methodName = 'count';
} else {
$methodName = 'getUids';
}
$relatedData = $data[$key];
if ($relatedData instanceof Collection) {
$this->saveManyToManyAndCommaSeparatedRelatedModels($relatedData, MapperRegistry::get($relation));
}
}
// @phpstan-ignore-next-line This variable method access is okay.
$data[$key] = (isset($data[$key]) && \is_object($data[$key])) ? $data[$key]->{$methodName}() : 0;
}
foreach ($data as &$dataItem) {
if (\is_bool($dataItem)) {
$dataItem = (int)$dataItem;
}
}
return $data;
}
/**
* Prepares the data for models that get newly inserted into the DB.
*
* @param array<string, mixed> $data the data of the record, will be modified
*/
protected function prepareDataForNewRecord(array &$data): void
{
if (!$this->testingFramework instanceof TestingFramework) {
return;
}
$tableName = $this->getTableName();
$this->testingFramework->markTableAsDirty($tableName);
$data[$this->testingFramework->getDummyColumnName($tableName)] = 1;
}
/**
* Saves the related model of an n:1-relation.
*
* @param AbstractModel $model the model to save
* @param AbstractDataMapper<AbstractModel> $mapper the mapper to use for saving
*/
private function saveManyToOneRelatedModels(AbstractModel $model, AbstractDataMapper $mapper): void
{
$mapper->save($model);
}
/**
* Saves the related models of a comma-separated and a regular m:n relation.
*
* @param Collection<AbstractModel> $list the list of models to save
* @param AbstractDataMapper<AbstractModel> $mapper the mapper to use for saving
*/
private function saveManyToManyAndCommaSeparatedRelatedModels(Collection $list, AbstractDataMapper $mapper): void
{
/** @var AbstractModel $model */
foreach ($list as $model) {
$mapper->save($model);
}
}
/**
* Deletes the records in the intermediate table of m:n relations for a
* given model.
*
* @param M $model the model to delete the records in the intermediate table of m:n relations for
*/
private function deleteManyToManyRelationIntermediateRecords(AbstractModel $model): void
{
foreach (array_keys($this->relations) as $key) {
if (!$this->isManyToManyRelationConfigured($key)) {
continue;
}
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
$mnTable = $relationConfiguration['MM'] ?? '';
if ($mnTable === '') {
throw new \UnexpectedValueException('MM relation information missing.', 1646236349);
}
$columnName = isset($relationConfiguration['MM_opposite_field']) ? 'uid_foreign' : 'uid_local';
$this->getConnectionForTable($mnTable)->delete($mnTable, [$columnName => $model->getUid()]);
}
}
/**
* Creates records in the intermediate table of m:n relations for a given model.
*
* @param M $model the model to create the records in the intermediate table of m:n relations for
*/
private function createManyToManyRelationIntermediateRecords(AbstractModel $model): void
{
$data = $model->getData();
foreach (\array_keys($this->relations) as $key) {
if (!($data[$key] instanceof Collection) || !$this->isManyToManyRelationConfigured($key)) {
continue;
}
$sorting = 0;
$relationConfiguration = $this->getRelationConfigurationFromTca($key);
$mnTable = $relationConfiguration['MM'] ?? '';
if ($mnTable === '') {
throw new \UnexpectedValueException('MM relation information missing.', 1646236298);
}
/** @var AbstractModel $relatedModel */
foreach ($data[$key] as $relatedModel) {
if (isset($relationConfiguration['MM_opposite_field'])) {
$uidLocal = $relatedModel->getUid();
$uidForeign = $model->getUid();
} else {
$uidLocal = $model->getUid();
$uidForeign = $relatedModel->getUid();
}
$newData
= $this->getManyToManyRelationIntermediateRecordData($mnTable, $uidLocal, $uidForeign, $sorting);
$this->getConnectionForTable($mnTable)->insert($mnTable, $newData);
$sorting++;
}
}
}
/**
* Saves records that this model relates to as 1:n.
*
* @param M $model the model to save the related records for
*/
private function saveOneToManyRelationRecords(AbstractModel $model): void
{
$data = $model->getData();
foreach ($this->relations as $key => $relation) {
if (!$this->isOneToManyRelationConfigured($key)) {
continue;
}
/** @var Collection<AbstractModel> $relatedModels */
$relatedModels = $data[$key];
if (!($relatedModels instanceof Collection)) {
continue;
}