Repository navigation
Expand file tree
/
Copy pathAnnotationRules.php
More file actions
3266 lines (3168 loc) · 176 KB
/
Copy pathAnnotationRules.php
File metadata and controls
3266 lines (3168 loc) · 176 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
/**
* AnnotationRules — @UVALIDATE action-tag-style configuration.
*
* Lets a data manager attach validation where they already design fields: the
* "Action Tags / Field Annotation" box in the Online Designer, or the
* field_annotation column of a data dictionary CSV — which makes bulk
* configuration a spreadsheet edit + one upload instead of clicking through the
* module dialog per field. Three forms:
*
* @UVALIDATE default check (ISO 7064 Mod 37,36), message only
* @UVALIDATE=iso7064_mod11_10 pick the check-character algorithm
* @UVALIDATE={"algorithm":"none","pattern":"FC[0-9]{4}","blockSave":"hard"}
* full rule as JSON
*
* JSON keys: type ("single"|"pooled"), algorithm, source, pattern, strip,
* keepChars, idLengths (list or "10, 12"), idMinLen, idMaxLen, expectedIds,
* blockSave ("off"|"confirm"|"hard"), when (a REDCap-style condition — the
* rule validates only while it is true, see php/Logic.php), suggestFix
* (boolean; opt IN to the "should end in X" check-character hint), note. A
* malformed value becomes a visible per-field configuration error — never a
* silently skipped rule.
*
* Pure static class with no REDCap dependency, unit-tested by
* tests/annotation_php.php; UniversalValidator::getAnnotationRules() is the thin
* glue that feeds it the project's data dictionary.
*/
namespace INSPIRE\UniversalValidator;
require_once __DIR__ . '/CheckCharacter.php';
require_once __DIR__ . '/Logic.php';
require_once __DIR__ . '/ModeRegistry.php';
require_once __DIR__ . '/TemporalLogic.php';
require_once __DIR__ . '/GrowthReference.php';
require_once __DIR__ . '/GrowthOutputs.php';
require_once __DIR__ . '/GrowthCurve.php';
class AnnotationRules
{
const TAG = '@UVALIDATE';
const TAG_ASSERT = '@UVASSERT';
const TAG_REQUIRED = '@UVREQUIRED';
const TAG_UNIQUE = '@UVUNIQUE';
const TAG_CHOICES = '@UVCHOICES';
const TAG_WINDOW = '@UVWINDOW';
const TAG_EXISTS = '@UVEXISTS';
const TAG_RANGE = '@UVRANGE';
/** Most languages one text key (a "message" map) may name, "default" included. */
const MAX_TEXT_LANGUAGES = 50;
/** Longest @UVRANGE "unit" text: a label such as "g/dL", not a sentence. */
const MAX_RANGE_UNIT = 20;
/** Longest @UVRANGE limit, in characters once any exponent is written out. */
const MAX_RANGE_BOUND = 64;
/** With a growth "reference", the limits are z-scores no further than this from 0. */
const MAX_GROWTH_Z = 20;
/** "measureScale" bounds: a millionth (micrograms to grams) to a million. */
const MIN_MEASURE_SCALE = '0.000001';
const MAX_MEASURE_SCALE = '1000000';
/** Cap on @UVRANGE "return" pairs; what each key may name is php/growth_outputs.json (GrowthOutputs). */
const MAX_RANGE_RETURN = 16;
/** The limits a rule's returned bounds come from ("returnLimits"; soft is the default). */
const RETURN_LIMITS = ['soft', 'hard'];
/** Where an @UVEXISTS lookup may search: the whole project (default), the
* record's own Data Access Group, or the event of the entry being checked. */
const EXISTS_SCOPES = ['project', 'dag', 'event'];
/** Cap on @UVEXISTS "match" pairs, so a lookup stays one narrow read. */
const MAX_EXISTS_MATCH = 5;
/** Cap on @UVEXISTS "return" pairs: the fields one lookup writes into this form. */
const MAX_EXISTS_RETURN = 10;
/** Cap on the distinct fields an @UVEXISTS "where" condition tests in the entry found. */
const MAX_EXISTS_WHERE = 10;
/**
* An @UVEXISTS "project": a project id, or an alias the project's own
* settings map to one (so a data dictionary moves between servers unchanged).
*/
const EXISTS_PROJECT_RE = '/^(?:[1-9][0-9]{0,9}|[a-z][a-z0-9_-]{0,39})$/';
/** Largest window bound, in units either side of the anchor. */
const MAX_WINDOW_BOUND = 36500;
/** The most periods a @UVWINDOW "offset" moves either way (100 years of months). */
const MAX_WINDOW_OFFSET = 1200;
/** A date written in a @UVWINDOW "from": Y-M-D, with an optional time to the minute or second. */
const WINDOW_LITERAL_RE = '/^\d{4}-\d{2}-\d{2}(?: \d{2}:\d{2}(?::\d{2})?)?$/D';
/*
* Which tag configures which validation MODE, the field types each mode
* accepts, and the parser/validator each one uses all live in
* php/modes.json (served by ModeRegistry). Different modes on one field
* COMPOSE (all must pass); several tags of the SAME mode on one field
* branch (php/Branching.php). The mode travels on the rule as its "type"
* (single|pooled = check; constraint; required; ...), which is what the
* client dispatcher, the server audit, and Branching all key on.
*/
/** Uniqueness scopes: whole project (default), within the record's Data
* Access Group, or within the same event of a longitudinal project. */
const UNIQUE_SCOPES = ['project', 'dag', 'event'];
/** Composite-key size cap: [field]+with must stay a cheap lookup. */
const MAX_UNIQUE_WITH = 5;
/** Cap on the other fields a unique value is also looked for in ("also"):
* each one widens every lookup's read by one field. */
const MAX_UNIQUE_ALSO = 5;
/** Cap on the show/hide code list: filtering is a per-choice DOM walk on
* every re-evaluation, so the list must stay small. REDCap fields with
* more choices than this belong in an autocomplete dropdown anyway. */
const MAX_CHOICE_CODES = 200;
const ALGORITHMS = [
'iso7064_mod37_36', 'iso7064_mod11_10', 'iso7064_mod97_10',
'iso7064_mod11_2', 'iso7064_mod37_2', 'iso7064_letters1',
'iso7064_letters2', 'damm', 'verhoeff', 'luhn',
'gs1_mod10', 'aba_mod10', 'mrz_mod10', 'weighted_mod11', 'none',
];
/**
* Friendly shorthands for the algorithm names, so a data manager can write
* @UVALIDATE=3736 (or 37,36, mod37_36, ...) instead of the full
* iso7064_mod37_36. This is the SINGLE source of truth for synonyms —
* canonicalAlgorithm() resolves against it, the dialog dropdown stores
* canonical names directly, and the client always receives canonical names
* (the config is built server-side), so nothing else needs a synonym table.
*
* To add a shorthand: add it to the right canonical row here (lowercase),
* then run tests/annotation_php.php — a collision guard there fails if a
* shorthand clashes with a canonical name or another shorthand.
*
* Format: CANONICAL => [ shorthand, shorthand, ... ] (all lowercase).
*/
const ALGORITHM_SYNONYMS = [
'iso7064_mod37_36' => ['3736', '37_36', '37-36', '37,36', 'mod37_36', 'mod3736'],
'iso7064_mod11_10' => ['1110', '11_10', '11-10', '11,10', 'mod11_10', 'mod1110'],
'iso7064_mod97_10' => ['9710', '97_10', '97-10', '97,10', 'mod97_10', 'mod9710'],
'iso7064_mod11_2' => ['112', '11_2', '11-2', '11,2', 'mod11_2', 'mod112'],
'iso7064_mod37_2' => ['372', '37_2', '37-2', '37,2', 'mod37_2', 'mod372'],
'iso7064_letters1' => ['letters1', 'letter1'],
'iso7064_letters2' => ['letters2', 'letter2'],
'luhn' => ['mod10'],
'gs1_mod10' => ['gs1', 'gtin', 'ean', 'upc'],
'aba_mod10' => ['aba', 'routing'],
'mrz_mod10' => ['mrz', 'icao'],
'weighted_mod11' => ['isbn', 'mod11w', 'weighted11'],
'none' => ['regex', 'format'],
];
/** Keys accepted in the JSON form ("pattern" maps to the engine's idPattern). */
const JSON_KEYS = ['type', 'algorithm', 'source', 'pattern', 'alternates', 'strip', 'keepChars',
'idLengths', 'idMinLen', 'idMaxLen', 'expectedIds', 'blockSave', 'when',
'suggestFix', 'note', 'caseSensitive'];
/** Keys accepted INSIDE one entry of the "alternates" list. */
const ALT_KEYS = ['pattern', 'algorithm', 'source', 'strip', 'lengths', 'label'];
/**
* Resolve a user-typed algorithm shorthand to its canonical name.
*
* Matching is case-insensitive. An already-canonical name (any case) is
* returned canonical; an unrecognized value is returned UNCHANGED, so the
* existing "unknown algorithm" whitelist error still fires for real typos.
* Applied at every point a raw algorithm string is read into a rule, so the
* stored value — and therefore the check-character engine and the client —
* always sees a canonical name.
*/
public static function canonicalAlgorithm($name)
{
if (!is_string($name) || $name === '') return $name;
if (in_array($name, self::ALGORITHMS, true)) return $name; // fast path: already canonical
$key = strtolower(trim($name));
if (in_array($key, self::ALGORITHMS, true)) return $key; // canonical, just wrong case
foreach (self::ALGORITHM_SYNONYMS as $canonical => $synonyms) {
if (in_array($key, $synonyms, true)) return $canonical;
}
return $name; // unknown -> unchanged
}
/**
* Extract the raw value of the FIRST @UVALIDATE tag (compatibility form).
* Returns null when the tag is absent, '' for the bare tag, otherwise the
* value text (bare token, 'quoted', "quoted", or a brace-balanced {...}).
*/
public static function extractTag($annotation)
{
$tags = self::extractTags($annotation);
return $tags ? $tags[0] : null;
}
/**
* Extract EVERY real @UVALIDATE tag value from an annotation, in order —
* one field may carry several tags since 0.9.0 (branched validation: each
* tag becomes its own rule, and Branching::resolve() turns the sharing
* into a per-field branch rule or a config error). Returns [] when no tag
* is present; a bare tag contributes ''.
*/
public static function extractTags($annotation)
{
return self::extractTagsFor($annotation, self::TAG);
}
/**
* Extract every real occurrence of ONE tag from an annotation, in order.
* Generalized from extractTags so each module tag (@UVALIDATE, @UVASSERT,
* …) is scanned by the same value-boundary rules. A tag ends at '=',
* whitespace, or end-of-string, so @UVALIDATED / @UVASSERTS never match.
*/
public static function extractTagsFor($annotation, $tag)
{
return array_column(self::extractTagsDetailed($annotation, $tag), 'value');
}
/**
* extractTagsFor with each value's reading problem: a list of
* ['value' => string, 'error' => string|null]. $bare says how an unquoted,
* non-JSON value ends: 'token' (at the first space, the default) or
* 'condition' (the whole condition, for the tags whose bare value IS one —
* see Logic::parsePrefix). A condition that goes on past the point where it
* can be read gets an error instead of being cut short.
*/
public static function extractTagsDetailed($annotation, $tag, $bare = 'token')
{
$ann = (string) $annotation;
$len = strlen($ann);
$out = [];
$offset = 0;
while ($offset < $len) {
$pos = stripos($ann, $tag, $offset);
while ($pos !== false) {
$after = $pos + strlen($tag);
$ch = $after < $len ? $ann[$after] : '';
// a real tag ends at '=', whitespace, or end-of-string;
// @UVALIDATED / @UVALIDATE2 are different tags — keep scanning.
if ($ch === '' || $ch === '=' || ctype_space($ch)) break;
$pos = stripos($ann, $tag, $after);
}
if ($pos === false) break;
$after = $pos + strlen($tag);
if ($after >= $len || $ann[$after] !== '=') {
$out[] = ['value' => '', 'error' => null];
$offset = $after;
continue;
}
$read = self::readValue(substr($ann, $after + 1), $bare);
$eg = $tag . '="[a]=\'1\' and [b]=\'2\'".';
$out[] = ['value' => $read['value'], 'error' => !$read['continues'] ? null
: (isset($read['hint'])
? 'reads as the condition "' . $read['value'] . '" followed by more of a condition, which ' . $read['hint']
. ' Then put the whole condition in quotes, e.g. ' . $eg
: 'reads as the condition "' . $read['value'] . '" followed by more of a condition — put the whole condition in quotes, e.g. '
. $eg)];
// Advance PAST the consumed value so tag-like text inside a value
// (e.g. a pattern containing "@UVALIDATE") is never re-read as a
// second tag. Quoted values also consumed their two quote marks.
$offset = $after + 1 + $read['length'];
}
return $out;
}
/**
* Read one tag value: {json} (brace-balanced), quoted text, or a bare
* value — one token, or with $bare 'condition' the longest condition.
* Returns ['value', 'length' => bytes consumed, 'continues' => bool], plus
* 'hint' (Logic::parsePrefix) when a condition goes on with "&&", "||" or "!".
*/
private static function readValue($rest, $bare = 'token')
{
$plain = function ($v, $length = null) {
return ['value' => $v, 'length' => $length === null ? strlen($v) : $length, 'continues' => false];
};
if ($rest === '') return $plain('');
$c = $rest[0];
if ($c === '{') {
$depth = 0; $inStr = false; $esc = false;
$n = strlen($rest);
for ($i = 0; $i < $n; $i++) {
$ch = $rest[$i];
if ($inStr) {
if ($esc) { $esc = false; }
elseif ($ch === '\\') { $esc = true; }
elseif ($ch === '"') { $inStr = false; }
continue;
}
if ($ch === '"') { $inStr = true; continue; }
if ($ch === '{') { $depth++; }
elseif ($ch === '}') {
$depth--;
if ($depth === 0) return $plain(substr($rest, 0, $i + 1));
}
}
return $plain($rest); // unbalanced — parseField reports it as bad JSON
}
if ($c === '"' || $c === "'") {
$end = strpos($rest, $c, 1);
return $end === false ? $plain(substr($rest, 1), strlen($rest))
: $plain(substr($rest, 1, $end - 1), $end + 1);
}
if ($bare === 'condition') {
$p = Logic::parsePrefix($rest);
if ($p['length'] > 0) {
return ['value' => substr($rest, 0, $p['length']), 'length' => $p['length'], 'continues' => $p['continues'],
'hint' => $p['hint']];
}
// nothing parses: keep the first token, so the parser reports the
// condition's own error, as before
}
preg_match('/^\S+/', $rest, $m);
return $plain($m ? $m[0] : '');
}
/**
* Parse one field's annotation into a rule fragment (engine keys, without
* 'fields'): [] means "all defaults", ['error' => msg] a visible config
* error, null an untagged field. Compatibility form — reads the FIRST tag.
*/
public static function parseField($annotation)
{
$all = self::parseFieldAll($annotation);
return $all === null ? null : $all[0];
}
/**
* Parse EVERY @UVALIDATE tag of one field's annotation: null for an
* untagged field, otherwise a list of fragments (each [] | ['error'=>...]
* | engine-key config), one per tag, in annotation order.
*/
public static function parseFieldAll($annotation, array $opts = [])
{
$tags = self::extractTags($annotation);
if (!$tags) return null;
$out = [];
foreach ($tags as $val) $out[] = self::parseValue($val, $opts);
return $out;
}
/**
* Parse EVERY module tag on one field's annotation, across all modes
* (@UVALIDATE check rules AND the intent-named mode tags like @UVASSERT):
* null when the field carries none, else a list of fragments in tag order
* (each [] | engine-key config | ['error'=>msg, '_tag'=>tag]). A fragment's
* "type" carries its mode, so groupMulti/Branching/the audit route it. This
* is the multi-mode superset of parseFieldAll (which stays @UVALIDATE-only
* for back-compat).
*/
public static function parseAllTags($annotation, array $opts = [])
{
$any = false;
$out = [];
foreach (ModeRegistry::tagMap() as $tag => $mode) {
$parser = ModeRegistry::mode($mode)['parser'];
foreach (self::extractTagsDetailed($annotation, $tag, ModeRegistry::bareValue($mode)) as $read) {
$any = true;
$frag = $read['error'] !== null ? ['error' => $tag . ' ' . $read['error']] : self::$parser($read['value'], $opts);
if (isset($frag['error'])) $frag['_tag'] = $tag; // so groupMulti names the right tag
$out[] = $frag;
}
}
return $any ? $out : null;
}
/**
* Parse one @UVUNIQUE value into a unique fragment. Three forms:
* @UVUNIQUE unique across the whole project
* @UVUNIQUE=event pick a scope (project | dag | event)
* @UVUNIQUE={"with":["site"],"scope":"event","when":"...",
* "message":"...","blockSave":"hard","surveys":true,
* "also":["typed_id"]}
* "with" makes the key composite (value + those fields together must be
* unique). "also" looks for the value in those other fields of the other
* records too, so a value saved in either field counts as used.
* "surveys" is an explicit OPT-IN: a live used/free answer is
* record-derived information, so survey respondents only get the check
* when the designer decides the trade-off is acceptable (the server
* answers surveys with a boolean only, never a record id).
*/
private static function parseUniqueValue($val, array $opts = [])
{
$val = trim($val);
if ($val === '') {
$out = ['type' => 'unique'];
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
if ($val[0] !== '{') {
$scope = strtolower($val);
if (!in_array($scope, !empty($opts['qualified']) ? array_merge(self::UNIQUE_SCOPES, ['record']) : self::UNIQUE_SCOPES, true)) {
return ['error' => self::TAG_UNIQUE . '=' . $val . ' is not a scope — use '
. implode(', ', self::UNIQUE_SCOPES) . ', or the JSON form for other options.'];
}
$out = ['type' => 'unique', 'uniqueScope' => $scope];
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
$cfg = json_decode($val, true);
if (!is_array($cfg)) {
return ['error' => self::TAG_UNIQUE . ' JSON does not parse ('
. json_last_error_msg() . ') — use double quotes around keys and string values.'];
}
$allowed = ['with', 'also', 'scope', 'when', 'message', 'blockSave', 'surveys', 'caseSensitive', 'references'];
$unknown = array_diff(array_keys($cfg), $allowed);
if ($unknown) {
return ['error' => 'unknown ' . self::TAG_UNIQUE . ' option(s): ' . implode(', ', $unknown)
. ' — valid: ' . implode(', ', $allowed) . '.'];
}
$out = ['type' => 'unique'];
if (isset($cfg['with'])) {
if (!is_array($cfg['with'])) return ['error' => '"with" must be a list of field names, e.g. ["site"].'];
// Field names are lowercase in REDCap — normalize here so the rule,
// the client payload and the server lookup all agree.
$out['uniqueWith'] = array_map(function ($w) {
return is_string($w) ? strtolower(trim($w)) : $w;
}, array_values($cfg['with']));
}
if (isset($cfg['also'])) {
if (!is_array($cfg['also'])) return ['error' => '"also" must be a list of field names, e.g. ["typed_id"].'];
$out['uniqueAlso'] = array_map(function ($a) {
return is_string($a) ? strtolower(trim($a)) : $a;
}, array_values($cfg['also']));
}
if (isset($cfg['scope'])) {
if (!is_string($cfg['scope'])) return ['error' => '"scope" must be a string.'];
$out['uniqueScope'] = strtolower($cfg['scope']);
}
if (isset($cfg['surveys'])) {
if (!is_bool($cfg['surveys'])) return ['error' => '"surveys" must be true or false (unquoted).'];
$out['uniqueSurveys'] = $cfg['surveys'];
}
if (($e = self::takeTexts($cfg, $out)) !== null) return ['error' => $e];
foreach (['when', 'message', 'blockSave'] as $k) {
if (isset($cfg[$k])) {
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be a string.'];
$out[$k] = $cfg[$k];
}
}
self::takeCaseSensitive($cfg, $out);
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
/**
* Parse one @UVCHOICES value into a choices fragment (dynamic choice
* filtering: show/hide individual options of a radio, dropdown or checkbox
* field while a condition holds). JSON form only — the tag has no sensible
* bare default, and a shorthand would just be a second grammar to learn:
* @UVCHOICES={"when":"[country]='1'","show":["101","102"]}
* @UVCHOICES={"when":"[legacy]<>'1'","hide":["9"],"blockSave":"hard"}
* Exactly one of "show" (whitelist — everything else hides) or "hide"
* (blacklist) per tag. Several tags on one field branch via Branching, so
* a country→site cascade is one tag per country. A currently-selected
* choice that becomes hidden is NEVER cleared — it stays visible, flagged
* invalid, and blockSave decides whether the save is challenged.
*/
private static function parseChoicesValue($val, array $opts = [])
{
$val = trim($val);
if ($val === '' || $val[0] !== '{') {
return ['error' => self::TAG_CHOICES . ' needs a show or hide list — use the JSON form, e.g. '
. self::TAG_CHOICES . '={"when":"[country]=\'1\'","show":["101","102"]}.'];
}
$cfg = json_decode($val, true);
if (!is_array($cfg)) {
return ['error' => self::TAG_CHOICES . ' JSON does not parse ('
. json_last_error_msg() . ') — use double quotes around keys and string values.'];
}
$allowed = ['when', 'show', 'hide', 'message', 'blockSave', 'caseSensitive', 'references'];
$unknown = array_diff(array_keys($cfg), $allowed);
if ($unknown) {
return ['error' => 'unknown ' . self::TAG_CHOICES . ' option(s): ' . implode(', ', $unknown)
. ' — valid: ' . implode(', ', $allowed) . '.'];
}
$out = ['type' => 'choices'];
foreach (['show' => 'choicesShow', 'hide' => 'choicesHide'] as $k => $ruleKey) {
if (!isset($cfg[$k])) continue;
if (!is_array($cfg[$k])) {
return ['error' => '"' . $k . '" must be a list of choice codes, e.g. ["1","2"].'];
}
$codes = [];
foreach (array_values($cfg[$k]) as $c) {
// Codes may be typed unquoted (JSON numbers) — normalize every
// scalar to its trimmed string form, the shape REDCap stores.
if (!is_string($c) && !is_int($c) && !is_float($c)) {
return ['error' => '"' . $k . '" entry ' . json_encode($c)
. ' is not a choice code — use strings or numbers.'];
}
$codes[] = trim((string) $c);
}
$out[$ruleKey] = $codes;
}
if (($e = self::takeTexts($cfg, $out)) !== null) return ['error' => $e];
foreach (['when', 'message', 'blockSave'] as $k) {
if (isset($cfg[$k])) {
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be a string.'];
$out[$k] = $cfg[$k];
}
}
self::takeCaseSensitive($cfg, $out);
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
/**
* Parse one @UVREQUIRED value into a required fragment. Three forms:
* @UVREQUIRED always required (while non-blank saves)
* @UVREQUIRED="[consent]='1'" required only WHILE the condition is
* true (the value IS the "when")
* @UVREQUIRED={"when":"...","message":"...","blockSave":"hard"}
* A blank field is invalid while required; a filled field simply clears the
* notice (required mode never judges the VALUE — pair with @UVALIDATE or
* @UVASSERT for that; the modes compose).
*/
private static function parseRequiredValue($val, array $opts = [])
{
$val = trim($val);
if ($val === '') {
$out = ['type' => 'required'];
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
if ($val[0] !== '{') {
$out = ['type' => 'required', 'when' => $val];
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
$cfg = json_decode($val, true);
if (!is_array($cfg)) {
return ['error' => self::TAG_REQUIRED . ' JSON does not parse ('
. json_last_error_msg() . ') — use double quotes around keys and string values.'];
}
$strings = ['when', 'message', 'blockSave'];
$allowed = array_merge($strings, ['caseSensitive', 'references']);
$unknown = array_diff(array_keys($cfg), $allowed);
if ($unknown) {
return ['error' => 'unknown ' . self::TAG_REQUIRED . ' option(s): ' . implode(', ', $unknown)
. ' — valid: ' . implode(', ', $allowed) . '.'];
}
$out = ['type' => 'required'];
if (($e = self::takeTexts($cfg, $out)) !== null) return ['error' => $e];
foreach ($strings as $k) {
if (isset($cfg[$k])) {
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be a string.'];
$out[$k] = $cfg[$k];
}
}
self::takeCaseSensitive($cfg, $out);
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
/**
* Parse one @UVASSERT value into a constraint fragment. The value is EITHER
* the condition itself (@UVASSERT="[end]>=[start]") or a JSON object
* {assert, message, blockSave, when, caseSensitive}. The field is invalid
* whenever the condition is false; an empty field is inert (that is
* @UVREQUIRED's job). Text compares case-insensitively ('Yes' = 'yes')
* unless "caseSensitive" is true, in the "assert" and the "when" alike.
*/
private static function parseAssertValue($val, array $opts = [])
{
$val = trim($val);
if ($val === '') {
return ['error' => self::TAG_ASSERT . ' needs a condition — e.g. '
. self::TAG_ASSERT . '="[end_date]>=[start_date]".'];
}
if ($val[0] !== '{') {
$out = ['type' => 'constraint', 'assert' => $val];
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
$cfg = json_decode($val, true);
if (!is_array($cfg)) {
return ['error' => self::TAG_ASSERT . ' JSON does not parse ('
. json_last_error_msg() . ') — use double quotes around keys and string values.'];
}
$strings = ['assert', 'message', 'blockSave', 'when'];
$allowed = array_merge($strings, ['caseSensitive', 'references']);
$unknown = array_diff(array_keys($cfg), $allowed);
if ($unknown) {
return ['error' => 'unknown ' . self::TAG_ASSERT . ' option(s): ' . implode(', ', $unknown)
. ' — valid: ' . implode(', ', $allowed) . '.'];
}
$out = ['type' => 'constraint'];
if (($e = self::takeTexts($cfg, $out)) !== null) return ['error' => $e];
foreach ($strings as $k) {
if (isset($cfg[$k])) {
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be a string.'];
$out[$k] = $cfg[$k];
}
}
self::takeCaseSensitive($cfg, $out);
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
/**
* Parse one @UVWINDOW value into a window fragment (a date must fall in a
* window around another date, and/or not after today). JSON form only:
* @UVWINDOW={"from":"[visit_date_bl]","window":[21,35],"unit":"days"}
* @UVWINDOW={"from":"[dob]","window":[0,null]} not before the anchor
* @UVWINDOW={"notFuture":true} not after today
* @UVWINDOW={"notPast":true} not before today
* @UVWINDOW={"from":"today","window":[-30,0]} within the last 30 days
* @UVWINDOW={"from":"[enrol]","window":[0,6],"unit":"months"}
* @UVWINDOW={"period":"month","offset":-1} last month
* @UVWINDOW={"period":"week","from":"[visit_date]"} the week of visit_date
* "window" is [earliest, latest] in whole units from the "from" date,
* inclusive; null leaves that side open. "from" is a field reference, which
* may name another event ([baseline_arm_1][visit_date]) once event and
* instance references are enabled, or "today", "now" or a Y-M-D date
* (windowAnchor). A "period" (week, month, quarter, year) is the calendar
* period holding the "from" date, today when there is none, moved by
* "offset" periods (a whole number or [first, last]). Whether the field
* and its "from" field are date fields of the same kind is checked with
* the data dictionary in hand (UniversalValidator::annotateWindowField /
* annotateWindowDictionary).
*/
private static function parseWindowValue($val, array $opts = [])
{
$val = trim($val);
if ($val === '' || $val[0] !== '{') {
return ['error' => self::TAG_WINDOW . ' needs its settings as JSON, e.g. '
. self::TAG_WINDOW . '={"from":"[visit_date_bl]","window":[21,35]} or '
. self::TAG_WINDOW . '={"notFuture":true}.'];
}
$cfg = json_decode($val, true);
if (!is_array($cfg)) {
return ['error' => self::TAG_WINDOW . ' JSON does not parse ('
. json_last_error_msg() . ') — use double quotes around keys and string values.'];
}
$allowed = ['from', 'window', 'unit', 'period', 'offset', 'weekStart', 'notFuture', 'notPast',
'when', 'message', 'blockSave', 'caseSensitive', 'references'];
$unknown = array_diff(array_keys($cfg), $allowed);
if ($unknown) {
return ['error' => 'unknown ' . self::TAG_WINDOW . ' option(s): ' . implode(', ', $unknown)
. ' — valid: ' . implode(', ', $allowed) . '.'];
}
$out = ['type' => 'window'];
if (array_key_exists('from', $cfg)) {
if (!is_string($cfg['from'])) {
return ['error' => '"from" must be a field reference such as "[visit_date]", "today", "now" or a date such as "2026-01-01".'];
}
$from = trim($cfg['from']);
$kw = strtolower($from);
// "today", "now" and a written date are not fields: they travel
// as windowAnchor, so no field-reference path ever reads them.
if ($kw === 'today' || $kw === 'now') $out['windowAnchor'] = $kw;
elseif (preg_match(self::WINDOW_LITERAL_RE, $from)) $out['windowAnchor'] = $from;
else $out['windowFrom'] = $from;
}
if (array_key_exists('period', $cfg)) {
if (!is_string($cfg['period'])) return ['error' => '"period" must be week, month, quarter or year.'];
$out['windowPeriod'] = strtolower(trim($cfg['period']));
// A period with no "from" is the period holding today.
if (!isset($out['windowFrom']) && !isset($out['windowAnchor'])) $out['windowAnchor'] = 'today';
}
if (array_key_exists('offset', $cfg)) {
$o = $cfg['offset'];
if (is_array($o)) {
if (array_keys($o) !== [0, 1]) {
return ['error' => '"offset" must be a whole number of periods, or [first, last] — e.g. -1 for the last one, [-3,-1] for the three before this one.'];
}
$out['windowOffLo'] = $o[0];
$out['windowOffHi'] = $o[1];
} else {
$out['windowOffLo'] = $o;
$out['windowOffHi'] = $o;
}
// An offset of 0 is the default, dropped so two spellings of one rule group as one.
if (isset($out['windowPeriod']) && $out['windowOffLo'] === 0 && $out['windowOffHi'] === 0) {
unset($out['windowOffLo'], $out['windowOffHi']);
}
}
if (array_key_exists('weekStart', $cfg)) {
if (!is_string($cfg['weekStart'])) return ['error' => '"weekStart" must be monday or sunday.'];
$out['windowWeekStart'] = strtolower(trim($cfg['weekStart']));
}
if (array_key_exists('window', $cfg)) {
$w = $cfg['window'];
if (!is_array($w) || array_keys($w) !== [0, 1]) {
return ['error' => '"window" must be a list of two bounds, [earliest, latest] — e.g. [21,35], or [0,null] for an open end.'];
}
if ($w[0] === null && $w[1] === null) {
return ['error' => '"window" needs at least one bound — [null,null] would check nothing.'];
}
// An open side is simply absent from the rule, so two rules that
// differ only in how they spelled "open" still group as one.
if ($w[0] !== null) $out['windowLo'] = $w[0];
if ($w[1] !== null) $out['windowHi'] = $w[1];
}
if (array_key_exists('unit', $cfg)) {
if (!is_string($cfg['unit'])) return ['error' => '"unit" must be a string.'];
$out['windowUnit'] = strtolower(trim($cfg['unit']));
} elseif ((isset($out['windowFrom']) || isset($out['windowAnchor'])) && !isset($out['windowPeriod'])) {
$out['windowUnit'] = 'days';
}
// An explicit false IS the default, so it is dropped, as caseSensitive is.
if (array_key_exists('notFuture', $cfg) && $cfg['notFuture'] !== false) $out['windowNotFuture'] = $cfg['notFuture'];
if (array_key_exists('notPast', $cfg) && $cfg['notPast'] !== false) $out['windowNotPast'] = $cfg['notPast'];
if (($e = self::takeTexts($cfg, $out)) !== null) return ['error' => $e];
foreach (['when', 'message', 'blockSave'] as $k) {
if (isset($cfg[$k])) {
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be a string.'];
$out[$k] = $cfg[$k];
}
}
self::takeCaseSensitive($cfg, $out);
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
/**
* Parse one @UVEXISTS value into an exists fragment. The value must already
* be saved somewhere in the project:
* @UVEXISTS=record a record ID of this project
* @UVEXISTS=[specimen_id] a saved value of field specimen_id
* @UVEXISTS={"in":"[specimen_id]","event":"enrol_arm_1","scope":"dag",
* "match":{"site_code":"[site]"},"when":"...","message":"...",
* "blockSave":"hard","surveys":true}
* "match" narrows the lookup to saved entries whose target field holds the
* same value as a field of this record (target field => [local field]).
* "surveys" is an opt-in, as for @UVUNIQUE: a found / not found answer is
* record-derived information.
* "project" (a project id or alias) looks in another project instead. The
* searched fields are then that project's ("existsRemoteTargets"), so they
* never enter this project's field checks, read set or reverse dependencies.
* "return" writes fields of the entry found into fields of this form
* (field there => [field here], "record" for the record ID found):
* "return":{"lab_site":"[result_site]","record":"[lab_record]"}
* It becomes existsReturn (the map, kept on the server: the page never
* learns where the values come from) and existsReturnFields (the fields
* here, which the page fills).
* "where" is a condition on fields of the entry found (of the other
* project with "project"): only an entry where it holds counts as found.
* "where":"[consent]='1' and ([status]<>'3' or [status]='')"
* It becomes existsWhere (the text) and existsWhereFields (the fields it
* tests), both kept on the server; the fields join the searched fields
* (existsTargets, or existsRemoteTargets with "project"), so rights,
* Identifier checks, another project's agreement and the scan's read set
* cover them as they cover "in". "whereMessage" is what staff see when
* the value is saved but no entry holding it meets "where".
*/
private static function parseExistsValue($val, array $opts = [])
{
$val = trim($val);
if ($val === '') {
return ['error' => self::TAG_EXISTS . ' needs to know where to look: ' . self::TAG_EXISTS . '=record, '
. self::TAG_EXISTS . '=[field], or the JSON form with "in".'];
}
if ($val[0] !== '{') {
$in = self::existsSource($val);
if ($in === false) return ['error' => self::EXISTS_RECORD_FIELD];
if ($in === null) {
return ['error' => self::TAG_EXISTS . '=' . $val . ' is not a place to look — use record, one field '
. 'reference such as [specimen_id], or the JSON form for other options.'];
}
$out = ['type' => 'exists', 'existsIn' => $in];
if ($in !== 'record') $out['existsTargets'] = [$in];
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
$cfg = json_decode($val, true);
if (!is_array($cfg)) {
return ['error' => self::TAG_EXISTS . ' JSON does not parse ('
. json_last_error_msg() . ') — use double quotes around keys and string values.'];
}
$allowed = ['in', 'project', 'event', 'scope', 'match', 'when', 'message', 'blockSave', 'surveys', 'caseSensitive', 'return',
'where', 'whereMessage'];
$unknown = array_diff(array_keys($cfg), $allowed);
if ($unknown) {
return ['error' => 'unknown ' . self::TAG_EXISTS . ' option(s): ' . implode(', ', $unknown)
. ' — valid: ' . implode(', ', $allowed) . '.'];
}
if (!isset($cfg['in'])) {
return ['error' => self::TAG_EXISTS . ' needs "in": "record" or one field reference such as "[specimen_id]".'];
}
if (!is_string($cfg['in'])) return ['error' => '"in" must be a string.'];
$in = self::existsSource($cfg['in']);
if ($in === false) return ['error' => self::EXISTS_RECORD_FIELD];
if ($in === null) {
return ['error' => '"in" must be "record" or one field reference such as "[specimen_id]" — got '
. json_encode($cfg['in']) . '. To look in one event, add "event".'];
}
$out = ['type' => 'exists', 'existsIn' => $in];
if (isset($cfg['project'])) {
$p = $cfg['project'];
if (is_int($p) || (is_string($p) && trim($p) !== '')) {
$out['existsProject'] = strtolower(trim((string) $p));
} else {
return ['error' => '"project" must be a project id such as 123, or a project alias such as "lab".'];
}
}
if (isset($cfg['event'])) {
if (!is_string($cfg['event'])) return ['error' => '"event" must be a unique event name such as "enrolment_arm_1".'];
$out['existsEvent'] = strtolower(trim($cfg['event']));
}
if (isset($cfg['scope'])) {
if (!is_string($cfg['scope'])) return ['error' => '"scope" must be a string.'];
$out['existsScope'] = strtolower(trim($cfg['scope']));
}
if (isset($cfg['match'])) {
if (!is_array($cfg['match']) || !$cfg['match'] || array_keys($cfg['match']) === range(0, count($cfg['match']) - 1)) {
return ['error' => '"match" must be an object of target field to field of this record, e.g. '
. '{"site_code":"[site]"}.'];
}
$match = [];
foreach ($cfg['match'] as $target => $local) {
$t = strtolower(trim((string) $target)); // a target named "record": refused by checkExists
$l = is_string($local) ? self::existsSource($local) : null;
if ($l === false) return ['error' => self::EXISTS_RECORD_FIELD];
if ($l === null || $l === 'record') {
return ['error' => '"match" value for "' . $t . '" must be one field reference of this record, such as "[site]".'];
}
if (isset($match[$t])) return ['error' => '"match" names the target "' . $t . '" twice.'];
$match[$t] = $l;
}
$out['existsMatch'] = $match;
}
if (array_key_exists('return', $cfg)) {
$r = $cfg['return'];
if (!is_array($r) || !$r || array_keys($r) === range(0, count($r) - 1)) {
return ['error' => '"return" must be an object of field there to field of this form, e.g. '
. '{"lab_site":"[result_site]"} ("record" there for the record ID found).'];
}
$ret = [];
$seen = []; // field here => the field there written to it
foreach ($r as $source => $target) {
$s = strtolower(trim((string) $source));
$t = is_string($target) ? self::existsSource($target) : null;
if ($t === false) return ['error' => self::EXISTS_RECORD_FIELD];
if ($t === null || $t === 'record') {
return ['error' => '"return" value for "' . $s . '" must be one field reference of this form, such as "[result_site]".'];
}
if (isset($ret[$s])) return ['error' => '"return" names "' . $s . '" twice.'];
if (isset($seen[$t])) {
return ['error' => '"return" writes "' . $seen[$t] . '" and "' . $s . '" to the same field "[' . $t . ']" — give each its own.'];
}
$ret[$s] = $t;
$seen[$t] = $s;
}
$out['existsReturn'] = $ret;
$out['existsReturnFields'] = array_values($ret);
}
if (isset($cfg['surveys'])) {
if (!is_bool($cfg['surveys'])) return ['error' => '"surveys" must be true or false (unquoted).'];
if ($cfg['surveys']) $out['existsSurveys'] = true;
}
if (array_key_exists('where', $cfg)) {
if (!is_string($cfg['where'])) {
return ['error' => '"where" must be a condition on fields of the entry found, such as "[consent]=\'1\'".'];
}
$out['existsWhere'] = trim($cfg['where']);
$out['existsWhereFields'] = self::existsWhereFieldsOf($out['existsWhere']);
}
if (($e = self::takeTexts($cfg, $out)) !== null) return ['error' => $e];
foreach (['when', 'message', 'blockSave', 'whereMessage'] as $k) {
if (isset($cfg[$k])) {
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be a string.'];
$out[$k] = $cfg[$k];
}
}
self::takeCaseSensitive($cfg, $out);
// What the rule reads, as field lists: the fields of THIS record the
// lookup is narrowed by, and the fields it searches in other entries
// (the searched field, the "match" targets and the "where" fields).
if (isset($out['existsMatch'])) $out['existsLocal'] = array_values(array_unique(array_values($out['existsMatch'])));
$targets = $in === 'record' ? [] : [$in];
foreach (array_keys(isset($out['existsMatch']) ? $out['existsMatch'] : []) as $t) $targets[] = (string) $t;
foreach (isset($out['existsWhereFields']) ? $out['existsWhereFields'] : [] as $t) $targets[] = (string) $t;
if ($targets) $out[isset($out['existsProject']) ? 'existsRemoteTargets' : 'existsTargets'] = array_values(array_unique($targets));
$errs = self::checkFragment($out, $opts);
return $errs ? ['error' => implode(' ', $errs)] : $out;
}
/**
* Parse one @UVRANGE value into a range fragment: two tiers of plausibility
* limits for a number. JSON form only:
* @UVRANGE={"soft":[12,17.5],"hard":[3,25],"unit":"g/dL"}
* @UVRANGE={"soft":[null,140],"softBlock":"off","hard":[40,250],"hardBlock":"hard"}
* Outside "soft" is unusual (softBlock: off or confirm, default confirm);
* outside "hard", or not a number at all, is implausible (hardBlock:
* confirm or hard, default hard). Bounds are inclusive; null leaves a side
* open. Each bound is kept as an exact decimal string (rangeBound), so the
* two runtimes compare the same digits. Whether the field holds numbers is
* checked with the data dictionary in hand
* (UniversalValidator::annotateRangeField).
*
* With "reference" the limits are z-scores against a growth reference
* (php/GrowthReference.php), and the rule names its inputs:
* @UVRANGE={"reference":"who-wfa","sex":"[sex]","male":"1","female":"2",
* "age":{"dob":"[dob]","at":"[visit_date]"},"soft":[-2,2],"hard":[-6,5]}
* "sex", "age" (one of {"dob","at"}, {"days"} or {"months"}) and "by" become
* the operand keys rangeSex, rangeAgeDob/rangeAgeAt, rangeAgeDays,
* rangeAgeMonths and rangeBy; checkGrowth refuses a wrong combination.
*
* "return" writes values worked out from the reference to Text fields of
* the same form, and the rule then needs no limits when none of the values
* is made from one (GrowthOutputs::limitFree: "z", "percentile",
* "valueAtZ:<z>", "valueAtPercentile:<p>"):
* "return":{"z":"[wfa_z]","lower":"[wfa_low]","upper":"[wfa_high]","range":"[wfa_range]"}
* z is the z-score of the measurement, lower and upper the smallest and
* largest measurements, written with "decimals", that pass the low and high
* z limit of the "soft" limits (or "hard", "returnLimits"), and range the
* two as "7.7 to 12.0 kg" (GrowthReference::bound). percentile is written
* with "percentileDecimals", valueAtZ and valueAtPercentile with
* "decimals" (GrowthReference::output). The keys php/growth_outputs.json
* allows are read by GrowthOutputs::parse. They become rangeReturn (key =>
* field name), rangeReturnLimits, rangeDecimals and rangePercentileDecimals.
*/
private static function parseRangeValue($val, array $opts = [])
{
$val = trim($val);
if ($val === '' || $val[0] !== '{') {
return ['error' => self::TAG_RANGE . ' needs its settings as JSON, e.g. '
. self::TAG_RANGE . '={"soft":[12,17.5],"hard":[3,25]}.'];
}
$cfg = json_decode($val, true, 512, JSON_BIGINT_AS_STRING);
if (!is_array($cfg)) {
return ['error' => self::TAG_RANGE . ' JSON does not parse ('
. json_last_error_msg() . ') — use double quotes around keys and string values.'];
}
// The same JSON with every number as the text it was typed as. A limit
// is read from here, so 0.12345678901234567890 keeps all its digits
// instead of becoming the nearest double. Types are still judged on
// $cfg: a "unit" typed as 5 is a number, not the string "5".
$exact = json_decode(self::quoteJsonNumbers($val), true);
if (array_key_exists('blockSave', $cfg)) {
return ['error' => '"blockSave" does not apply to ' . self::TAG_RANGE . ' — use "softBlock" (off or confirm) '
. 'for values outside "soft", and "hardBlock" (confirm or hard) for values outside "hard".'];
}
$allowed = ['soft', 'hard', 'softBlock', 'hardBlock', 'unit', 'when', 'message', 'caseSensitive',
'reference', 'sex', 'male', 'female', 'age', 'by', 'plausible', 'measureScale',
'return', 'returnLimits', 'decimals', 'percentileDecimals', 'show'];
$unknown = array_diff(array_keys($cfg), $allowed);
if ($unknown) {
return ['error' => 'unknown ' . self::TAG_RANGE . ' option(s): ' . implode(', ', $unknown)
. ' — valid: ' . implode(', ', $allowed) . '.'];
}
$out = ['type' => 'range'];
// "plausible" (growth references only) is a pair like "soft" and "hard",
// in the reference's unit rather than in z-scores.
foreach (['soft' => 'rangeSoft', 'hard' => 'rangeHard', 'plausible' => 'rangePlausible'] as $k => $prefix) {
if (!array_key_exists($k, $cfg)) continue;
$pair = $cfg[$k];
if (!is_array($pair) || array_keys($pair) !== [0, 1]) {
return ['error' => '"' . $k . '" must be a list of two limits, [low, high] — e.g. [12,17.5], or [null,140] for no low limit.'];
}
if ($pair[0] === null && $pair[1] === null) {
return ['error' => '"' . $k . '" needs at least one limit — [null,null] would check nothing.'];
}
foreach ([0 => 'Lo', 1 => 'Hi'] as $i => $side) {
if ($pair[$i] === null) continue;
$typed = isset($exact[$k][$i]) && is_string($exact[$k][$i]) ? $exact[$k][$i] : null;
$b = self::rangeBound($pair[$i], $typed);
$what = 'the "' . $k . '" ' . ($i === 0 ? 'low' : 'high') . ' limit';
if ($b === null) {
return ['error' => $what . ' must be a number such as 12 or 17.5 — got '
. ((is_int($pair[$i]) || is_float($pair[$i])) && $typed !== null ? $typed : json_encode($pair[$i])) . '.'];
}
if ($b === false || strlen($b) > self::MAX_RANGE_BOUND) {
return ['error' => $what . ' is longer than ' . self::MAX_RANGE_BOUND . ' characters written out.'];
}
$out[$prefix . $side] = $b;
}
}
if (array_key_exists('measureScale', $cfg)) {
$typed = isset($exact['measureScale']) && is_string($exact['measureScale']) ? $exact['measureScale'] : null;
$b = self::rangeBound($cfg['measureScale'], $typed);
if ($b === null || $b === false) {
return ['error' => '"measureScale" must be a number such as 0.001 (grams typed into a reference in kg) — got '
. ((is_int($cfg['measureScale']) || is_float($cfg['measureScale'])) && $typed !== null ? $typed : json_encode($cfg['measureScale'])) . '.'];
}
$out['rangeMeasureScale'] = $b;
}
if (($e = self::takeTexts($cfg, $out)) !== null) return ['error' => $e];
foreach (['softBlock' => 'rangeSoftBlock', 'hardBlock' => 'rangeHardBlock', 'unit' => 'rangeUnit',
'when' => 'when', 'message' => 'message'] as $k => $key) {
if (!isset($cfg[$k])) continue;
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be a string.'];
$out[$key] = $k === 'unit' ? trim($cfg[$k]) : $cfg[$k];
}
// A growth reference: the limits are z-scores, and the reference reads
// the sex and the age (or the length or height) from other fields.
if (array_key_exists('reference', $cfg)) {
if (!is_string($cfg['reference']) || trim($cfg['reference']) === '') {
return ['error' => '"reference" must be the id of a growth reference, such as "who-wfa".'];
}
$out['rangeReference'] = trim($cfg['reference']);
}
foreach (['sex' => 'rangeSex', 'by' => 'rangeBy'] as $k => $key) {
if (!array_key_exists($k, $cfg)) continue;
if (!is_string($cfg[$k])) return ['error' => '"' . $k . '" must be one field reference, such as "[' . ($k === 'sex' ? 'sex' : 'height_cm') . ']".'];
$out[$key] = $cfg[$k];
}
foreach (['male' => 'rangeMale', 'female' => 'rangeFemale'] as $k => $key) {