-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
RelationalTableGateway.php
1616 lines (1387 loc) · 65.7 KB
/
RelationalTableGateway.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 Directus\Database\TableGateway;
use Directus\Database\Exception;
use Directus\Database\Object\Column;
use Directus\Database\Object\Table;
use Directus\Database\Query\Builder;
use Directus\Database\RowGateway\BaseRowGateway;
use Directus\Database\TableSchema;
use Directus\Util\ArrayUtils;
use Directus\Util\DateUtils;
use Directus\Util\StringUtils;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Predicate\PredicateInterface;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\TableGateway\TableGateway;
class RelationalTableGateway extends BaseTableGateway
{
const ACTIVITY_ENTRY_MODE_DISABLED = 0;
const ACTIVITY_ENTRY_MODE_PARENT = 1;
const ACTIVITY_ENTRY_MODE_CHILD = 2;
protected $toManyCallStack = [];
/**
* @var array
*/
protected $defaultEntriesSelectParams = [
'order' => ['sort' => 'ASC'],
'limit' => 200,
'offset' => 0,
'skip' => null,
'search' => null,
'depth' => 1,
'status' => null
];
protected $operatorShorthand = [
'eq' => ['operator' => 'equal_to', 'not' => false],
'=' => ['operator' => 'equal_to', 'not' => false],
'neq' => ['operator' => 'equal_to', 'not' => true],
'!=' => ['operator' => 'equal_to', 'not' => true],
'<>' => ['operator' => 'equal_to', 'not' => true],
'in' => ['operator' => 'in', 'not' => false],
'nin' => ['operator' => 'in', 'not' => true],
'lt' => ['operator' => 'less_than', 'not' => false],
'lte' => ['operator' => 'less_than_or_equal', 'not' => false],
'gt' => ['operator' => 'greater_than', 'not' => false],
'gte' => ['operator' => 'greater_than_or_equal', 'not' => false],
'nlike' => ['operator' => 'like', 'not' => true],
'contains' => ['operator' => 'like'],
'ncontains' => ['operator' => 'like', 'not' => true],
'<' => ['operator' => 'less_than', 'not' => false],
'<=' => ['operator' => 'less_than_or_equal', 'not' => false],
'>' => ['operator' => 'greater_than', 'not' => false],
'>=' => ['operator' => 'greater_than_or_equal', 'not' => false],
'nnull' => ['operator' => 'null', 'not' => true],
'nempty' => ['operator' => 'empty', 'not' => true],
'nbetween' => ['operator' => 'between', 'not' => true],
];
public function manageRecordUpdate($tableName, $recordData, $activityEntryMode = self::ACTIVITY_ENTRY_MODE_PARENT, &$childLogEntries = null, &$parentCollectionRelationshipsChanged = false, $parentData = [])
{
$TableGateway = $this;
if ($tableName !== $this->table) {
$TableGateway = new RelationalTableGateway($tableName, $this->adapter, $this->acl);
}
$recordIsNew = !array_key_exists($TableGateway->primaryKeyFieldName, $recordData);
$tableSchema = TableSchema::getTableSchema($tableName);
$currentUserId = $this->acl ? $this->acl->getUserId() : null;
$currentUserGroupId = $this->acl ? $this->acl->getGroupId() : null;
// Upload file if necessary
$TableGateway->copyFiles($tableName, $recordData);
// Delete file if necessary
$TableGateway->deleteFiles($tableName, $recordData);
//Dont do for directus users since id is pk
if ($recordIsNew && $tableName != 'directus_users') {
$cmsOwnerColumnName = $this->acl->getCmsOwnerColumnByTable($tableName);
if ($cmsOwnerColumnName) {
$recordData[$cmsOwnerColumnName] = $currentUserId;
}
}
//Dont let non-admins make admins
if ($tableName == 'directus_users' && $currentUserGroupId != 1) {
if (isset($recordData['group']) && $recordData['group']['id'] == 1) {
unset($recordData['group']);
}
}
$thisIsNested = ($activityEntryMode == self::ACTIVITY_ENTRY_MODE_CHILD);
// Recursive functions will change this value (by reference) as necessary
// $nestedCollectionRelationshipsChanged = $thisIsNested ? $parentCollectionRelationshipsChanged : false;
$nestedCollectionRelationshipsChanged = false;
if ($thisIsNested) {
$nestedCollectionRelationshipsChanged = &$parentCollectionRelationshipsChanged;
}
// Recursive functions will append to this array by reference
// $nestedLogEntries = $thisIsNested ? $childLogEntries : [];
$nestedLogEntries = [];
if ($thisIsNested) {
$nestedLogEntries = &$childLogEntries;
}
// Update and/or Add Many-to-One Associations
$parentRecordWithForeignKeys = $TableGateway->addOrUpdateManyToOneRelationships($tableSchema, $recordData, $nestedLogEntries, $nestedCollectionRelationshipsChanged);
// Merge the M21 foreign keys into the recordData array
$recordData = array_merge($recordData, $parentRecordWithForeignKeys);
// If more than the record ID is present.
$newRecordObject = null;
$parentRecordChanged = $this->recordDataContainsNonPrimaryKeyData($parentRecordWithForeignKeys); // || $recordIsNew;
if ($parentRecordChanged) {
// Update the parent row, w/ any new association fields replaced by their IDs
$newRecordObject = $TableGateway
->addOrUpdateRecordByArray($parentRecordWithForeignKeys);
if (!$newRecordObject) {
return [];
}
if ($newRecordObject) {
$newRecordObject = $newRecordObject->toArray();
}
}
// Do it this way, because & byref for outcome of ternary operator spells trouble
$draftRecord = &$parentRecordWithForeignKeys;
if ($recordIsNew) {
$draftRecord = &$newRecordObject;
}
// Restore X2M relationship / alias fields to the record representation & process these relationships.
$collectionColumns = $tableSchema->getAliasColumns();
foreach ($collectionColumns as $collectionColumn) {
$colName = $collectionColumn->getId();
if (isset($recordData[$colName])) {
$draftRecord[$colName] = $recordData[$colName];
}
}
// parent
if ($activityEntryMode === self::ACTIVITY_ENTRY_MODE_PARENT) {
$parentData = [
'id' => array_key_exists($this->primaryKeyFieldName, $recordData) ? $recordData[$this->primaryKeyFieldName] : null,
'table_name' => $tableName
];
}
$draftRecord = $TableGateway->addOrUpdateToManyRelationships($tableSchema, $draftRecord, $nestedLogEntries, $nestedCollectionRelationshipsChanged, $parentData);
$rowId = $draftRecord[$this->primaryKeyFieldName];
$columnNames = TableSchema::getAllNonAliasTableColumnNames($tableName);
$TemporaryTableGateway = new TableGateway($tableName, $this->adapter);
$fullRecordData = $TemporaryTableGateway->select(function ($select) use ($rowId, $columnNames) {
$select->where->equalTo($this->primaryKeyFieldName, $rowId);
$select->limit(1)->columns($columnNames);
})->current();
if (!$fullRecordData) {
$recordType = $recordIsNew ? 'new' : 'pre-existing';
throw new \RuntimeException('Attempted to load ' . $recordType . ' record post-insert with empty result. Lookup via row id: ' . print_r($rowId, true));
}
$fullRecordData = (array)$fullRecordData;
$deltaRecordData = $recordIsNew ? [] : array_intersect_key((array)$parentRecordWithForeignKeys, (array)$fullRecordData);
switch ($activityEntryMode) {
// Activity logging is enabled, and I am a nested action
case self::ACTIVITY_ENTRY_MODE_CHILD:
$logEntryAction = $recordIsNew ? DirectusActivityTableGateway::ACTION_ADD : DirectusActivityTableGateway::ACTION_UPDATE;
$childLogEntries[] = [
'type' => DirectusActivityTableGateway::makeLogTypeFromTableName($this->table),
'table_name' => $tableName,
'action' => $logEntryAction,
'user' => $currentUserId,
'datetime' => DateUtils::now(),
'parent_id' => isset($parentData['id']) ? $parentData['id'] : null,
'parent_table' => isset($parentData['table_name']) ? $parentData['table_name'] : null,
'data' => json_encode($fullRecordData),
'delta' => json_encode($deltaRecordData),
'parent_changed' => (int)$parentRecordChanged,
'row_id' => $rowId,
'identifier' => $this->findRecordIdentifier($tableSchema, $fullRecordData),
'logged_ip' => get_request_ip(),// isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''
];
if ($recordIsNew) {
/**
* This is a nested call, creating a new record w/in a foreign collection.
* Indicate by reference that the top-level record's relationships have changed.
*/
$parentCollectionRelationshipsChanged = true;
}
break;
case self::ACTIVITY_ENTRY_MODE_PARENT:
// Does this act deserve a log?
$parentRecordNeedsLog = $nestedCollectionRelationshipsChanged || $parentRecordChanged;
/**
* NESTED QUESTIONS!
* @todo what do we do if the foreign record OF a foreign record changes?
* is that activity entry also directed towards this parent activity entry?
* @todo how should nested activity entries relate to the revision histories of foreign items?
* @todo one day: treat children as parents if this top-level record was not modified.
*/
$recordIdentifier = $this->findRecordIdentifier($tableSchema, $fullRecordData);
// Produce log if something changed.
if ($parentRecordChanged || $nestedCollectionRelationshipsChanged) {
$logEntryAction = $recordIsNew ? DirectusActivityTableGateway::ACTION_ADD : DirectusActivityTableGateway::ACTION_UPDATE;
//If we are updating and active is being set to 0 then we are deleting
if (!$recordIsNew && array_key_exists(STATUS_COLUMN_NAME, $deltaRecordData)) {
if ($deltaRecordData[STATUS_COLUMN_NAME] == STATUS_DELETED_NUM) {
$logEntryAction = DirectusActivityTableGateway::ACTION_DELETE;
}
}
// Save parent log entry
$parentLogEntry = BaseRowGateway::makeRowGatewayFromTableName('id', 'directus_activity', $this->adapter, $this->acl);
$logData = [
'type' => DirectusActivityTableGateway::makeLogTypeFromTableName($this->table),
'table_name' => $tableName,
'action' => $logEntryAction,
'user' => $currentUserId,
'datetime' => DateUtils::now(),
'parent_id' => null,
'data' => json_encode($fullRecordData),
'delta' => json_encode($deltaRecordData),
'parent_changed' => (int)$parentRecordChanged,
'identifier' => $recordIdentifier,
'row_id' => $rowId,
'logged_ip' => get_request_ip(),// isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''
];
$parentLogEntry->populate($logData, false);
$parentLogEntry->save();
// Update & insert nested activity entries
$ActivityGateway = new DirectusActivityTableGateway($this->adapter, $this->acl);
foreach ($nestedLogEntries as $entry) {
$entry['parent_id'] = $rowId;
// @todo ought to insert these in one batch
$ActivityGateway->insert($entry);
}
}
break;
}
// Yield record object
$recordGateway = new BaseRowGateway($TableGateway->primaryKeyFieldName, $tableName, $this->adapter, $this->acl);
$fullRecordData = $this->schemaManager->castRecordValues($fullRecordData, $tableSchema->getColumns());
$recordGateway->populate($fullRecordData, true);
return $recordGateway;
}
/**
* @param string $tableName
* @param array $recordData
*
* @return bool
*/
public function deleteFiles($tableName, $recordData)
{
if ($tableName != 'directus_files') {
return false;
}
if (!isset($recordData[STATUS_COLUMN_NAME]) || $recordData[STATUS_COLUMN_NAME] != STATUS_DELETED_NUM) {
return false;
}
$filesTableGateway = new RelationalTableGateway($tableName, $this->adapter, $this->acl);
$primaryKeyFieldName = $filesTableGateway->primaryKeyFieldName;
$params = [];
$params[$primaryKeyFieldName] = $recordData[$primaryKeyFieldName];
$file = $filesTableGateway->loadItems($params);
$Files = static::$container->get('files');
$Files->delete($file);
return true;
}
/**
* @param string $tableName
* @param array $recordData
*
* @return bool
*/
public function copyFiles($tableName, &$recordData)
{
$schemaArray = TableSchema::getSchemaArray($tableName);
foreach ($schemaArray as $column) {
$colName = $column['id'];
// Ignore absent values & non-arrays
if (!isset($recordData[$colName]) || !is_array($recordData[$colName])) {
continue;
}
$foreignRow = $recordData[$colName];
$colUiType = $column['ui'];
// $isManyToOne = (array_key_exists('relationship', $column) &&
// $column['relationship']['type'] == 'MANYTOONE'
// );
// $isManyToMany = (array_key_exists('relationship', $column) &&
// $column['relationship']['type'] == 'MANYTOMANY'
// );
$foreignTableName = $column['relationship']['related_table'];
// @todo: rewrite this
if ($foreignTableName === 'directus_files' && static::$container) {
// Update/Add foreign record
$Files = static::$container->get('files');
if (count(array_filter($foreignRow, 'is_array')) == count($foreignRow)) {
$index = 0;
foreach ($foreignRow as $row) {
if (!isset($row['data'][$this->primaryKeyFieldName]) && isset($row['data']['data'])) {
if (array_key_exists('type', $row['data']) && strpos($row['data']['type'], 'embed/') === 0) {
$recordData[$colName][$index]['data'] = $Files->saveEmbedData($row['data']);
} else {
$recordData[$colName][$index]['data'] = $Files->saveData($row['data']['data'], $row['data']['name']);
// @NOTE: this is duplicate code from the upload file endpoint
// to maintain the file title.
$recordData[$colName][$index]['data'] = array_merge(
$recordData[$colName][$index]['data'],
ArrayUtils::omit($row['data'], ['data', 'name'])
);
}
}
unset($recordData[$colName][$index]['data']['data']);
$index++;
}
} else {
if (!isset($foreignRow[$this->primaryKeyFieldName]) && isset($foreignRow['data'])) {
if (array_key_exists('type', $foreignRow) && strpos($foreignRow['type'], 'embed/') === 0) {
$recordData[$colName] = $Files->saveEmbedData($foreignRow);
} else {
$recordData[$colName] = $Files->saveData($foreignRow['data'], $foreignRow['name']);
// @NOTE: this is duplicate code from the upload file endpoint
// to maintain the file title.
$recordData[$colName] = array_merge($recordData[$colName], ArrayUtils::omit($foreignRow, ['data', 'name']));
}
}
unset($recordData[$colName]['data']);
}
}
}
return true;
}
/**
* @param Table $schema The table schema array.
* @param array $parentRow The parent record being updated.
* @return array
*/
public function addOrUpdateManyToOneRelationships($schema, $parentRow, &$childLogEntries = null, &$parentCollectionRelationshipsChanged = false)
{
// Create foreign row and update local column with the data id
foreach ($schema->getColumns() as $column) {
$colName = $column['id'];
if (!$column->hasRelationship()) {
continue;
}
// Ignore absent values & non-arrays
if (!isset($parentRow[$colName]) || !is_array($parentRow[$colName])) {
continue;
}
$relationship = $column['relationship'];
$fieldIsCollectionAssociation = in_array($relationship['type'], TableSchema::$association_types);
$lowercaseColumnType = strtolower($relationship['type']);
// Ignore empty OneToMany collections
$fieldIsOneToMany = ('onetomany' === $lowercaseColumnType);
// Ignore non-arrays and empty collections
if (empty($parentRow[$colName])) {
// Once they're managed, remove the foreign collections from the record array
unset($parentRow[$colName]);
continue;
}
$foreignDataSet = $parentRow[$colName];
$colUiType = $column['ui'];
// @TODO: create isManyToOne, etc helpers in Relationship and Column
$isManyToOne = $column->hasRelationship() && $column->getRelationship()->getType() === 'MANYTOONE';
/** Many-to-One */
if ($isManyToOne) {
$foreignRow = $foreignDataSet;
$foreignTableName = null;
$foreignTableName = $column['relationship']['related_table'];
// Update/Add foreign record
if ($this->recordDataContainsNonPrimaryKeyData($foreignRow)) {
$foreignRow = $this->addOrUpdateRecordByArray($foreignRow, $foreignTableName);
}
$parentRow[$colName] = $foreignRow['id'];
} /** One-to-Many, Many-to-Many */
elseif ($fieldIsCollectionAssociation) {
unset($parentRow[$colName]);
}
}
return $parentRow;
}
/**
* @param Table $schema The table schema array.
* @param array $parentRow The parent record being updated.
* @return array
*/
public function addOrUpdateToManyRelationships($schema, $parentRow, &$childLogEntries = null, &$parentCollectionRelationshipsChanged = false, $parentData = [])
{
// Create foreign row and update local column with the data id
foreach ($schema->getColumns() as $column) {
$colName = $column['id'];
if (!$column->hasRelationship()) {
continue;
}
// Ignore absent values & non-arrays
if (!isset($parentRow[$colName]) || !is_array($parentRow[$colName])) {
continue;
}
$relationship = $column['relationship'];
$fieldIsCollectionAssociation = in_array($relationship['type'], TableSchema::$association_types);
$lowercaseColumnType = strtolower($relationship['type']);
// Ignore empty OneToMany collections
$fieldIsOneToMany = ('onetomany' === $lowercaseColumnType);
// Ignore non-arrays and empty collections
if (empty($parentRow[$colName])) {//} || ($fieldIsOneToMany && )) {
// Once they're managed, remove the foreign collections from the record array
unset($parentRow[$colName]);
continue;
}
$foreignDataSet = $parentRow[$colName];
$colUiType = $column['ui'];
/** One-to-Many, Many-to-Many */
if ($fieldIsCollectionAssociation) {
$this->enforceColumnHasNonNullValues($column['relationship'], ['related_table', 'junction_key_right'], $this->table);
$foreignTableName = $column['relationship']['related_table'];
$foreignJoinColumn = $column['relationship']['junction_key_right'];
switch ($lowercaseColumnType) {
/** One-to-Many */
case 'onetomany':
$ForeignTable = new RelationalTableGateway($foreignTableName, $this->adapter, $this->acl);
foreach ($foreignDataSet as &$foreignRecord) {
if (empty($foreignRecord)) {
continue;
}
$foreignSchema = TableSchema::getTableSchema($ForeignTable->getTable());
$hasActiveColumn = $foreignSchema->hasStatusColumn();
$foreignColumn = TableSchema::getColumnSchema($ForeignTable->getTable(), $foreignJoinColumn);
$hasPrimaryKey = isset($foreignRecord[$ForeignTable->primaryKeyFieldName]);
$canBeNull = $foreignColumn->isNullable();
if ($hasPrimaryKey && isset($foreignRecord[STATUS_COLUMN_NAME]) && $foreignRecord[STATUS_COLUMN_NAME] === STATUS_DELETED_NUM) {
if (!$hasActiveColumn && !$canBeNull) {
$Where = new Where();
$Where->equalTo($ForeignTable->primaryKeyFieldName, $foreignRecord[$ForeignTable->primaryKeyFieldName]);
$ForeignTable->delete($Where);
continue;
}
if (!$hasActiveColumn || $canBeNull) {
unset($foreignRecord[STATUS_COLUMN_NAME]);
}
if (!$canBeNull) {
$foreignRecord[$foreignJoinColumn] = $parentRow['id'];
}
}
// only add parent id's to items that are lacking the parent column
if (!array_key_exists($foreignJoinColumn, $foreignRecord)) {
$foreignRecord[$foreignJoinColumn] = $parentRow['id'];
}
$foreignRecord = $this->manageRecordUpdate($foreignTableName, $foreignRecord, self::ACTIVITY_ENTRY_MODE_CHILD, $childLogEntries, $parentCollectionRelationshipsChanged, $parentData);
}
break;
/** Many-to-Many */
case 'manytomany':
/**
* [+] Many-to-Many payloads declare collection items this way:
* $parentRecord['collectionName1'][0-9]['data']; // record key-value array
* [+] With optional association metadata:
* $parentRecord['collectionName1'][0-9]['id']; // for updating a pre-existing junction row
* $parentRecord['collectionName1'][0-9]['active']; // for disassociating a junction via the '0' value
*/
$noDuplicates = isset($column['options']['no_duplicates']) ? $column['options']['no_duplicates'] : 0;
$this->enforceColumnHasNonNullValues($column['relationship'], ['junction_table', 'junction_key_left'], $this->table);
$junctionTableName = $column['relationship']['junction_table'];
$junctionKeyLeft = $column['relationship']['junction_key_left'];
$junctionKeyRight = $column['relationship']['junction_key_right'];
$JunctionTable = new RelationalTableGateway($junctionTableName, $this->adapter, $this->acl);
$ForeignTable = new RelationalTableGateway($foreignTableName, $this->adapter, $this->acl);
foreach ($foreignDataSet as $junctionRow) {
/** This association is designated for removal */
if (isset($junctionRow[STATUS_COLUMN_NAME]) && $junctionRow[STATUS_COLUMN_NAME] == STATUS_DELETED_NUM) {
$Where = new Where;
$Where->equalTo($JunctionTable->primaryKeyFieldName, $junctionRow[$JunctionTable->primaryKeyFieldName]);
$JunctionTable->delete($Where);
// Flag the top-level record as having been altered.
// (disassociating w/ existing M2M collection entry)
$parentCollectionRelationshipsChanged = true;
continue;
} else if (isset($junctionRow['data'][$JunctionTable->primaryKeyFieldName])) {
// Is this a new element?
// if the element `id` exists it's because is not a new element
// and already had its id given.
$Where = new Where;
$Where->equalTo($junctionKeyLeft, $parentRow[$this->primaryKeyFieldName])
->equalTo($junctionKeyRight, $junctionRow['data'][$JunctionTable->primaryKeyFieldName]);
// hard-coded check for sort diff
// @todo fix this
$junctionRowResult = $JunctionTable->select($Where);
if ($junctionRowResult->count()) {
// we are expecting one.
$junctionRowResultArray = $junctionRowResult->toArray();
$junctionRowResultArray = end($junctionRowResultArray);
if (array_key_exists('sort', $junctionRow) && array_key_exists('sort', $junctionRowResultArray)) {
if ($junctionRowResultArray['sort'] === $junctionRow['sort']) {
continue;
}
}
}
}
/** Update foreign record */
$foreignRecord = $ForeignTable->manageRecordUpdate($foreignTableName, $junctionRow['data'], self::ACTIVITY_ENTRY_MODE_CHILD, $childLogEntries, $parentCollectionRelationshipsChanged, $parentData);
// Junction/Association row
$junctionTableRecord = [
$junctionKeyLeft => $parentRow[$this->primaryKeyFieldName],
$foreignJoinColumn => $foreignRecord[$ForeignTable->primaryKeyFieldName]
];
// Update fields on the Junction Record
$junctionTableRecord = array_merge($junctionTableRecord, $junctionRow);
$foreignRecord = (array)$foreignRecord;
$relationshipChanged = $this->recordDataContainsNonPrimaryKeyData($foreignRecord, $ForeignTable->primaryKeyFieldName) ||
$this->recordDataContainsNonPrimaryKeyData($junctionTableRecord, $JunctionTable->primaryKeyFieldName);
// Update Foreign Record
if ($relationshipChanged) {
unset($junctionTableRecord['data']);
$JunctionTable->addOrUpdateRecordByArray($junctionTableRecord, $junctionTableName);
}
}
break;
}
// Once they're managed, remove the foreign collections from the record array
unset($parentRow[$colName]);
}
}
return $parentRow;
}
public function applyDefaultEntriesSelectParams(array $params)
{
$defaultParams = $this->defaultEntriesSelectParams;
// Is not there a sort column?
$tableColumns = array_flip(TableSchema::getTableColumns($this->table, null, true));
if (!array_key_exists('sort', $tableColumns)) {
unset($defaultParams['order']);
}
$params = array_merge($defaultParams, $params);
// convert csv columns into array
$columns = ArrayUtils::get($params, 'columns', []);
if (!is_array($columns)) {
$columns = StringUtils::csv($columns, true);
}
// filter all 'falsy' columns name
$columns = array_filter($columns);
// Stripe whitespaces
$columns = array_map('trim', $columns);
// Add columns to params if it's not empty.
// otherwise remove from params
if (!empty($columns)) {
$params['columns'] = $columns;
} else {
ArrayUtils::remove($params, 'columns');
}
if ($params['limit'] === null) {
ArrayUtils::remove($params, 'limit');
}
array_walk($params, [$this, 'castFloatIfNumeric']);
return $params;
}
/**
* @param array $params
* @param Builder $builder
* @param Table $schema
* @param bool $hasActiveColumn
*
* @return Builder
*/
public function applyParamsToTableEntriesSelect(array $params, Builder $builder, Table $schema, $hasActiveColumn = false)
{
// @TODO: Query Builder Object
foreach($params as $type => $argument) {
$method = 'process' . ucfirst($type);
if (method_exists($this, $method)) {
call_user_func_array([$this, $method], [$builder, $argument]);
}
}
$this->applyLegacyParams($builder, $params);
return $builder;
}
/**
* Relational Getter
* NOTE: equivalent to old DB#get_entries
*/
public function getEntries($params = [])
{
if (!is_array($params)) {
$params = [];
}
return $this->getItems($params);
}
/**
* Get table items
*
* @param array $params
*
* @return array|mixed
*/
public function getItems(array $params = [])
{
$entries = $this->loadItems($params);
// @NOTE: it should has another name
// this evolved into something else
$entries = $this->loadMetadata($entries, ArrayUtils::has($params, 'id'));
return $entries;
}
public function loadMetadata($entriesData, $single = false)
{
return [
'meta' => $this->createMetadata($entriesData, $single),
'data' => $entriesData
];
}
public function createMetadata($entriesData, $single)
{
$singleEntry = $single || !ArrayUtils::isNumericKeys($entriesData);
$tableSchema = TableSchema::getTableSchema($this->table);
$metadata = [
'table' => $tableSchema->getTableName(),
'type' => $singleEntry ? 'item' : 'collection'
];
if (!$singleEntry) {
$metadata = array_merge($metadata, $this->createEntriesMetadata($entriesData, $tableSchema));
}
return $metadata;
}
/**
* Create entries metadata
*
* @param array $entries
* @param Table $tableSchema
* @return array
*/
public function createEntriesMetadata($entries, Table $tableSchema)
{
$metadata = [
'table' => $tableSchema->getTableName(),
'total' => count($entries)
];
if ($tableSchema->hasStatusColumn()) {
$statusCount = $this->countByStatus();
$metadata = array_merge($metadata, $statusCount);
} else {
$metadata['total_entries'] = $this->countTotal();
}
return $metadata;
}
/**
* Load Table entries
*
* @param array $params
* @param \Closure|null $queryCallback
*
* @return mixed
*/
public function loadItems(array $params = [], \Closure $queryCallback = null)
{
// Get table column schema
$tableSchema = $this->getTableSchema();
// table only has one column
// return an empty array
if ($tableSchema === false || count($tableSchema->getColumns()) <= 1) {
return [];
}
$hasActiveColumn = $tableSchema->hasStatusColumn();
// when preview is passed was true, it means returns everything! active, draft and soft-delete.
if (ArrayUtils::has($params, 'preview') && ArrayUtils::get($params, 'preview', false) === true) {
$params['status'] = null;
}
$params = $this->applyDefaultEntriesSelectParams($params);
// @TODO: Create a new TableGateway Query Builder based on Query\Builder
$builder = new Builder($this->getAdapter());
$builder->from($this->getTable());
if (ArrayUtils::has($params, 'columns') || ArrayUtils::has($params, 'columns_visible')) {
$columns = array_unique(array_merge($tableSchema->getPrimaryKeysName(), ArrayUtils::get($params, 'columns', []), ArrayUtils::get($params, 'columns_visible', [])));
} else {
$columns = $tableSchema->getColumnsName();
}
$nonAliasColumns = ArrayUtils::intersection($columns, $tableSchema->getNonAliasColumnsName());
$builder->columns($nonAliasColumns);
$builder = $this->applyParamsToTableEntriesSelect($params, $builder, $tableSchema, $hasActiveColumn);
// If we have user field and do not have big view privileges but have view then only show entries we created
$cmsOwnerId = $this->acl ? $this->acl->getCmsOwnerColumnByTable($this->table) : null;
$currentUserId = $this->acl ? $this->acl->getUserId() : null;
if ($cmsOwnerId && !$this->acl->hasTablePrivilege($this->table, 'bigview') && $this->acl->hasTablePrivilege($this->table, 'view')) {
$builder->whereEqualTo($cmsOwnerId, $currentUserId);
}
if ($queryCallback !== null) {
$builder = $queryCallback($builder);
}
// Run the builder Select with this tablegateway
// to run all the hooks against the result
$results = $this->selectWith($builder->buildSelect())->toArray();
// ==========================================================================
// Perform data casting based on the column types in our schema array
// and Convert dates into ISO 8601 Format
// ==========================================================================
$results = $this->parseRecord($results);
$depth = ArrayUtils::get($params, 'depth', null);
if ($depth !== null) {
$paramColumns = array_merge(ArrayUtils::get($params, 'columns', []), ArrayUtils::get($params, 'columns_visible', []));
$relationalColumns = $tableSchema->getRelationalColumnsName();
if ($paramColumns) {
$relationalColumns = ArrayUtils::intersection($paramColumns, $relationalColumns);
}
$results = $this->loadRelationalDataByDepth($results, (int) $depth, $relationalColumns);
}
// When the params column list doesn't include the primary key
// it should be included because each row gateway expects the primary key
// after all the row gateway are created and initiated it only returns the chosen columns
if (ArrayUtils::has($params, 'columns')) {
$primaryKeysName = $tableSchema->getPrimaryKeysName();
if (!ArrayUtils::contains(array_flip(ArrayUtils::get($params, 'columns')), $primaryKeysName)) {
$results = array_map(function ($entry) use ($primaryKeysName) {
return ArrayUtils::omit($entry, $primaryKeysName);
}, $results);
}
}
if (ArrayUtils::get($params, $this->primaryKeyFieldName)) {
$results = reset($results);
}
return $results ? $results : [];
}
/**
* Load Table entries
*
* Alias of loadItems
*
* @param array $params
* @param \Closure|null $queryCallback
*
* @return mixed
*/
public function loadEntries(array $params = [], \Closure $queryCallback = null)
{
return $this->loadItems($params, $queryCallback);
}
/**
* Loads all relational data by depth level
*
* @param $result
* @param int $maxDepth
* @param array|null $columns
*
* @return array
*/
protected function loadRelationalDataByDepth($result, $maxDepth = 0, array $columns = [])
{
if ((int) $maxDepth <= 0 || !$columns) {
return $result;
}
$columns = $this->getTableSchema()->getColumns($columns);
$maxDepth--;
$result = $this->loadManyToOneRelationships($result, $maxDepth, $columns);
$result = $this->loadOneToManyRelationships($result, $maxDepth, $columns);
$result = $this->loadManyToManyRelationships($result, $maxDepth, $columns);
return $result;
}
/**
* Process Select Filters (Where conditions)
*
* @param Builder $query
* @param array $filters
*/
protected function processFilters(Builder $query, array $filters = [])
{
foreach($filters as $column => $condition) {
$operator = is_array($condition) ? key($condition) : '=';
$value = is_array($condition) ? current($condition) : $condition;
$not = false;
// Get information about the operator shorthand
if (ArrayUtils::has($this->operatorShorthand, $operator)) {
$operatorShorthand = $this->operatorShorthand[$operator];
$operator = ArrayUtils::get($operatorShorthand, 'operator', $operator);
$not = ArrayUtils::get($operatorShorthand, 'not', !$value);
}
$operatorName = StringUtils::underscoreToCamelCase(strtolower($operator), true);
$method = 'where' . ($not === true ? 'Not' : '') . $operatorName;
if (!method_exists($query, $method)) {
continue;
}
$splitOperators = ['between', 'in'];
if (in_array($operator, $splitOperators) && !is_array($value)) {
$value = explode(',', $value);
}
$arguments = [$column, $value];
$relationship = TableSchema::getColumnRelationship($this->getTable(), $column);
if (in_array($operator, ['all', 'has']) && in_array($relationship->getType(), ['ONETOMANY', 'MANYTOMANY'])) {
if ($operator == 'all' && is_string($value)) {
$value = array_map(function ($item) {
return trim($item);
}, explode(',', $value));
} else if ($operator == 'has') {
$value = (int) $value;
}
if ($relationship->getType() == 'ONETOMANY') {
$arguments = [
$this->primaryKeyFieldName,
$relationship->getRelatedTable(),
null,
$relationship->getJunctionKeyRight(),
$value
];
} else {
$arguments = [
$this->primaryKeyFieldName,
$relationship->getJunctionTable(),
$relationship->getJunctionKeyLeft(),
$relationship->getJunctionKeyRight(),
$value
];
}
}
call_user_func_array([$query, $method], $arguments);
}
}
/**
* Process Query search
*
* @param Builder $query
* @param $search
*/
protected function processQ(Builder $query, $search)
{
$columns = TableSchema::getAllTableColumns($this->getTable());
$table = $this->getTable();
foreach ($columns as $column) {
if (!$column->isAlias()) {
$query->orWhereLike($column->getTableName() . '.' . $column->getName(), $search);
}
}
$query->nestOrWhere(function (Builder $query) use ($columns, $search, $table) {
foreach ($columns as $column) {
if ($column->isManyToOne()) {
$relationship = $column->getRelationship();
$relatedTable = $relationship->getRelatedTable();
$relatedTableColumns = TableSchema::getAllTableColumns($relatedTable);
$query->whereRelational($column->getName(), $relatedTable, $this->primaryKeyFieldName, function (Builder $query) use ($column, $relatedTable, $relatedTableColumns, $search) {
$query->nestOrWhere(function (Builder $query) use ($relatedTableColumns, $relatedTable, $search) {
foreach ($relatedTableColumns as $column) {
if (!$column->isAlias()) {
$query->orWhereLike($column->getTableName() . '.' . $column->getName(), $search);
}
}
});
});
} else if ($column->isOneToMany()) {
$relationship = $column->getRelationship();
$relatedTable = $relationship->getRelatedTable();
$relatedRightColumn = $relationship->getJunctionKeyRight();
$relatedTableColumns = TableSchema::getAllTableColumns($relatedTable);
$query->from($table);
$query->whereRelational($this->primaryKeyFieldName, $relatedTable, null, $relatedRightColumn, function(Builder $query) use ($column, $relatedTable, $relatedTableColumns, $search) {
foreach ($relatedTableColumns as $column) {
if (!$column->isAlias()) {
$query->orWhereLike($column->getName(), $search, false);
}
}
});
} else if ($column->isManyToMany()) {
// @TODO:
}
}
});
}
/**
* Process Select Order
*
* @param Builder $query
* @param array $order