-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathAbstractModelAPI.php
More file actions
1932 lines (1703 loc) · 72.2 KB
/
AbstractModelAPI.php
File metadata and controls
1932 lines (1703 loc) · 72.2 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
namespace Hashtopolis\inc\apiv2\common;
use Hashtopolis\dba\MassUpdateSet;
use Hashtopolis\inc\apiv2\error\ErrorHandler;
use Hashtopolis\inc\apiv2\error\HttpConflict;
use Hashtopolis\inc\apiv2\error\HttpError;
use Hashtopolis\inc\apiv2\error\HttpForbidden;
use Hashtopolis\inc\apiv2\error\InternalError;
use Hashtopolis\inc\apiv2\error\ResourceNotFoundError;
use Hashtopolis\inc\HTException;
use JsonException;
use PDOException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Hashtopolis\dba\AbstractModelFactory;
use Hashtopolis\dba\JoinFilter;
use Hashtopolis\dba\Factory;
use Hashtopolis\dba\ContainFilter;
use Hashtopolis\dba\LimitFilter;
use Hashtopolis\dba\OrderFilter;
use Hashtopolis\dba\PaginationFilter;
use Hashtopolis\dba\QueryFilter;
use Hashtopolis\inc\Util;
abstract class AbstractModelAPI extends AbstractBaseAPI {
abstract static public function getDBAClass();
abstract protected function createObject(array $data): int;
abstract protected function deleteObject(object $object): void;
/**
* Available 'expand' parameters on $object
*/
public static function getExpandables(): array {
return array_merge(array_keys(static::getToOneRelationships()), array_keys(static::getToManyRelationships()));
}
/**
* Fetch objects for $expand on $objects
* @throws InternalError
* @throws HttpError
*/
protected static function fetchExpandObjects(array $objects, string $expand): mixed {
//disabled the check because with intermediate objects its possible to fetch a different model
/* Ensure we receive the proper type */
// $baseModel = static::getDBAClass();
// array_walk($objects, function ($obj) use ($baseModel) {
// assert($obj instanceof $baseModel);
// });
$toOneRelationships = static::getToOneRelationships();
if (array_key_exists($expand, $toOneRelationships)) {
$relationFactory = self::getModelFactory($toOneRelationships[$expand]['relationType']);
if (array_key_exists('junctionTableType', $toOneRelationships[$expand])) {
$junctionTableFactory = self::getModelFactory($toOneRelationships[$expand]['junctionTableType']);
return self::getManyToOneRelationViaIntermediate(
$objects,
$toOneRelationships[$expand]['junctionTableJoinField'],
$junctionTableFactory,
$relationFactory,
$toOneRelationships[$expand]['relationKey'],
$toOneRelationships[$expand]['parentKey']
);
};
return self::getForeignKeyRelation(
$objects,
$toOneRelationships[$expand]['key'],
$relationFactory,
$toOneRelationships[$expand]['relationKey'],
);
};
$toManyRelationships = static::getToManyRelationships();
if (array_key_exists($expand, $toManyRelationships)) {
$relationFactory = self::getModelFactory($toManyRelationships[$expand]['relationType']);
/* Associative entity */
if (array_key_exists('junctionTableType', $toManyRelationships[$expand])) {
$junctionTableFactory = self::getModelFactory($toManyRelationships[$expand]['junctionTableType']);
return self::getManyToManyRelationViaIntermediate(
$objects,
$toManyRelationships[$expand]['key'],
$junctionTableFactory,
$toManyRelationships[$expand]['junctionTableFilterField'],
$relationFactory,
$toManyRelationships[$expand]['relationKey'],
);
};
return self::getManyToOneRelation(
$objects,
$toManyRelationships[$expand]['key'],
$relationFactory,
$toManyRelationships[$expand]['relationKey'],
);
};
throw new InternalError("Internal error: Expansion '$expand' not implemented!");
}
/**
* @throws HttpError
*/
final protected static function getFactory(): object {
return self::getModelFactory(static::getDBAclass());
}
/**
* Get features based on form fields and DBA model features
*/
final protected function getFeatures(): array {
return array_merge(
parent::getFeatures(),
call_user_func($this->getDBAclass() . '::getFeatures'),
);
}
/**
* Separate get features function to get features without the form fields. This is needed to generate the openAPI documentation
* TODO: This function could probably be used in the patch endpoints as well, since form fields are not relevant there.
*/
public function getFeaturesWithoutFormfields(): array {
$features = call_user_func($this->getDBAclass() . '::getFeatures');
return $this->mapFeatures($features);
}
/**
* Find primary key for another DBA object
* A little bit hacky because the getPrimaryKey function in dbaClass is not static
*
* @param string $dbaClass is the dba class to get the primary key from
* @throws InternalError
*/
protected function getPrimaryKeyOther(string $dbaClass): string {
$features = $this->getFeaturesOther($dbaClass);
# Work-around required since getPrimaryKey is not static in dba/models/*.php
foreach ($features as $key => $value) {
if ($value['pk']) {
return $key;
}
}
throw new InternalError("Internal error: no primary key found");
}
/**
* Retrieve ManyToOne relation for $objects ('parents') of type $targetFactory via 'intermediate'
* of $intermediateFactory joining on $joinField (between 'intermediate' and 'target'). Filtered by
* $filterField at $intermediateFactory.
*
* @param array $objects Objects Fetch relation for selected Objects
* @param string $objectField Field to use as base for $objects
* @param object $intermediateFactory Factory used as intermediate between parentObject and targetObject
* @param object $targetFactory Object properties of objects returned
* @param string $joinField Field to connect 'intermediate' to 'target'
* @param string $parentKey
* @return array $many2One which is a map where the key is the id of the parent object and the value is an array of the included
* objects that are included for this parent object
*/
//A bit hacky solution to get a to one through an intermediate table, currently only used by tasks to include a hashlist through the taskwrapper
//another solution can be to overwrite fetchExpandObjects() in tasks.routes
final protected static function getManyToOneRelationViaIntermediate(
array $objects,
string $objectField,
object $intermediateFactory,
object $targetFactory,
string $joinField,
string $parentKey
): array {
assert($intermediateFactory instanceof AbstractModelFactory);
assert($targetFactory instanceof AbstractModelFactory);
$many2One = array();
/* Retrieve Parent -> Intermediate -> Target objects */
$objectIds = [];
foreach ($objects as $object) {
$kv = $object->getKeyValueDict();
$objectIds[] = $kv[$objectField];
}
$baseFactory = self::getModelFactory(static::getDBAClass());
$qF = new ContainFilter($objectField, $objectIds, $intermediateFactory);
$jF = new JoinFilter($intermediateFactory, $joinField, $joinField);
$jF2 = new JoinFilter($baseFactory, $objectField, $objectField, $intermediateFactory);
$hO = $targetFactory->filter([Factory::FILTER => $qF, Factory::JOIN => [$jF, $jF2]]);
$intermediateObjectList = $hO[$intermediateFactory->getModelName()];
$targetObjectList = $hO[$targetFactory->getModelName()];
$baseObjectList = $hO[$baseFactory->getModelName()];
$intermediateObject = current($intermediateObjectList);
$targetObject = current($targetObjectList);
$baseObject = current($baseObjectList);
while ($intermediateObject && $targetObject && $baseObject) {
$kv = $baseObject->getKeyValueDict();
$many2One[$kv[$parentKey]] = $targetObject;
$intermediateObject = next($intermediateObjectList);
$targetObject = next($targetObjectList);
$baseObject = next($baseObjectList);
}
return $many2One;
}
/**
* Retrieve ForeignKey Relation
*
* @param array $objects Objects Fetch relation for selected Objects
* @param string $objectField Field to use as base for $objects
* @param object $factory Factory used to retrieve objects
* @param string $filterField Filter field of $field to filter against $objects field
*
* @return array
*/
final protected static function getForeignKeyRelation(
array $objects,
string $objectField,
object $factory,
string $filterField
): array {
assert($factory instanceof AbstractModelFactory);
$retval = array();
/* Fetch required objects */
$objectIds = [];
foreach ($objects as $object) {
$kv = $object->getKeyValueDict();
$objectIds[] = $kv[$objectField];
}
$qF = new ContainFilter($filterField, $objectIds, $factory);
$hO = $factory->filter([Factory::FILTER => $qF]);
/* Objects are uniquely identified by fields, create mapping to speed-up further processing */
$f2o = [];
foreach ($hO as $relationObject) {
$f2o[$relationObject->getKeyValueDict()[$filterField]] = $relationObject;
};
/* Map objects */
foreach ($objects as $object) {
$fieldId = $object->getKeyValueDict()[$objectField];
if (array_key_exists($fieldId, $f2o)) {
$retval[$object->getId()] = $f2o[$fieldId];
}
}
return $retval;
}
/**
* Retrieve ManyToOneRelation (reverse ForeignKey)
*
* @param array $objects Objects Fetch relation for selected Objects
* @param string $objectField Field to use as base for $objects
* @param object $factory Factory used to retrieve objects
* @param string $filterField Filter field of $field to filter against $objects field
*
* @return array
*/
final protected static function getManyToOneRelation(
array $objects,
string $objectField,
object $factory,
string $filterField
): array {
assert($factory instanceof AbstractModelFactory);
$retval = array();
/* Fetch required objects */
$objectIds = [];
foreach ($objects as $object) {
$kv = $object->getKeyValueDict();
$objectIds[] = $kv[$objectField];
}
$qF = new ContainFilter($filterField, $objectIds, $factory);
$hO = $factory->filter([Factory::FILTER => $qF]);
/* Map (multiple) objects to base objects */
foreach ($hO as $relationObject) {
$kv = $relationObject->getKeyValueDict();
$retval[$kv[$filterField]][] = $relationObject;
}
return $retval;
}
/**
* Retrieve ManyToOne relation for $objects ('parents') of type $targetFactory via 'intermediate'
* of $intermediateFactory joining on $joinField (between 'intermediate' and 'target'). Filtered by
* $filterField at $intermediateFactory.
*
* @param array $objects Objects Fetch relation for selected Objects
* @param string $objectField Field to use as base for $objects
* @param object $intermediateFactory Factory used as intermediate between parentObject and targetObject
* @param string $filterField Filter field of intermediateObject to filter against $objects field
* @param object $targetFactory Object properties of objects returned
* @param string $joinField Field to connect 'intermediate' to 'target'
* @return array $many2many which is a map where the key is the id of the parent object and the value is an array of the included
* objects that are included for this parent object
*/
final protected static function getManyToManyRelationViaIntermediate(
array $objects,
string $objectField,
object $intermediateFactory,
string $filterField,
object $targetFactory,
string $joinField,
): array {
assert($intermediateFactory instanceof AbstractModelFactory);
assert($targetFactory instanceof AbstractModelFactory);
$many2Many = array();
/* Retrieve Parent -> Intermediate -> Target objects */
$objectIds = [];
foreach ($objects as $object) {
$kv = $object->getKeyValueDict();
$objectIds[] = $kv[$objectField];
}
$qF = new ContainFilter($filterField, $objectIds, $intermediateFactory);
$jF = new JoinFilter($intermediateFactory, $joinField, $joinField);
$hO = $targetFactory->filter([Factory::FILTER => $qF, Factory::JOIN => $jF]);
$intermediateObjectList = $hO[$intermediateFactory->getModelName()];
$targetObjectList = $hO[$targetFactory->getModelName()];
$intermediateObject = current($intermediateObjectList);
$targetObject = current($targetObjectList);
while ($intermediateObject && $targetObject) {
$kv = $intermediateObject->getKeyValueDict();
$many2Many[$kv[$filterField]][] = $targetObject;
$intermediateObject = next($intermediateObjectList);
$targetObject = next($targetObjectList);
}
return $many2Many;
}
/**
* Retrieve permissions based on class and method requested
* @throws HttpForbidden
*/
public function getRequiredPermissions(string $method): array {
$model = $this->getDBAclass();
# Get required permission based on API method type
$required_perm = match (strtoupper($method)) {
"GET" => $model::PERM_READ,
"POST" => $model::PERM_CREATE,
"PATCH" => $model::PERM_UPDATE,
"DELETE" => $model::PERM_DELETE,
default => throw new HttpForbidden("Method '" . $method . "' is not allowed "),
};
return array($required_perm);
}
/**
* API entry point for deletion of single object
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
* @throws HTException
* @throws HttpForbidden
* @throws ResourceNotFoundError
*/
public function deleteOne(Request $request, Response $response, array $args): Response
// TODO how to handle cascading deletes?
// ex. Hash foreignkey to hashlist can't be null, but hashlist delete doesnt cascade to Hash
// Which effectively means that we cant delete a hashlist because of foreign key constraints
// Solution 1: make cascading rules in Database
// Solution 2: implement delete logic in every api model
{
$this->preCommon($request);
$object = $this->doFetch($args['id']);
/* Actually delete object */
$this->deleteObject($object);
return $response->withStatus(204)
->withHeader("Content-Type", "application/json");
}
/**
* Request single object from database & validate permissions
* @throws ResourceNotFoundError
* @throws HttpForbidden
* @throws HttpError
*/
protected function doFetch(string $pk, ?AbstractModelFactory $otherFactory = null): mixed {
if ($otherFactory != null) {
$object = $otherFactory->get($pk);
}
else {
$object = $this->getFactory()->get($pk);
}
if ($object === null) {
throw new ResourceNotFoundError();
}
$group = Factory::getRightGroupFactory()->get($this->getCurrentUser()->getRightGroupId());
if ($group->getPermissions() !== 'ALL' && $otherFactory == null && $this->getSingleACL($this->getCurrentUser(),
$object
) === false) {
throw new HttpForbidden("No access to this object!", 403);
}
return $object;
}
/**
* Additional filtering required for limiting access to objects
*/
protected function getFilterACL(): array {
return [];
}
/**
* Helper function to determine if $resourceRecord is a valid resource record
* returns true if it is a valid resource record and false if it is an invalid resource record
*/
final protected function validateResourceRecord(mixed $resourceRecord): bool {
return (isset($resourceRecord['type']) && is_numeric($resourceRecord['id']));
}
/**
* @throws HttpError
*/
final protected function ResourceRecordArrayToUpdateArray($data, $parentId): array {
$updates = [];
foreach ($data as $item) {
if (!$this->validateResourceRecord($item)) {
$encoded_item = json_encode($item);
throw new HttpError('Invalid resource record given in list! invalid resource record: ' . $encoded_item);
}
$updates[] = new MassUpdateSet($item["id"], $parentId);
}
return $updates;
}
protected static function calculate_next_cursor(string|int $cursor, bool $ascending = true): int|string {
if (is_int($cursor)) {
if ($ascending) {
return $cursor + 1;
}
else {
return $cursor - 1;
}
}
elseif (is_string($cursor)) {
$len = strlen($cursor);
$lastChar = $cursor[$len - 1];
$ord = ord($lastChar);
if ($ascending) {
if ($len == 0) {
return '~';
}
if ($ord < 126) {
return substr($cursor, 0, $len - 1) . chr($ord + 1);
}
else {
return $cursor . '!'; // '!' is lowest printable ascii
}
}
else {
if ($len == 0) {
return "";
}
if ($ord > 33) {
return substr($cursor, 0, $len - 1) . chr($ord - 1);
}
else {
return substr($cursor, 0, $len - 1);
}
}
}
else {
throw new HttpError("Internal error", 500);
}
}
/**
* The cursor is base64 encoded in the following json format:
* {"primary":{"isSlowHash":0},"secondary":{"hashTypeId":10810}}
* This contains a primary filter which is the main sorting filter, but to handle duplicates, it has an optional
* secondary filter for when the primary filter is not unique. This way there is an unique secondary filter to
* handle tie breaks.
*
* @param mixed $primaryFilter The main filter that is sorted on
* @param mixed $primaryId the value of the primaryFilter
* @param bool $hasSecondaryFilter This is a boolean to set whether there is a secondary filter
* @param mixed $secondaryFilter An unique secondary filter to use as a tiebreaker when the main filter is not unique
* @param object $secondaryId The value of the secondary filter
* @return string a base64 encoded json string that contains the filters.
*/
protected static function build_cursor($primaryFilter, $primaryId, $hasSecondaryFilter = false, $secondaryFilter = null, $secondaryId = null): string {
$cursor = ["primary" => [$primaryFilter => $primaryId]];
if ($hasSecondaryFilter) {
assert($secondaryId !== null && $secondaryFilter !== null,
"Secondary id and filter should be set"
);
//Add the primary key as a secondary cursor to guarantee the cursor is unique
$cursor["secondary"] = [$secondaryFilter => $secondaryId];
}
$json = json_encode($cursor);
return urlencode(base64_encode($json));
}
/**
* Function to decode the cursor from base64 format
*
* @param string $encoded_cursor in base64 format
*
* @return array the decoded cursor in a json string format
* @throws HttpError
*/
protected static function decode_cursor(string $encoded_cursor): array {
$json = base64_decode($encoded_cursor);
if ($json == false) {
throw new HttpError("Invallid pagination cursor, cursor has to be base64 encoded");
}
$cursor = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new HttpError("Invallid pagination cursor, it has to be a valid json string");
}
return $cursor;
}
protected static function compare_keys($key1, $key2, $isNegativeSort): bool|int {
if (is_string($key1) && is_string($key2)) {
if ($isNegativeSort) {
return strcmp($key2, $key1);
}
else {
return strcmp($key1, $key2);
}
}
else {
if ($isNegativeSort) {
return $key2 > $key1;
}
else {
return $key1 > $key2;
}
}
}
protected static function getMinMaxCursor($apiClass, string $sort, array $filters, $request, $aliasedfeatures) {
$filters[Factory::LIMIT] = new LimitFilter(1);
// Descending queries are used to retrieve the last element. For this all sorts have to be reversed, since
// if all order queries are reversed and limit to 1, you will retrieve the last element.
$reverseSort = $sort == "DESC";
$orderTemplates = $apiClass->makeOrderFilterTemplates($request, $aliasedfeatures, $sort, $reverseSort);
$orderFilters = [];
// TODO this logic is now done twice, once for the max and once for the min, this should be moved outside this function
// and given as an argument
foreach ($orderTemplates as $orderTemplate) {
$orderFilters[] = new OrderFilter($orderTemplate['by'], $orderTemplate['type'], $orderTemplate['factory']);
if ($orderTemplate['factory'] !== null) {
// if factory of orderTemplate is not null, sort is happening on joined table
$otherFactory = $orderTemplate['factory'];
if (!$apiClass::checkJoinExists($filters[Factory::JOIN], $otherFactory->getModelName())) {
$filters[Factory::JOIN][] = new JoinFilter($otherFactory, $orderTemplate['joinKey'], $apiClass->getPrimaryKeyOther($otherFactory->getNullObject()::class));
}
}
}
$filters[Factory::ORDER] = $orderFilters;
$filters = $apiClass->parseFilters($filters);
$factory = $apiClass->getFactory();
$result = $factory->filter($filters);
//handle joined queries
if (array_key_exists(Factory::JOIN, $filters)) {
$result = $result[$factory->getModelname()];
}
if (sizeof($result) == 0) {
return null;
}
return $result[0];
}
/**
* overridable function to parse filters, currently only needed for taskWrapper endpoint
* to handle the taskWrapper -> task relation, to be able to treat it as a to one relationship
*/
protected function parseFilters(array $filters): array {
return $filters;
}
/**
* API entry point for requesting multiple objects
* @throws HttpError
*/
public static function getManyResources(object $apiClass, Request $request, Response $response, array $relationFs = []): Response {
$apiClass->preCommon($request);
$aliasedfeatures = $apiClass->getAliasedFeatures();
$factory = $apiClass->getFactory();
$defaultPageSize = 10000;
$maxPageSize = 50000;
// TODO: if 0.14.4 release has happened, following parameters can be retrieved from config
// $defaultPageSize = SConfig::getInstance()->getVal(DConfig::DEFAULT_PAGE_SIZE);
// $maxPageSize = SConfig::getInstance()->getVal(DConfig::MAX_PAGE_SIZE);
$pageAfter = $apiClass->getQueryParameterFamilyMember($request, 'page', 'after');
$pageBefore = $apiClass->getQueryParameterFamilyMember($request, 'page', 'before');
$pageSize = $apiClass->getQueryParameterFamilyMember($request, 'page', 'size') ?? $defaultPageSize;
if (!is_numeric($pageSize) || $pageSize < 0) {
throw new HttpError("Invalid parameter, page[size] must be a positive integer");
}
elseif ($pageSize > $maxPageSize) {
throw new HttpError(sprintf("You requested a size of %d, but %d is the maximum.", $pageSize, $maxPageSize));
}
$validExpandables = $apiClass::getExpandables();
$expands = $apiClass->makeExpandables($request, $validExpandables);
/* Object filter definition */
$aFs = [];
$joinFilters = [];
/* Generate filters */
$filters = $apiClass->getFilters($request);
$qFs_Filter = $apiClass->makeFilter($filters, $apiClass, $joinFilters);
$group = Factory::getRightGroupFactory()->get($apiClass->getCurrentUser()->getRightGroupId());
if ($group->getPermissions() !== 'ALL') { // Only add permission filters when no admin user
$aFs_ACL = $apiClass->getFilterACL();
if (isset($aFs_ACL[Factory::FILTER])) {
$qFs_Filter = array_merge($aFs_ACL[Factory::FILTER], $qFs_Filter);
}
if (isset($aFs_ACL[Factory::JOIN])) {
foreach($aFs_ACL[Factory::JOIN] as $filter) {
if(!$apiClass::checkJoinExists($joinFilters, $filter->getOtherFactory()->getModelName())) {
$joinFilters[] = $filter;
}
}
}
}
if (count($qFs_Filter) > 0) {
$aFs[Factory::FILTER] = $qFs_Filter;
}
/**
* Create pagination
*
* TODO: Deny pagination with un-stable sorting
*/
$sortList = $apiClass->getQueryParameterAsList($request, 'sort');
$isNegativeSort = $sortList != null && $sortList[0][0] == '-';
//this is used to reverse the array to show the data correctly for the user
$reverseArray = false;
$aFs[Factory::JOIN] = $joinFilters;
$firstCursorObject = $apiClass->getMinMaxCursor($apiClass, "ASC", $aFs, $request, $aliasedfeatures);
$lastCursorObject = $apiClass->getMinMaxCursor($apiClass, "DESC", $aFs, $request, $aliasedfeatures);
if (!$isNegativeSort && !isset($pageBefore) && isset($pageAfter)) {
// this happens when going to the next page while having an ascending sort
$defaultSort = "ASC";
$reverseArray = false;
$operator = ">";
$paginationCursor = $pageAfter;
}
else if (!$isNegativeSort && isset($pageBefore) && !isset($pageAfter)) {
// this happens when going to the previous page while having an ascending sort
$defaultSort = "DESC";
$reverseArray = true;
$operator = "<";
$paginationCursor = $pageBefore;
}
else if ($isNegativeSort && (isset($pageBefore) && !isset($pageAfter))) {
// this happens when going to the previous page while having a descending sort
$defaultSort = "ASC";
$reverseArray = true;
$operator = ">";
$paginationCursor = $pageBefore;
}
else if ($isNegativeSort && isset($pageAfter) && !isset($pageBefore)) {
// this happens when going to the next page while having an ascending sort
$defaultSort = "DESC";
$reverseArray = false;
$operator = "<";
$paginationCursor = $pageAfter;
}
else if ($isNegativeSort) {
//the default negative case to retrieve the first elements in a descending way
$defaultSort = "DESC";
}
else {
$defaultSort = "ASC";
}
$primaryKey = $apiClass->getPrimaryKey();
$orderTemplates = $apiClass->makeOrderFilterTemplates($request, $aliasedfeatures, $defaultSort);
$orderTemplates[0]["type"] = $defaultSort;
$primaryFilter = $orderTemplates[0]['by'];
$orderFilters = [];
// Build actual order filters
foreach ($orderTemplates as $orderTemplate) {
// $aFs[Factory::ORDER][] = new OrderFilter($orderTemplate['by'], $orderTemplate['type']);
$orderFilters[] = new OrderFilter($orderTemplate['by'], $orderTemplate['type'], $orderTemplate['factory']);
if ($orderTemplate['factory'] !== null) {
// if factory of ordertemplate is not null, sort is happening on joined table
$otherFactory = $orderTemplate['factory'];
if (!$apiClass::checkJoinExists($joinFilters, $otherFactory->getModelName())) {
$joinFilters[] = new JoinFilter($otherFactory, $orderTemplate['joinKey'], $orderTemplate['key']);
}
}
}
$aFs[Factory::ORDER] = $orderFilters;
$aFs[Factory::JOIN] = $joinFilters;
/* Include relation filters */
$finalFs = array_merge($aFs, $relationFs);
$finalFs = $apiClass->parseFilters($finalFs);
//TODO it would be even better if its possible to see if the primary filter is unique, instead of primary key.
//But this probably needs to be added in getFeatures() then.
$primaryKeyIsNotPrimaryFilter = $primaryFilter != $primaryKey;
$total = $factory->countFilter($finalFs);
//pagination filters need to be added after max has been calculated
$finalFs[Factory::LIMIT] = new LimitFilter($pageSize);
if (isset($paginationCursor) && isset($operator)) {
$decoded_cursor = $apiClass->decode_cursor($paginationCursor);
$primary_cursor = $decoded_cursor["primary"];
$primary_cursor_key = key($primary_cursor);
// Special filtering of id to use for uniform access to model primary key
$primary_cursor_key = $primary_cursor_key == 'id' ? array_column($aliasedfeatures, 'alias', 'dbname')[$apiClass->getPrimaryKey()] : $primary_cursor_key;
$secondary_cursor = array_key_exists("secondary", $decoded_cursor) ? $decoded_cursor["secondary"] : null;
if ($secondary_cursor) {
$secondary_cursor_key = key($secondary_cursor);
$secondary_cursor_key = $secondary_cursor_key == '_id' ? array_column($aliasedfeatures, 'alias', 'dbname')[$apiClass->getPrimaryKey()] : $secondary_cursor_key;
$finalFs[Factory::FILTER][] = new PaginationFilter($primary_cursor_key, current($primary_cursor),
$operator, $secondary_cursor_key, current($secondary_cursor), $qFs_Filter
);
}
else {
$finalFs[Factory::FILTER][] = new QueryFilter($primary_cursor_key, current($primary_cursor), $operator, $factory);
}
}
/* Request objects */
$filterObjects = $factory->filter($finalFs);
/* JOIN statements will return related modules as well, discard for now */
if (array_key_exists(Factory::JOIN, $finalFs)) {
$objects = $filterObjects[$factory->getModelname()];
}
else {
$objects = $filterObjects;
}
if ($reverseArray) {
$objects = array_reverse($objects);
}
/* Resolve all expandables */
$expandResult = [];
foreach ($expands as $expand) {
// mapping from $objectId -> result objects in
$expandResult[$expand] = $apiClass->fetchExpandObjects($objects, $expand);
}
/* Convert objects to JSON:API */
$dataResources = [];
$includedResources = [];
// Convert objects to data resources
foreach ($objects as $object) {
// Create object
$newObject = $apiClass->obj2Resource($object, $expandResult, $request->getQueryParams()['fields'] ?? null, $request->getQueryParams()['aggregate'] ?? null);
$includedResources = $apiClass->processExpands($apiClass, $expands, $object, $expandResult, $includedResources, $request->getQueryParams()['fields'] ?? null, $request->getQueryParams()['aggregate'] ?? null);
// Add to result output
$dataResources[] = $newObject;
}
$baseUrl = Util::buildServerUrl();
//build last link
$lastParams = $request->getQueryParams();
unset($lastParams['page']['after']);
$lastParams['page']['size'] = $pageSize;
// $next_cursor = $apiClass::build_cursor($primaryFilter, $nextId, $primaryKeyIsNotPrimaryFilter, $primaryKey, $nextPrimaryKey);
// $lastParams['page']['before'] = $apiClass::encode_cursor(self::calculate_next_cursor($max));
if ($primaryKeyIsNotPrimaryFilter && isset($lastCursorObject)) {
$new_secondary_cursor = $apiClass::calculate_next_cursor($lastCursorObject->getId(), !$isNegativeSort);
$last_cursor = $apiClass::build_cursor($primaryFilter, $lastCursorObject->expose()[$primaryFilter], $primaryKeyIsNotPrimaryFilter, $primaryKey, $new_secondary_cursor);
}
else if (isset($lastCursorObject)) {
$new_cursor = $apiClass::calculate_next_cursor($lastCursorObject->getId(), !$isNegativeSort);
$last_cursor = $apiClass::build_cursor($primaryFilter, $new_cursor);
}
else {
$last_cursor = null;
}
$lastParams['page']['before'] = $last_cursor;
$linksLast = $baseUrl . $request->getUri()->getPath() . '?' . urldecode(http_build_query($lastParams));
// Build self link
$selfParams = $request->getQueryParams();
if (isset($selfParams['page']['after'])) {
$selfParams['page']['after'] = urlencode($selfParams['page']['after']);
}
if (isset($selfParams['page']['before'])) {
$selfParams['page']['before'] = urlencode($selfParams['page']['before']);
}
$selfParams['page']['size'] = $pageSize;
$linksSelf = $baseUrl . $request->getUri()->getPath() . '?' . urldecode(http_build_query($selfParams));
$linksNext = null;
$linksPrev = null;
if (!empty($objects)) {
// retrieve last object in page and retrieve the attribute based on the filter
$firstObject = $objects[0]->expose();
$lastObject = end($objects)->expose();
$prevId = $firstObject[$primaryFilter];
$nextId = $lastObject[$primaryFilter];
$nextPrimaryKey = $lastObject[$primaryKey];
$previousPrimaryKey = $firstObject[$primaryKey];
//only set next page when its not the last page
if (isset($lastCursorObject) && $nextPrimaryKey !== $lastCursorObject->getId()) {
$nextParams = $selfParams;
// $nextParams['page']['after'] = urlencode($nextId);
$next_cursor = $apiClass::build_cursor($primaryFilter, $nextId, $primaryKeyIsNotPrimaryFilter, $primaryKey, $nextPrimaryKey);
$nextParams['page']['after'] = $next_cursor;
unset($nextParams['page']['before']);
$linksNext = $baseUrl . $request->getUri()->getPath() . '?' . urldecode(http_build_query($nextParams));
}
// Build prev link
//only set previous page when its not the first page
if (isset($firstCursorObject) && $previousPrimaryKey !== $firstCursorObject->getId()) {
//build page before
$prevParams = $selfParams;
$previous_cursor = $apiClass::build_cursor($primaryFilter, $prevId, $primaryKeyIsNotPrimaryFilter, $primaryKey, $previousPrimaryKey);
$prevParams['page']['before'] = $previous_cursor;
unset($prevParams['page']['after']);
$linksPrev = $baseUrl . $request->getUri()->getPath() . '?' . urldecode(http_build_query($prevParams));
}
}
//build first link
$firstParams = $request->getQueryParams();
unset($firstParams['page']['before']);
$firstParams['page']['size'] = $pageSize;
// $firstParams['page']['after'] = urlencode($min);
unset($firstParams['page']['after']);
$linksFirst = $baseUrl . $request->getUri()->getPath() . '?' . urldecode(http_build_query($firstParams));
$links = [
"self" => $linksSelf,
"first" => $linksFirst,
"last" => $linksLast,
"next" => $linksNext,
"prev" => $linksPrev,
];
$metadata = ["page" => ["total_elements" => $total]];
if ($apiClass->permissionErrors !== null) {
$metadata["Include errors"] = $apiClass->permissionErrors;
}
// Generate JSON:API GET output
$ret = self::createJsonResponse($dataResources, $links, $includedResources, $metadata);
$body = $response->getBody();
$body->write($apiClass->ret2json($ret));
return $response->withStatus(200)
->withHeader("Content-Type", 'application/vnd.api+json; ext="https://jsonapi.org/profiles/ethanresnick/cursor-pagination"');
}
/**
* API entry point for requesting multiple objects
* @throws HttpError
*/
public function get(Request $request, Response $response, array $args): Response {
return self::getManyResources($this, $request, $response);
}
/**
* Maps filters to the appropiate models based on their feautures.
*
* Helper function to get valid filters for the models. This is usefull when multiple objects
* have been included and the correct filters need to be mapped to the correct objects.
* Currently used to make complex filters for counting objects
*
* @param array $filters An associative array of filters where the key is the filter
* name and the value is the filter value. Filters should match
* the pattern `<field><operator>`, where `<operator>` can be
* one of the supported suffixes (e.g., `__eq`, `__ne`).
* @param array $models An array of model objects. Each model must have a `getFeatures()`
* method that returns an associative array of model features.
* The features should map filter keys to their respective
* attributes or aliases.
*
* @return array An associative array mapping model classes to their respective valid filters.
* The structure is:
* [
* ModelClassName => [
* 'filter' => 'value',
* ...
* ],
* ...
* ]
*
* @throws HttpForbidden If a filter key does not match the expected format or is invalid.
* @throws InternalError
*/
public function filterObjectMap(array $filters, array $models): array {
$modelFilterMap = [];
foreach ($filters as $filter => $value) {
if (preg_match('/^(?P<key>[_a-zA-Z0-9]+?)(?<operator>|__eq|__ne|__lt|__lte|__gt|__gte|__contains|__startswith|__endswith|__icontains|__istartswith|__iendswith)$/', $filter, $matches) == 0) {
throw new HttpForbidden("Filter parameter '" . $filter . "' is not valid");
}
foreach ($models as $model) {
$features = $model->getFeatures();
// Special filtering of _id to use for uniform access to model primary key
$cast_key = $matches['key'] == '_id' ? array_column($features, 'alias', 'dbname')[$this->getPrimaryKey()] : $matches['key'];
if (!array_key_exists($cast_key, $features)) {
continue; //not a valid filter for current model
};
$modelFilterMap[$model::class][$filter] = $value;
break; //filter has been found for current model, so break to go to next filter
}
}
return $modelFilterMap;
}
/**
* API entry point for retrieving count information of data
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
* @throws HTException
* @throws HttpError
* @throws HttpForbidden
* @throws InternalError
* @throws JsonException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function count(Request $request, Response $response, array $args): Response {
$this->preCommon($request);
$factory = $this->getFactory();
//resolve all expandables
$validExpandables = $this::getExpandables();
$expands = $this->makeExpandables($request, $validExpandables);
$objects = [$factory->getNullObject()];
$aFs = [];
//build join filters
foreach ($expands as $expand) {
$relation = $this->getToManyRelationships()[$expand];
$objects[] = $this->getModelFactory($relation["relationType"])->getNullObject();
$otherFactory = $this->getModelFactory($relation["relationType"]);
$primaryKey = $this->getPrimaryKey();
$aFs[Factory::JOIN][] = new JoinFilter($otherFactory, $relation["relationKey"], $primaryKey, $factory);
}
$filters = $this->getFilters($request);
$filterObjectMap = $this->filterObjectMap($filters, $objects);
$qFs = [];
foreach ($filterObjectMap as $class => $cur_filters) {
$relationApiClass = new ($this->container->get('classMapper')->get($class))($this->container);
$current_qFs = $this->makeFilter($cur_filters, $relationApiClass);
$qFs = array_merge($qFs, $current_qFs);
}
if (count($qFs) > 0) {
$aFs[Factory::FILTER] = $qFs;
}
$count = $factory->countFilter($aFs);
$meta = ["count" => $count];
$include_total = $request->getQueryParams()['include_total'] ?? false;
if ($include_total == "true") {
$meta["total_count"] = $factory->countFilter([]);
}
$ret = self::createJsonResponse(meta: $meta);