Repository navigation
Expand file tree
/
Copy pathExternalModule.php
More file actions
834 lines (644 loc) · 22.6 KB
/
Copy pathExternalModule.php
File metadata and controls
834 lines (644 loc) · 22.6 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
<?php
namespace Vanderbilt\REDSTAMP\ExternalModule;
// require_once __DIR__ . '/src/autoload.php';
// require_once(dirname(__FILE__) . '/vendor/autoload.php');
require_once(dirname(__FILE__) . '/src/autoload.php');
use ExternalModules\AbstractExternalModule;
// use ExternalModules\ExternalModule;
// use REDCap;
use Twig\TwigFunction;
use GuzzleHttp\Client;
class ExternalModule extends AbstractExternalModule
{
private const AJAX_ALTERABLE_PROJECT_SETTINGS_WHITELIST = [
"active_sdtmig",
"active_sdtmct",
"active_study_level_domains",
"active_subject_level_domains"
];
public function redcap_every_page_top($project_id) {
$this->initializeJavascriptModuleObject();
$this->tt_addToJavascriptModuleObject(
"sdtm_config_page",
$this->getUrl("interfaces/sdtm_config_page.php")
);
$inject_tab_pages = [
"index.php", // equivalent to project_home_page
"ProjectSetup/index.php",
"ProjectSetup/other_functionality.php",
"ProjectSetup/project_revision_history.php"
];
if (
in_array(PAGE, $inject_tab_pages) ||
(PAGE === "external_modules/index.php" && $_GET['prefix'] === "redstamp")
) {
$this->addJS("js/inject_config_tab.js");
}
}
public function loaderModal() {
$loader_path = APP_PATH_IMAGES . 'loader.gif';
$loader_html = <<<_
<div id="loader_modal">
<p>Kyle is still trying to optimize load times so you have to wait :(</p>
<img id="loader_bar" src="{$loader_path}"/>
</div>
_;
echo $loader_html;
}
public function setUpJSMO(): void {
$this->initializeJavascriptModuleObject();
// $param1 = [
// "foo" => "bar"
// ];
// $this->tt_addToJavascriptModuleObject("param1", $param1);
}
public function addJS(string $path): void {
// $this->initializeJavascriptModuleObject();
echo "<script src='" . $this->getUrl($path) . "'></script>";
}
public function addCSS(string $path): void {
echo "<link rel='stylesheet' href='" . $this->getUrl($path) . "'>";
}
public function loadTwigExtensions(): void {
$this->initializeTwig();
// Source - https://stackoverflow.com/a/74089647
// Posted by RcoderNY
// Retrieved 2026-01-30, License - CC BY-SA 4.0
// $profile = new \Twig\Profiler\Profile();
// $this->getTwig()->addExtension(new \Twig\Extension\ProfilerExtension($profile));
// $GLOBALS['profile'] = $profile;
$this->getTwig()->addFunction(new TwigFunction('loadJSBS', function () {
return $this->framework->loadBootstrap() . $this->framework->loadREDCapJS();
}));
$this->getTwig()->addFunction(new TwigFunction('getCSRFToken', function () {
return $this->getCSRFToken();
}));
$this->getTwig()->addFunction(new TwigFunction('addJS', function ($path) {
return $this->addJS($path);
}));
$this->getTwig()->addFunction(new TwigFunction('addCSS', function ($path) {
return $this->addCSS($path);
}));
$this->getTwig()->addFunction(new TwigFunction('getSDTMFields', function (?array $domain_filter = null) {
return $this->getSDTMFields($domain_filter);
}));
$this->getTwig()->addFunction(new TwigFunction('getFields', function (array $filter_fields = []) {
return $this->getFields($filter_fields);
}));
$this->getTwig()->addFunction(new TwigFunction('getMappings', function (string $domain_filter = null) {
return $this->getMappings($domain_filter);
}));
}
public function loadIndexTwig() {
return $this->getTwig()->render('index.html.twig', [
'project_id' => $this->getProjectId()
]);
}
public function loadRedcapTwig() {
return $this->getTwig()->render('redcap_to_sdtm.html.twig', [
'project_id' => $this->getProjectId()
]);
}
public function loadSdtmTwig(string $domain_filter = null) {
$sdtm_fields = $this->getSDTMFields($domain_filter);
$html = $this->getTwig()->render('sdtm_to_redcap.html.twig', [
'project_id' => $this->getProjectId(),
'sdtm' => $sdtm_fields,
'sdtm_domains' => $this->getSDTMDomains(),
'sdtm_ctr' => $this->getSDTMCTR(),
'get' => $_GET
]);
return $html;
}
public function loadTestTwig() {
return $this->getTwig()->render('test_page.html.twig', [
'project_id' => $this->getProjectId(),
'sdtm' => $this->getSDTMFields(),
'sdtm_ctr' => $this->getSDTMCTR()
]);
}
public function loadConfigPageTwig() {
$igs = $this->getSDTMIGs();
$html = $this->getTwig()->render('sdtm_config_page.html.twig', [
'project_id' => $this->getProjectId(),
// FIXME: this is also exposed in tt_addToJavascriptModuleObject as sdtmigs
'sdtmigs' => $igs,
'get' => $_GET
]);
// $this->tt_addToJavascriptModuleObject(
// "sdtm_ctr",
// $this->getSDTMCTR(),
// "sdtmigs",
// $igs
// );
return $html;
}
public function getFields(array $filterFields = []): array {
$returnArray = [];
$thisProject = new \Project($this->getProjectId());
// $userForm = $this->getProjectSetting('user-form');
$metadata = $thisProject->metadata;
foreach ($metadata as $fieldName => $fieldInfo) {
if ($fieldName == $thisProject->table_pk || (str_ends_with($fieldName, "_complete")) || (count($filterFields) !== 0 && !in_array($fieldName, $filterFields))) {
continue;
}
$returnArray[$fieldInfo['field_order']] = [];
$this_field = $fieldInfo;
switch ($fieldInfo['element_type']) {
case 'descriptive':
unset($returnArray[$fieldInfo['field_order']]);
break;
case 'select':
// $this_field['choices'] = $this->processFieldEnum($fieldInfo);
$this_field['choices'] = parseEnum($fieldInfo['element_enum']);
// 'choices' => $this->processFieldEnum($fieldInfo),
// no break
default:
// $returnArray[$fieldInfo['field_order']] = [
// 'name' => $fieldName,
// 'label' => $fieldInfo['element_label'],
// 'type' => $fieldInfo['element_type'],
// // 'choices' => $this->processFieldEnum($fieldInfo),
// 'required' => ($fieldInfo['field_req'] ? 'required' : '')
// ];
$returnArray[$fieldInfo['field_order']] = $this_field;
break;
}
}
return $returnArray;
}
public function getSDTMFields(string $domain_filter = null): array {
// HACK: load csv direct from EM
// TODO: expose as file upload setting
$target_file = $this->getUrl("SDTMIG_v3.4.csv");
// $target_file = "/var/www/html/modules/redstamp_v0.0.0/" . "SDTMIG_v3.4.csv";
// TODO: allow user to provide
$target_file = $this->getModulePath() . "SDTMIG_v3.4.csv";
$csv_file = fopen($target_file, "r");
$csv_data = [];
$headers = fgetcsv($csv_file);
while (($row = fgetcsv($csv_file)) !== false) {
$labeled_row = array_combine($headers, $row);
if (!is_null($domain_filter) && ($domain_filter != $labeled_row["Dataset Name"])) {
continue;
}
// replace newlines with ... newlines
// str_replace('\n', "\n", &$labeled_row["CDISC Notes"]);
$labeled_row["CDISC Notes"] = str_replace('\n', "\n", $labeled_row["CDISC Notes"]);
// NOTE: nl2br result in literal <br /> displayed to user
// $labeled_row["CDISC Notes"] = nl2br($labeled_row["CDISC Notes"]);
$csv_data[] = $labeled_row;
}
fclose($csv_file);
$display_order = ["Req", "Exp", "Perm"];
// adapted from
// https://www.php.net/manual/en/function.usort.php
usort($csv_data, function ($a, $b) use ($display_order) {
$pos_a = array_search($a['Core'], $display_order);
$pos_b = array_search($b['Core'], $display_order);
// retain order
if ($pos_a == $pos_b) {
return 0;
}
return ($pos_a < $pos_b) ? -1 : 1;
});
return $csv_data;
}
public function getSDTMDomainJson(array $domain_filter = null): array {
// TODO: consider just returning an entire SDTM dataset instead of the fields
// TODO: check for cached JSON and request from API otherwise, cached ds should be stored at system level in edocs
$target_file = $this->getModulePath() . "sdtmig_v3.4.json";
$file_data = json_decode(file_get_contents($target_file), true);
// $file_data['classes']['datasets']
// find dataset where $ds['name'] == $domain_filter
// return datasetVariables for processing
$return_datasets = [];
foreach ($file_data['classes'] as $class) {
$domain = $class['datasets'];
foreach ($domain as $ds) {
// TODO: borked
if (!is_null($domain_filter) && (!in_array($ds['name'], $domain_filter))
) {
continue;
}
$return_datasets[] = $ds;
}
}
return $return_datasets;
$display_order = ["Req", "Exp", "Perm"];
// TODO: adapt display order for json data
// adapted from
// https://www.php.net/manual/en/function.usort.php
usort($csv_data, function ($a, $b) use ($display_order) {
$pos_a = array_search($a['Core'], $display_order);
$pos_b = array_search($b['Core'], $display_order);
// retain order
if ($pos_a == $pos_b) {
return 0;
}
return ($pos_a < $pos_b) ? -1 : 1;
});
return $csv_data;
}
public function getSDTMDomains(): array {
// HACK: load csv direct from EM
// Can't simply array_unique(array_column(sdtm, "Dataset Name"))
// because filtering is applied durring array creation lol
// TODO: expose as file upload setting
// $target_file = "/var/www/html/modules/redstamp_v0.0.0/" . "SDTMIG_v3.4.csv";
// TODO: allow user to provide
$target_file = $this->getModulePath() . "SDTMIG_v3.4.csv";
$csv_file = fopen($target_file, "r");
$headers = fgetcsv($csv_file);
$domains = [];
while (($row = fgetcsv($csv_file)) !== false) {
$labeled_row = array_combine($headers, $row);
$domains[] = $labeled_row["Dataset Name"];
}
fclose($csv_file);
return array_unique($domains);
}
public function getSDTMCTR(): array {
// HACK: load csv direct from EM
// TODO: fetch from JSON
$target_file = $this->getModulePath() . "SDTM_CT_2025-09-26.csv";
// $target_file = "/var/www/html/modules/redstamp_v0.0.0/" . "SDTM_CT_2025-09-26.csv";
$csv_file = fopen($target_file, "r");
$csv_data = [];
$headers = fgetcsv($csv_file);
while (($row = fgetcsv($csv_file)) !== false) {
$csv_data[] = array_combine($headers, $row);
}
fclose($csv_file);
return $csv_data;
}
public function getSDTMCTRJson(): array {
// HACK: load csv direct from EM
// TODO: expose as file upload setting
$target_file = $this->getModulePath() . "SDTM_CT_2025-09-26.csv";
// $target_file = "/var/www/html/modules/redstamp_v0.0.0/" . "SDTM_CT_2025-09-26.csv";
$csv_file = fopen($target_file, "r");
$csv_data = [];
$headers = fgetcsv($csv_file);
while (($row = fgetcsv($csv_file)) !== false) {
$csv_data[] = array_combine($headers, $row);
}
fclose($csv_file);
return $csv_data;
}
public function getAvailableSDTMCTs(): array {
// $api_path = "mdr/products/DataTabulation?expand=true";
$api_path = "mdr/ct/packages";
$response = $this->makeRequest($api_path);
$stds = $response["_links"]["packages"];
$search = "SDTM Controlled Terminology";
$stds = array_filter($stds, function ($item) use ($search) {
return isset($item['title']) && str_starts_with($item['title'], $search);
});
usort($stds, fn ($a, $b) => $b['title'] <=> $a['title']);
return $stds;
// HACK: load csv direct from EM
// TODO: expose as file upload setting
$target_file = $this->getModulePath() . "SDTM_CT_2025-09-26.csv";
// $target_file = "/var/www/html/modules/redstamp_v0.0.0/" . "SDTM_CT_2025-09-26.csv";
$csv_file = fopen($target_file, "r");
$csv_data = [];
$headers = fgetcsv($csv_file);
while (($row = fgetcsv($csv_file)) !== false) {
$csv_data[] = array_combine($headers, $row);
}
fclose($csv_file);
return $csv_data;
}
public function getSDTMMappingsFromFields(): array {
$fields = $this->getFields();
// $name_col = array_column($fields, 'field_name');
// $misc_col = array_column($fields, 'misc');
$df = [];
$idx = 0;
foreach ($fields as &$row) {
if (empty($row['misc'])) {
continue;
}
// $this_s = new SDTMMapping($row);
$df[] = new SDTMMapping($row);
$idx++;
}
return $df;
}
public function getModal($custom = null) {
if ($custom === null) {
$custom = "modal_calc.html";
}
include($custom);
}
// public function redcap_module_ajax($action, $payload, $project_id, $record, $instrument, $event_id, $repeat_instance, $survey_hash, $response_id, $survey_queue_hash, $page, $page_full, $user_id, $group_id) {
public function redcap_module_ajax($action, $payload) {
$response = null;
switch ($action) {
case "store_calc_mapping":
$response = $payload;
$sdtm = new SDTMMapping($payload);
$this->saveSDTM($sdtm);
$response = $sdtm->uid;
break;
case "check_logic":
return \LogicTester::isValid($payload['calc_text']);
break;
case "save_project_setting":
if (!in_array($payload["setting"], self::AJAX_ALTERABLE_PROJECT_SETTINGS_WHITELIST)) {
$response = "disallowed setting";
// TODO: log?
break;
}
$stored_value = $payload["value"];
// if (is_array($stored_value)) {
// arrays result in duplication of fields
// $stored_value = json_encode($stored_value);
// }
// NOTE: backend stores this as a single field, but manager config shows indepent json fields
$this->setProjectSetting($payload["setting"], $payload["value"]);
break;
case "get_domains":
$response = $this->getDomains();
break;
case "get_sdtm_ctr":
$domain_filter = $payload["domain_filter"];
$response = $this->getSDTMCTR($domain_filter);
break;
case "lazy_load":
$payload['resource'];
$response = json_encode($this->getAvailableSDTMCTs());
break;
case "apply_mapping":
$response = json_encode(
$this->applyMappingToRecord(
$payload['record_id'],
$payload['domain_filter']
)
);
// $response = $this->applyMappingToRecord(
// $payload['record_id'],
// $payload['domain_filter']
// );
break;
default:
$response = "no room";
}
return $response;
}
public function saveSDTM(SDTMMapping $sdtm) {
$db_file_name = PROJECT_ID . "_sdtm_mappings.db";
$db_full_path = $this->getModulePath() . $db_file_name;
$sdti = new SDTMInterface($db_full_path);
$result = $sdti->storeMapping($sdtm);
return $result;
}
public function getMappings(string $domain_filter = null) {
$db_file_name = PROJECT_ID . "_sdtm_mappings.db";
$db_full_path = $this->getModulePath() . $db_file_name;
$sdti = new SDTMInterface($db_full_path);
$mappings = $sdti->getMappings($domain_filter);
// HACK: add instance from uid
// future, storing this in table until table schema done
// array_walk(
// $mappings,
// function (&$input) {
// $variable = $input["uid"];
// $instance = (int) explode("__", $variable)[1] ?? 0;
// $input["instance"] = $instance;
// }
// );
return $mappings;
}
public function redcap_module_link_check_display($project_id, $link) {
$public_pages = ["configPage", "sdtmToRedcapStudyLevel", "sdtmToRedcapSubjectLevel"];
$cur_user = $this->getUser()->getUsername();
// HACK: keep my beta testers form seeing my hacky test pages replace with actual e2e tests
$is_admin = in_array($cur_user, ["admin", "kyle.chesney@vumc.org"]);
// HACK: hide pages that are angry
//$public_pages = ["twigpage1"];
if (
!in_array($link['key'], $public_pages) &&
!$is_admin) {
return null;
}
return $link;
}
/////////////////////////////////////////////////////////////////////////////
// API Interface //
/////////////////////////////////////////////////////////////////////////////
public function makeRequest(string $api_path) {
$api_key = $this->getSystemSetting("cdisc_api_key");
// Create a client instance
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://api.library.cdisc.org/api/',
'headers' => [
'Authorization' => "Subscription key",
'Cache-Control' => "no-cache",
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'api-key' => $api_key
]
]);
// Send a GET request to a specific URI
try {
// $response = $client->request('GET', 'mdr/products/DataTabulation');
$response = $client->get($api_path);
// or use the shortcut:
// $response = $client->get('user/123');
// Get the response body as a string
$body = $response->getBody()->getContents();
// Decode JSON response into a PHP array or object
$data = json_decode($body, true);
// Print the data (for demonstration)
return $data;
} catch (GuzzleHttp\Exception\RequestException $e) {
// Handle exceptions (e.g., 4xx or 5xx errors)
echo 'Error: ' . $e->getMessage();
}
}
public function getSDTMIGs() {
// Always makes an API call because this must be up to date
$api_path = "mdr/products/DataTabulation?expand=true";
$stds = $this->makeRequest($api_path);
// filter for registrationStatus = Final
$igs = array_filter(
$stds["_links"]["sdtmig"],
fn ($ig) => (
$ig['registrationStatus'] === "Final" &&
$ig['type'] === "Implementation Guide" &&
str_starts_with($ig['name'], "SDTMIG ") // exclude -MD and -AP
)
);
// descending release date order
usort(
$igs,
function ($a, $b) {
$date_a = new \DateTime($a['effectiveDate']);
$date_b = new \DateTime($b['effectiveDate']);
// edge case, shouldn't happen
if ($date_a == $date_b) {
return 0;
}
return $date_a > $date_b ? -1 : 1;
}
);
// order by effectiveDate
return $igs;
}
public function getInfo() {
$api_path = "mdr/sdtmig/3-4?expand=true";
$stds = $this->makeRequest($api_path);
// TODO:
// filter for registrationStatus = Final
// order by effectiveDate
return $stds;
}
public function getDomains($level = "study") {
// HACK: why no use stored?
// HACK: replace entirely with API pull
$target_file = $this->getModulePath() . "sdtmig_v3.4.json";
$file_data = json_decode(file_get_contents($target_file), true);
return $file_data;
// Always calls API because this is used in config, where up to date IGs must be sourced
$active_sdtmig = $this->getProjectSetting("active_sdtmig");
$api_path = $active_sdtmig . "?expand=true";
// TODO: above no work :(
$api_path = "mdr/sdtmig/3-4?expand=true";
$stds = $this->makeRequest($api_path);
// TODO:
// filter for registrationStatus = Final
// order by effectiveDate
return $stds;
}
/////////////////////////////////////////////////////////////////////////////
// Other //
/////////////////////////////////////////////////////////////////////////////
// TODO: store and fetch from a reserved file repository
// see crispi clone EM for this
private function writeToEdocs() {
// TODO: saveFile in EMFW needs to exist again
$stds = $this->getInfo();
// TODO: tmpfile
$file_path = $this->getModulePath() . 'sdtmig_v3.4.json';
$file_handle = fopen($file_path, 'w');
if ($file_handle) {
fwrite($file_handle, json_encode($stds));
fclose($file_handle);
echo "Data written using fopen/fwrite/fclose.";
} else {
echo "Could not open file for writing.";
}
}
public function applyMappingToRecord($record_id, string|null $domain_filter = null) {
$db_file_name = PROJECT_ID . "_sdtm_mappings.db";
$db_full_path = $this->getModulePath() . $db_file_name;
$sdtmi = new SDTMInterface($db_full_path);
$mappings = $sdtmi->getMappings($domain_filter);
//return $mappings;
// TODO: break into domain and instance
/*
* [
* [
* domain => "LB",
* "instances" => [
* 0 => [$mappings],
* 1 => [$mappings],
* ...
* ]
* ]
* ]
*/
$result = [];
foreach ($mappings as $m) {
// TODO: process conditional logic for an instance prior to attempting any other calcs
// HACK: if they deleted their inputs, don't show this
if ($m['calc_text'] === "" || empty($m['calc_text'])) {
continue;
}
$this_result = [
...$m,
"result" => null
];
$result[$m['uid']] = $this_result;
$is_valid_logic = \LogicTester::isValid($m['calc_text']);
if (!$is_valid_logic) {
$this_result["result"] = "invalid logic";
$result[$m['uid']] = $this_result;
continue;
}
// override record_data, extremely similar to base evaluateLogicSingleRecord, but we don't want empty events
// TODO: for fields, should be able to detect source form, from there can eval event/arm assoc and broadcast
// var_dump($is_valid_logic);
// TODO: if field in calc_text, need to prepend with every event/arm the field exists in?
$r = \LogicTester::evaluateLogicSingleRecord(
raw_logic: $m['calc_text'],
// record: 12217,
record: $record_id,
// repeat_instance: 1,
returnValue: true
);
// HACK: json decode completely breaks for nan values, PHP's is_nan also completely breaks if value is a string
// this appears to be the case from dropdown fields
if (is_float($r) && is_nan($r)) {
$r = "NaN";
}
$this_result["result"] = $r;
$result[$m['uid']] = $this_result;
}
// sort by domain, instance, key
uasort($result, function($a, $b) {
return (
$a['domain'] <=> $b['domain'] ?:
($a['instance'] <=> $b['instance']) ?:
($a['uid'] <=> $b['uid'])
);
}
);
return $result;
$record_data = \REDCap::getData([
// 'return_format' => "json-array",
"records" => [$record_id]
]);
// order by domain and instance
// if conditional logic blocks processing, just skip it
$LP = new \LogicParser();
$logic_basic = "[record_id:value] = 12217";
$lp_result = $LP->parse(
str: "[record_id] = 12217",
isCalcField: true
);
// FIXME: record ID when first form is repeating may get missed
// NOTE: logic string must be:
// [$field-on-repeat][$idx]
// hdr_date is LBW0150 Hematologies Date of Patient Visit
$logic_basic = "[hdr_date][first-instance]";
$logic_basic = "[record_id] = 12217";
$logic_basic = "[record_id] = 1";
$logic_basic = "[prim_scryn]";
// $logic_basic = "[hdr_date][2]";
// NOTE: look at the source code of buildLogicArgs, repeat detection is unreliable
// need to force instanceVar to be set in the logic string
// TODO: incorporate record_data param to try to process arms separately?
$r = \LogicTester::evaluateLogicSingleRecord(
raw_logic: $logic_basic,
// record: 12217,
record: 1,
// repeat_instance: 1,
returnValue: true
);
// NOTE: 2nd arg is event_id if providing record_data?
// $r = \LogicTester::evaluateLogicSingleRecord($logic_basic, 12217, $record_data);
// $r = \LogicTester::evaluateCondition($logic_basic, $record_data);
return $r;
return $mappings;
}
public function validateLogic($calc_text) {
return \LogicTester::isValid($calc_text);
}
public function storeEdoc() {
// TODO: json returned from API should be stored as an edoc
}
}