-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbrapi.module
1055 lines (1001 loc) · 35 KB
/
brapi.module
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
/**
* @file
* Contains brapi.module.
*/
use Drupal\brapi\Entity\BrapiDatatype;
use Drupal\brapi\Entity\BrapiToken;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
const BRAPI_PERMISSION_USE = 'use brapi';
const BRAPI_PERMISSION_EDIT = 'edit brapi content';
const BRAPI_PERMISSION_SPECIFIC = 'use restricted brapi';
const BRAPI_PERMISSION_ADMIN = 'administer brapi';
const BRAPI_DEFAULT_PAGE_SIZE = 40;
const BRAPI_DEFAULT_PAGE_SIZE_MAX = 200;
const BRAPI_DATATYPE_ID_REGEXP = '/^(v[\d])-([^\-]+)-([^\-]+)-?(.*)$/';
const BRAPI_MIME_JSON = 'application/json';
const BRAPI_DEFAULT_TOKEN_LIFETIME = 86400; // 1 day.
const BRAPI_DEFAULT_SEARCH_LIFETIME = 604800; // 1 week.
const BRAPI_TO_PLURAL = [
'entity' => 'entities',
'Entity' => 'Entities',
'ENTITY' => 'ENTITIES',
'germplasm' => 'germplasm',
'Germplasm' => 'Germplasm',
'GERMPLASM' => 'GERMPLASM',
];
const BRAPI_TO_SINGULAR = [
'entities' => 'entity',
'Entities' => 'Entity',
'ENTITIES' => 'ENTITY',
'germplasm' => 'germplasm',
'Germplasm' => 'Germplasm',
'GERMPLASM' => 'GERMPLASM',
];
/**
* Implements hook_help().
*/
function brapi_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the brapi module.
case 'help.page.brapi':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Plant Breeding API server implementation for Drupal.') . '</p>';
return $output;
default:
}
}
/**
* Implements hook_theme().
*/
function brapi_theme($existing, $type, $theme, $path) {
return [
'brapi_main' => [
'template' => 'brapi-main',
'variables' => [],
],
'brapi_documentation' => [
'template' => 'brapi-documentation',
'variables' => [],
],
'brapi_token' => [
'template' => 'brapi-token',
'variables' => ['tokens', 'all_tokens'],
],
];
}
/**
* Implements hook_preprocess_TEMPLATE().
*/
function brapi_preprocess_brapi_token(&$variables){
$user = \Drupal::currentUser();
$tokens = BrapiToken::getUserTokens($user, TRUE);
$variables['tokens'] = $tokens;
// Check if admin and add all available tokens if so.
if ($user->hasPermission(BRAPI_PERMISSION_ADMIN)) {
$token_storage = \Drupal::entityTypeManager()->getStorage('brapi_token');
$query = $token_storage->getQuery()
->accessCheck(FALSE)
->condition('user_id', $user->id(), '!=')
->sort('expiration', 'DESC');
;
// Only display unexpired tokens.
$group = $query
->orConditionGroup()
->condition('expiration', time(), '>')
->condition('expiration', 0, '<')
;
$query->condition($group);
$ids = $query->execute();
if (count($ids)) {
// Load tokens.
$variables['all_tokens'] = $token_storage->loadMultiple($ids);
}
}
}
/**
* Returns available BrAPI versions.
*
* @return array
* An array which keys are BrAPI major versions (either 'v1' or 'v2') and
* values are arrays which keys are subversions (ex. ['2.0', '2.1']) and
* values are booleans (set to TRUE).
*/
function brapi_available_versions() :array {
static $versions = [];
if (empty($versions)) {
// Get version definition directory.
$module_handler = \Drupal::service('module_handler');
$module_path = $module_handler->getModule('brapi')->getPath();
$version_path = \Drupal::service('file_system')->realpath(
$module_path . '/definitions'
);
$files = scandir($version_path);
// Process version files.
foreach ($files as $file) {
$file_path = "$version_path/$file";
// Limit to version files.
if (is_file($file_path)
&& preg_match('#^brapi_(v[12])_([\w\.\-]+)\.json$#', $file, $matches)
) {
$versions[$matches[1]] = $versions[$matches[1]] ?? [];
$versions[$matches[1]][$matches[2]] = TRUE;
}
}
}
return $versions;
}
/**
* Generates a data type identifier used in configs.
*
* @return string
* A data type identifier.
*/
function brapi_generate_datatype_id($datatype_name, $version, $active_def) :string {
$datatype_id = $version . '-' . $active_def . '-' . $datatype_name;
return $datatype_id;
}
/**
* Returns a BrAPI fields, data types and calls definition for a given version.
*
* @param string $version
* BrAPI version. Currently either 'v1' or 'v2'
*
* @param string $subversion
* BrAPI version with subversion number. Example: '2.0'.
*
* @return array
* An array as described below or an empty array if the version definition is
* not available:
* ```
* [
* 'modules' => [
* "<MODULE NAME1>" => [
* "<CATEGORY NAME1>" => [
* "calls" => [
* "<API CALL PATH1>" => TRUE,
* "<API CALL PATH2>" => TRUE,
* ...
* ],
* "data_types" => [
* "<DATA TYPE NAME1>" => TRUE,
* "<DATA TYPE NAME2>" => TRUE,
* ...
* ],
* ],
* "<CATEGORY NAME2>" => [
* ...
* ],
* ...
* ],
* "<MODULE NAME2>" => [
* ...
* ],
* ...
* ],
* 'calls' => [
* "<API CALL PATH1>" => [
* "definition" => [
* "<METHOD1>" => [
* "summary" => "...",
* "description" => "...",
* "fields" => [
* "<FIELD NAME1>" => [
* "description" => "...",
* "required" => TRUE/FALSE,
* "type" => "<TYPE>",
* "is_array" => TRUE/FALSE,
* ],
* ...
* ],
* ],
* "<METHOD2>" => [
* ...
* ],
* ...
* ],
* 'data_types' => [
* "<DATA TYPE NAME1>" => TRUE,
* ...
* ],
* ],
* ],
* 'data_types' => [
* "<DATA TYPE NAME1>" => [
* "description" => "...",
* "fields" => [
* "<FIELD NAME1>" => [
* "type" => <DATA TYPE NAME or basic type name followed by '[]' if array>
* "required" => TRUE/FALSE,
* ],
* ...
* ],
* "as_field_in" => [
* "<DATA TYPE NAME1>" => TRUE,
* ...
* ],
* "calls" => [
* "<API CALL PATH1>" => TRUE,
* ...
* ],
* ],
* "<DATA TYPE NAME2>" => [
* ...
* ],
* ...
* ],
* 'fields' => [
* "<FIELD NAME1>" => [
* "type" => "<TYPE>",
* "description" => "...",
* "example" => "...",
* "calls" => [
* "<API CALL PATH1>" => TRUE,
* ...
* ],
* "data_types" => [
* "<DATA TYPE NAME1>" => TRUE,
* ...
* ],
* ],
* "<FIELD NAME2>" => [
* ...
* ],
* ...
* ],
* ];
* ```
*/
function brapi_get_definition(string $version, string $subversion) :array {
static $versions = [];
// Sanitize parameters.
$version = preg_replace('/[^\w\.\-]/', '', $version);
$subversion = preg_replace('/[^\w\.\-]/', '', $subversion);
// Generate a static cache key.
$version_key = $version . '#' . $subversion;
if (!array_key_exists($version_key, $versions)) {
// Default to empty definition.
$versions[$version_key] = [];
// Get definition directory.
$module_handler = \Drupal::service('module_handler');
$module_path = $module_handler->getModule('brapi')->getPath();
$definition_path = \Drupal::service('file_system')->realpath(
$module_path . '/definitions'
);
$file_path = "$definition_path/brapi_" . $version . '_' . $subversion . '.json';
// Limit to definition files.
if (is_file($file_path)) {
// Try to get file content.
$json_raw = file_get_contents($file_path);
if (empty($json_raw)) {
// Log error.
\Drupal::logger('brapi')->error("Unable to get JSON file content for file '$file_path'.");
}
else {
$definition = json_decode($json_raw, TRUE);
if (NULL == $definition) {
\Drupal::logger('brapi')->error(
"Failed to parse JSON file '$file_path': "
. json_last_error_msg()
);
}
$versions[$version_key] = $definition;
}
}
$module_handler = \Drupal::moduleHandler();
$module_handler->alter('brapi_definition', $versions, $version_key);
}
return $versions[$version_key];
}
/**
* Converts an Open API JSON into a definition.
*
* This function is used "manually" to parse OpenAPI output and generate
* definitions files stored in module's "definitions" directory.
* Example of use:
* ```
* $f1 = file_get_contents('versions/openapi_brapi_1.2.json');
* $def = brapi_open_api_to_definition([json_decode($f1, TRUE),]);
* $json = json_encode($def, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
* $fj = fopen('definitions/brapi_v1_1.2.json', 'w');
* fwrite($fj, $json);
* fclose($fj);
* ```
*
* @param array $openapis
* An array of Open API data structures.
*
* @return array
* A definition array as describbed in brapi_get_definition().
*
* @see brapi_get_definition
* @see https://swagger.io/specification/
*/
function brapi_open_api_to_definition(array $openapis) :array {
$definition = [
'modules' => [],
'calls' => [],
'data_types' => [],
'fields' => [],
];
$ref_resolutions = [];
foreach ($openapis as $openapi_index => $openapi) {
// Init module data if needed.
$module = $openapi['info']['title'] ?? 'BrAPI';
$definition['modules'][$module] = $definition['modules'][$module] ?? [];
$module_definition =& $definition['modules'][$module];
// Add missing categories.
foreach ($openapi['tags'] ?? [['name' => '']] as $category) {
$module_definition[$category['name']] =
$module_definition[$category['name']]
?? []
;
}
// Process data types.
foreach ($openapi['components']['schemas'] ?? [] as $datatype => $datatype_definition) {
$ref =
$datatype_definition['$ref']
?? $datatype_definition['properties']['result']['$ref']
// ?? $datatype_definition['properties']['data']['$ref']
?? $datatype_definition['properties']['data']['items']['$ref']
?? ''
;
if (!empty($ref)) {
// Check for reference.
if (preg_match('%^#/components/schemas/(\w+)$%', $ref, $matches)) {
$ref_resolutions[$datatype] = $matches[1];
}
else {
\Drupal::logger('brapi')->warning("Unsuppoted \$ref: components>schemas>$datatype: " . $ref . '.');
}
continue 1;
}
// Check for response wrapper.
if (!empty($datatype_definition['properties']['metadata'])
&& !empty($datatype_definition['properties']['result'])
) {
// Check for reference.
$ref =
$datatype_definition['properties']['result']['$ref']
?? ''
;
if (!empty($ref)) {
if (preg_match('%^#/components/schemas/(\w+)$%', $ref, $matches)) {
$ref_resolutions[$datatype] = $matches[1];
}
else {
\Drupal::logger('brapi')->warning("Unsuppoted \$ref: components>schemas>$datatype>properties>result: " . $ref . '.');
}
}
continue 1;
}
// Process data type fields.
$fields = [];
foreach ($datatype_definition['properties'] ?? [] as $field => $field_definition) {
$fields[$field] = ['type' => $field_definition['type'] ?? ''];
if (!empty($field_definition['$ref'])) {
// Get type from reference.
if (preg_match('%^#/components/schemas/(\w+)$%', $field_definition['$ref'], $matches)) {
$fields[$field] = ['type' => $matches[1]];
}
else {
\Drupal::logger('brapi')->warning("Unsuppoted \$ref: components>schemas>$datatype>properties>$field.");
}
}
// Check for array of values.
if (!empty($field_definition['items']['$ref'])) {
if ((!empty($fields[$field]['type'])) && ('array' != $fields[$field]['type'])) {
\Drupal::logger('brapi')->warning("Check components>schemas>$datatype>properties>$field definition (invalid type: " . $fields[$field]['type'] . ").");
}
if (preg_match('%^#/components/schemas/(\w+)$%', $field_definition['items']['$ref'], $matches)) {
$fields[$field] = ['type' => $matches[1] . '[]'];
}
else {
\Drupal::logger('brapi')->warning("Unsuppoted \$ref: components>schemas>$datatype>properties>$field>items.");
}
}
elseif (!empty($field_definition['items']['type'])) {
if ((!empty($fields[$field]['type'])) && ('array' != $fields[$field]['type'])) {
\Drupal::logger('brapi')->warning("Check components>schemas>$datatype>properties>$field definition (invalid type: " . $fields[$field]['type'] . ").");
}
$fields[$field] = ['type' => $field_definition['items']['type'] . '[]'];
}
// Check if field is required by datatype.
$fields[$field]['required'] = in_array(
$field, $datatype_definition['required'] ?? []
);
// Fill field definitions.
if (empty($definition['fields'][$field])
|| empty($definition['fields'][$field]['type'])
) {
// New or incomplete field.
$definition['fields'][$field] = [
'type' => $fields[$field]['type'],
'description' => $field_definition['description'] ?? '',
'example' => $field_definition['example'] ?? '',
'calls' => $definition['fields'][$field]['calls'] ?? [],
'data_types' => [$datatype => TRUE],
];
}
else {
// Field redefinition. Check for inconsistency.
$current_type = $definition['fields'][$field]['type'];
$new_type = $fields[$field]['type'];
if (!empty($current_type)
&& !empty($new_type)
&& ($current_type != $new_type)
) {
\Drupal::logger('brapi')->warning("components>schemas>$datatype>properties>$field: inconsistent field redefinition (" . $current_type . ' vs ' . $new_type . ").");
}
// Register new data type dependency.
$definition['fields'][$field]['data_types'][$datatype] = TRUE;
}
}
$datatype_details = [
'type' => $datatype_definition['type'] ?? '',
'description' => $datatype_definition['description'] ?? '',
'fields' => $fields,
'calls' => [],
'as_field_in' => [],
];
if (!empty($definition['data_types'][$datatype])) {
\Drupal::logger('brapi')->warning("components>schemas>$datatype: data type already defined before. Completing definition.");
$definition['data_types'][$datatype]['type'] ?: $datatype_details['type'];
$definition['data_types'][$datatype]['description'] ?: $datatype_details['description'];
foreach ($datatype_details['fields'] as $field_name => $field_def) {
$definition['data_types'][$datatype]['fields'][$field_name] ??= $field_def;
}
}
else {
$definition['data_types'][$datatype] = $datatype_details;
}
}
// Process responses.
foreach ($openapi['components']['responses'] ?? [] as $response => $response_definition) {
$ref = $response_definition['content']['application/json']['schema']['$ref'] ?? '';
if (preg_match('%^#/components/schemas/(\w+)$%', $ref, $matches)) {
$ref_resolutions['response>' . $response] = $matches[1];
}
elseif (!empty($ref)) {
\Drupal::logger('brapi')->warning("Unsupported response components>respones>$response.");
}
}
// Process $ref_resolutions to update resolutions to final objects.
foreach ($ref_resolutions as $ref => $resolution) {
$circular_check = [];
while (
array_key_exists($resolution, $ref_resolutions)
&& empty($circular_check[$ref_resolutions[$resolution]])
) {
$circular_check[$resolution] = TRUE;
$resolution = $ref_resolutions[$resolution];
}
if (!empty($circular_check[$resolution])) {
\Drupal::logger('brapi')->warning("Unresolved circular references for $ref.");
}
if (empty($definition['data_types'][$resolution])) {
\Drupal::logger('brapi')->warning("Missing data type definition '$resolution' for $ref.");
}
$ref_resolutions[$ref] = $resolution;
}
// Fill 'as_field_in'.
foreach ($definition['data_types'] as $datatype => $datatype_definition) {
foreach ($datatype_definition['fields'] as $field => $def) {
$type = $def['type'];
// We don't care if it is an array, we just need the type name.
$type = rtrim($type, '[]');
if (array_key_exists($type, $definition['data_types'])) {
$definition['data_types'][$type]['as_field_in'][$datatype] = TRUE;
}
}
}
// Process calls.
foreach ($openapi['paths'] ?? [] as $call => $call_definition) {
$call_details = [
'definition' => $call_definition,
'data_types' => [],
];
$categories = [];
if (!empty($call_definition['$ref'])) {
// @todo: Get methods from reference.
\Drupal::logger('brapi')->warning("Unsuppoted \$ref: paths>$call.");
}
foreach ($call_definition as $method => $method_definition) {
foreach ($method_definition['parameters'] ?? [] as $parameter) {
if (!empty($parameter['$ref'])) {
// @todo: Get schema from ref.
\Drupal::logger('brapi')->warning("Unsuppoted \$ref: paths>$call>$method>parameters.");
}
// Fill data type dependencies.
if (!empty($parameter['schema'])) {
if (!empty($parameter['schema']['$ref'])) {
if (preg_match('%^#/components/schemas/(\w+)$%', $parameter['schema']['$ref'], $matches)) {
// Resolve reference ro real data type name.
$datatype = $matches[1];
if (array_key_exists($datatype, $ref_resolutions)) {
$datatype = $ref_resolutions[$datatype];
}
$call_details['data_types'][$datatype] = TRUE;
}
else {
\Drupal::logger('brapi')->warning("Unsuppoted \$ref: paths>$call>$method>parameters>schema.");
}
}
else {
$field = $parameter['name'] ?? '';
if (!array_key_exists($field, $definition['fields'])) {
$definition['fields'][$field] = [
'type' => $parameter['type'] ?? '',
'description' => $parameter['description'] ?? '',
'example' => $parameter['example'] ?? '',
'calls' => [$call => TRUE,],
'data_types' => [],
];
if (!empty($parameter['items'])) {
$definition['fields'][$field]['type'] = $parameter['items']['type'] . '[]';
}
}
$definition['fields'][$field]['calls'][$call] = TRUE;
}
}
}
// Add response data type dependencies.
// Resolve references to a real data type name.
$ref =
$method_definition['responses']['200']['$ref']
?? $method_definition['responses']['200']['content']['application/json']['schema']['$ref']
?? $method_definition['responses']['200']['content']['application/json']['schema']['properties']['result']['$ref']
?? $method_definition['responses']['200']['content']['application/json']['schema']['properties']['result']['properties']['data']['$ref']
?? $method_definition['responses']['200']['content']['application/json']['schema']['properties']['result']['properties']['data']['items']['$ref']
?? ''
;
// Check if we have a reference.
if (!empty($ref)
&& (preg_match('%^#/components/schemas/(\w+)$%', $ref, $matches))
) {
// Resolve reference ro real data type name.
$datatype = $matches[1];
if (array_key_exists($datatype, $ref_resolutions)) {
$datatype = $ref_resolutions[$datatype];
}
$call_details['data_types'][$datatype] = TRUE;
}
else {
// No reference, maybe a simple type defined.
$type =
$method_definition['responses']['200']['content']['application/json']['schema']['properties']['result']['properties']['data']['items']['type']
?? $method_definition['responses']['200']['content']['application/json']['schema']['properties']['result']['properties']['data']['type']
?? $method_definition['responses']['200']['content']['application/json']['schema']['properties']['result']['properties']['status']['type']
?? ''
;
if (empty($type)) {
// No type either, report as warning.
\Drupal::logger('brapi')->warning("No response data type identified for paths>$call>$method>responses.");
}
}
// Add call to categories.
foreach ($method_definition['tags'] ?? [['name' => '']] as $category) {
$module_definition[$category]['calls'][$call] = TRUE;
$categories[$category] = TRUE;
}
}
// Add call details to BrAPI definition.
if (!empty($definition['calls'][$call])) {
\Drupal::logger('brapi')->warning("Redefinition of call $call in " . $module . '(array ' . $openapi_index . ').');
}
$definition['calls'][$call] = $call_details;
// Add call to data types and data types to categories.
foreach (array_keys($call_details['data_types']) as $datatype) {
if (empty($definition['data_types'][$datatype])) {
\Drupal::logger('brapi')->warning("Missing data type '$datatype' definition for call $call in " . $module . '(array ' . $openapi_index . ') (note: it may be defined later in other modules).');
}
$definition['data_types'][$datatype]['calls'][$call] = TRUE;
foreach ($categories as $category) {
$module_definition[$category]['data_types'][$datatype] = TRUE;
}
}
}
}
return $definition;
}
/**
* Tells if a field references another BrAPI datatype.
*
* @param string $field
* The current datatype field name to check.
* @param string $current_datatype
* The current datatype that holds the potential reference field to check.
* @param array $brapi_def
* The BrAPI definition to use.
*
* @return FALSE if the field is not a reference, the referenced datatype name
* otherwise (evaluated as a TRUE value).
*/
function brapi_is_reference_to_datatype(
string $field,
string $current_datatype,
array $brapi_def
) {
$referenced_datatype = FALSE;
$field_datatype =
$brapi_def['data_types'][$current_datatype]['fields'][$field]['type']
?? ''
;
// Adjust field datatype to match real datatypes.
// Ex.: field datatype "GermplasmAttribute_trait" should be in fact
// treated as "Trait".
// @todo: Maybe use a more generic way to get existing mappings: maybe use
// BrAPI git YAML files as source instead of Swagger?
$field_datatype = ucfirst(
str_replace($current_datatype . '_', '', $field)
);
if (array_key_exists($field_datatype, $brapi_def['data_types'])) {
$referenced_datatype = $field_datatype;
}
return $referenced_datatype;
}
/**
* Tells if a field references another BrAPI datatype.
*
* @param string $field
* The current datatype field name to check.
* @param BrapiDatatype $current_datatype_mapping
* The current datatype mapping containing the field to check.
* @param array $brapi_def
* The BrAPI definition to use.
*
* @return the BrapiDatatype instance used to load field data, FALSE if there is
* no corresponding mapping object.
*/
function brapi_get_referenced_datatype_mapping(
string $field,
BrapiDatatype $current_datatype_mapping,
array $brapi_def
) {
$brapi_mapping = FALSE;
$current_datatype = $current_datatype_mapping->getBrapiDatatype();
$ref_datatype = brapi_is_reference_to_datatype(
$field,
$current_datatype,
$brapi_def
);
if ($ref_datatype) {
$drupal_mapping = $current_datatype_mapping->mapping[$field] ?? ['field' => '',];
if ('_submapping' == $drupal_mapping['field']) {
// Get data type mapping entities.
$mapping_loader = \Drupal::service('entity_type.manager')
->getStorage('brapidatatype')
;
if ('custom' == $drupal_mapping['submapping']) {
$submapping = $current_datatype_mapping->id . '-' . lcfirst($ref_datatype);
$brapi_mapping = $mapping_loader->load($submapping);
}
else {
$brapi_mapping = $mapping_loader->load($drupal_mapping['submapping']);
}
}
}
return $brapi_mapping;
}
/**
* Returns a given term plural as defined in BrAPI.
*
* This function supports lower case, uppercase, camelCase and CamelCase.
*
* @param string $term
* Term to pluralize.
*
* @return string
* Pluralized term.
*/
function brapi_get_term_plural(string $term) :string {
if (array_key_exists($term, BRAPI_TO_PLURAL)) {
$plural = BRAPI_TO_PLURAL[$term];
}
elseif (preg_match('#[a-z]#', $term)) {
$plural = $term . 's';
}
else {
// All upper case.
$plural = $term . 'S';
}
return $plural;
}
/**
* Returns a given term singular as defined in BrAPI.
*
* This function supports lower case, uppercase, camelCase and CamelCase.
*
* @param string $term
* Term to singularize.
*
* @return string
* Singularized term.
*/
function brapi_get_term_singular(string $term) :string {
if (array_key_exists($term, BRAPI_TO_SINGULAR)) {
$singular = BRAPI_TO_SINGULAR[$term];
}
elseif (('s' == substr($term, -1)) || ('S' == substr($term, -1))) {
$singular = substr($term, 0, -1);
}
else {
$singular = $term;
}
return $singular;
}
/**
* Implements hook_brapi_call_CALL_SIGNATURE_result_alter().
*
* This implementation alters the 'data' result of list details. By default, it
* is mapped to a Drupal array of string fields which is turned into an array
* containing 'value' keys. The implementation removes the 'value' keys and
* flatten the array.
*
* It also turns dates into the appropriate format.
*/
function brapi_brapi_call_get_v2_lists_listdbid_result_alter(&$json_array, array &$context) {
// Flatten data.
if (!empty($json_array['result']['data'])) {
$json_array['result']['data'] = array_map(
function ($d) {
return $d['value'] ?? $d;
},
$json_array['result']['data']
);
}
// Adjust date format.
if (!empty($json_array['result']['dateCreated'])
&& is_numeric($json_array['result']['dateCreated'])
) {
$json_array['result']['dateCreated'] = date(DATE_ATOM, $json_array['result']['dateCreated']);
}
if (!empty($json_array['result']['dateModified'])
&& is_numeric($json_array['result']['dateModified'])
) {
$json_array['result']['dateModified'] = date(DATE_ATOM, $json_array['result']['dateModified']);
}
// Manage externalReferences.
if (!empty($json_array['result']['externalReferences'])
&& is_array($json_array['result']['externalReferences'])
) {
$new_extref_values = [];
foreach ($json_array['result']['externalReferences'] as $extref) {
if (is_array($extref) && !empty($extref['value'])) {
$extref = json_decode($extref['value']) ?: $extref;
}
$new_extref_values[] = $extref;
}
$json_array['result']['externalReferences'] = $new_extref_values;
}
}
/**
* Implements hook_brapi_call_CALL_SIGNATURE_result_alter().
*/
function brapi_brapi_call_put_v2_lists_listdbid_result_alter(&$json_array, array &$context) {
brapi_brapi_call_get_v2_lists_listdbid_result_alter($json_array, $context);
}
/**
* Implements hook_brapi_call_CALL_SIGNATURE_result_alter().
*/
function brapi_brapi_call_post_v2_lists_listdbid_data_result_alter(&$json_array, array &$context) {
brapi_brapi_call_get_v2_lists_listdbid_result_alter($json_array, $context);
}
/**
* Implements hook_brapi_call_CALL_SIGNATURE_result_alter().
*/
function brapi_brapi_call_post_v2_lists_listdbid_items_result_alter(&$json_array, array &$context) {
brapi_brapi_call_get_v2_lists_listdbid_result_alter($json_array, $context);
}
/**
* Implements hook_brapi_BRAPI_DATA_TYPE_save_alter().
*/
function brapi_brapi_listdetails_save_alter(
array &$data,
BrapiDatatype &$data_type,
EntityStorageInterface &$storage
) {
// Convert dates.
$date_created = strtotime($data['dateCreated'] ?? '');
if ($date_created) {
$data['dateCreated'] = $date_created;
}
$date_modified = strtotime($data['dateModified'] ?? '');
if ($date_modified) {
$data['dateModified'] = $date_modified;
}
// Manage externalReferences.
if (!empty($data['externalReferences'])
&& is_array($data['externalReferences'])
) {
$new_extref_values = [];
foreach ($data['externalReferences'] as $extref) {
if (!is_string($extref)) {
$extref = json_encode($extref);
}
$new_extref_values[] = $extref;
}
$data['externalReferences'] = $new_extref_values;
}
}
/**
* Implements hook_brapi_call_CALL_SIGNATURE_result_alter().
*
* Handles specificities of the /lists/{listDbId}/data POST call.
*/
function brapi_brapi_call_post_v2_lists_listdbid_data_alter(&$json_array, array &$context) {
// Variable aliases.
$controller = &$context['controller'];
$request = &$context['request'];
$config = &$context['config'];
$version = &$context['version'];
$call = &$context['call'];
$method = &$context['method'];
// Load the list.
$active_def = $config->get($version . 'def');
$brapi_def = brapi_get_definition($version, $active_def);
$datatype = 'ListDetails';
$mapping_loader = \Drupal::service('entity_type.manager')->getStorage('brapidatatype');
$datatype_id = brapi_generate_datatype_id($datatype, $version, $active_def);
$datatype_mapping = $mapping_loader->load($datatype_id);
if (empty($datatype_mapping)) {
$message = "No mapping available for data type '$datatype_id'.";
\Drupal::logger('brapi')->error($message);
throw new NotFoundHttpException($message);
}
$filters = $request->attributes->get('_raw_variables')->all();
$result = $datatype_mapping->getBrapiData($filters);
if (!empty($result['entities'])) {
$list_data = current($result['entities']);
}
// Get POST data.
$parameters = $controller->getPostData($request);
if (empty($parameters)) {
throw new BadRequestHttpException('Missing input data to record.');
}
if (!is_array($parameters)) {
throw new BadRequestHttpException('Invalid input data to record. Expecting a list of object identifiers.');
}
foreach ($parameters as $index => $object_id) {
if (!is_string($object_id) && !is_int($object_id)) {
throw new BadRequestHttpException('Invalid input data to record. Expecting a list of object identifiers but found an invalid identifier (at position ' . $index . ').');
}
}
// Append new items to the list.
$list_data['data'] = array_unique(
array_merge($list_data['data'] ?? [], $parameters)
);
$status = [];
$brapi_data = [];
$id_field_name = $datatype_mapping->getBrapiIdField();
try {
// Save the list.
$new_list_data = $datatype_mapping->saveBrapiData($list_data);
$status[] = [
'message' => $datatype_mapping->getBrapiDatatype() . ' ' . ($new_list_data[$id_field_name] ?? '') . ' updated.',
'messageType' => 'INFO',
];
$brapi_data = $new_list_data;
}
catch (HttpException $e) {
$status[] = [
'message' => 'Failed to update record. ' . $e->getMessage(),
'messageType' => 'ERROR',
];
}
$result = ['result' => $brapi_data];
$parameters = [
'page_size' => $brapi_data ? 1 : 0,
'page' => 0,
'total_count' => $brapi_data ? 1 : 0,
'status' => $status ?: NULL,
];
$metadata = $controller->generateMetadata($request, $config, $parameters);
// Returns the updated record.
$json_array = $metadata + $result;
}
/**
* Implements hook_brapi_definition_alter().
*
* Adds a delete method to /lists/{listDbId}.
*/
function brapi_brapi_definition_alter(
array &$versions,
string &$version_key,
) {
if (empty($versions[$version_key]['calls']['/lists/{listDbId}']['definition']['delete'])) {
$versions[$version_key]['calls']['/lists/{listDbId}']['definition']['delete'] = [
"tags" => [
"Lists",
],
"summary" => "Removes a specific list",
"description" => "Removes a specific list",
"parameters" => [
[
"name" => "listDbId",
"in" => "path",
"description" => "The unique ID of this generic list",
"required" => true,
"style" => "simple",
"explode" => false,
"schema" => [
"type" => "string",
],
],
[
"name" => "Authorization",
"in" => "header",
"description" => "HTTP HEADER - Token used for Authorization\n\n<strong> Bearer {token_string} </strong>",
"required" => false,
"style" => "simple",
"explode" => false,
"schema" => [
"pattern" => "^Bearer .*\$",
"type" => "string",
],
"example" => "Bearer XXXX",
],
],
"responses" => [
200 => [
"description" => "OK",
"content" => [