-
Notifications
You must be signed in to change notification settings - Fork 88
/
Interpreter.php
913 lines (788 loc) · 29.1 KB
/
Interpreter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
<?php
declare(strict_types=1);
namespace EDI;
/**
* EDIFACT Messages Interpreter
* (c) 2018 Stefano Sabatini
*/
class Interpreter
{
/**
* @var array
*/
public $messageTextConf = [
'MISSINGREQUIREDSEGMENT' => 'Missing required segment',
'MISSINGREQUIREDGROUP' => 'Missing required group',
'NOTCONFORMANT' => "It looks like that this message isn't conformant to the mapping provided. (Not all segments were added)",
'TOOMANYELEMENTS_COMPOSITE' => 'This composite data element has more elements than expected',
'TOOMANYELEMENTS' => 'This segment has more data elements than expected',
'MISSINGINTERCHANGEDELIMITER' => 'The file has at least one UNB or UNZ missing',
'MISSINGMESSAGEDELIMITER' => 'The message has at least one UNH or UNT missing',
'TOOMANYSEGMENTS' => 'The message has some additional segments beyond the maximum repetition allowed',
'TOOMANYGROUPS' => 'The message has some additional groups beyond the maximum repetition allowed',
'SPURIOUSSEGMENT' => 'This segment is spurious',
];
/**
* @var array
*/
public $segmentTemplates = [
'DTM' => ['DTM', '999', 'XXX'],
];
/**
* @var array
*/
public $groupTemplates = [
'SG1' => [['TDT', '20', 'XXX']],
];
/**
* @var bool
*/
private $patchFiles = true;
/**
* @var bool
*/
private $segmentGroup = true;
/**
* @var bool
*/
private $forceArrayWhenRepeatable = false;
/**
* @var \SimpleXMLElement
*/
private $xmlMsg;
/**
* @var array
*/
private $xmlSeg;
/**
* @var array
*/
private $xmlSvc;
/**
* @var array
*/
private $ediGroups;
/**
* @var array
*/
private $errors;
/**
* @var array
*/
private $msgs;
/**
* @var array
*/
private $serviceSeg;
/**
* @var array
*/
private $codes;
/**
* @var callable
*/
private $comparisonFunction;
/**
* @var callable
*/
private $replacementFunction;
/**
* @var string
*/
private $outputKey = 'name';
/**
* @var string
*/
private $currentGroup = '';
/**
* @var string
*/
private $currentGroupHeader = '';
/**
* Split multiple messages and process
*
* @param string $xmlMsg Path to XML Message representation
* @param array $xmlSeg Segments processed by EDI\Analyser::loadSegmentsXml or EDI\Mapping\MappingProvider
* @param array $xmlSvc Service segments processed by EDI\Analyser::loadSegmentsXml or EDI\Mapping\MappingProvider
* @param array|null $messageTextConf Personalization of error messages
*/
public function __construct(string $xmlMsg, array $xmlSeg, array $xmlSvc, ?array $messageTextConf = null)
{
// simplexml_load_file: This can be affected by a PHP bug #62577 (https://bugs.php.net/bug.php?id=62577)
$xmlData = \file_get_contents($xmlMsg);
if ($xmlData === false) {
throw new \InvalidArgumentException('file_get_contents for "'.$xmlMsg.'" failed');
}
$xmlMsgTmp = \simplexml_load_string($xmlData);
if ($xmlMsgTmp === false) {
throw new \InvalidArgumentException('simplexml_load_string for "'.$xmlMsg.'" failed');
}
$this->xmlMsg = $xmlMsgTmp;
$this->xmlSeg = $xmlSeg;
$this->xmlSvc = $xmlSvc;
if ($messageTextConf !== null) {
$this->messageTextConf = \array_replace($this->messageTextConf, $messageTextConf);
}
$this->errors = [];
$this->comparisonFunction = static function ($segment, $elm) {
return $segment[0] == $elm['id'];
};
}
/**
* @return void
*/
public function togglePatching(bool $flag)
{
$this->patchFiles = $flag;
return $this;
}
/**
* @return void
*/
public function toggleSegmentGroup(bool $flag)
{
$this->segmentGroup = $flag;
return $this;
}
/**
* @return void
*/
public function forceArrayWhenRepeatable(bool $flag)
{
$this->forceArrayWhenRepeatable = $flag;
return $this;
}
/**
* Patch the error messages array
*
* @param array $messageTextConf An array with same keys as the internal $messageTextConf
* @return void
*/
public function setMessageTextConf(array $messageTextConf)
{
$this->messageTextConf = \array_replace($this->messageTextConf, $messageTextConf);
return $this;
}
/**
* Add fake segments used to patch the message if a required segment is missing
*
* @param array $segmentTemplates An array with segments (having the segment name as key)
* @return void
*/
public function setSegmentTemplates(array $segmentTemplates)
{
$this->segmentTemplates = $segmentTemplates;
return $this;
}
/**
* Add fake groups used to patch the message if a required group is missing
*
* @param array $groupTemplates An array with segments (having the group name as key)
* @return void
*/
public function setGroupTemplates(array $groupTemplates)
{
$this->groupTemplates = $groupTemplates;
return $this;
}
/**
* Set the data parsed from the xml list of codes
*
* @param array $codes An array with codes from the chosen directory
* @return void
*/
public function setCodes(array $codes)
{
$this->codes = $codes;
return $this;
}
/**
* Function that implements how to compare a message segment and its definition
*
* @param callable $func A function accepting two arguments, first is the segment array, then the element definition
* @return void
*/
public function setComparisonFunction(callable $func)
{
$this->comparisonFunction = $func;
return $this;
}
/**
* Function that replaces a segment
*
* @param callable $func A function accepting two arguments, first is the segment array, then the element definition
* @return void
*/
public function setReplacementFunction(callable $func)
{
$this->replacementFunction = $func;
return $this;
}
/**
* Set to true if UNCEFACT XML ID should be used instead of names
*
*
* @return void
*/
public function toggleUseIdInsteadOfNameForOutput(bool $toggle)
{
if ($toggle) {
$this->outputKey = 'id';
} else {
$this->outputKey = 'name';
}
return $this;
}
/**
* Split multiple messages and process
*
* @param array $parsed An array coming from EDI\Parser
*/
public function prepare(array $parsed): array
{
$this->msgs = $this->splitMessages($parsed, $this->errors);
$groups = [];
$service = $this->msgs['service'];
$this->serviceSeg = $this->processService($service);
foreach ($this->msgs as $k => $msg) {
if ($k === 'service') {
continue;
}
$grouped = $this->loopMessage($msg, $this->xmlMsg, $this->errors);
$groups[] = $grouped['message'];
}
$this->ediGroups = $groups;
return $groups;
}
/**
* Get result as json.
*
*
* @return false|string
*/
public function getJson(bool $pretty = false)
{
if ($pretty) {
return \json_encode($this->ediGroups, \JSON_PRETTY_PRINT);
}
return \json_encode($this->ediGroups);
}
/**
* Get EDI groups.
*
* @return array
*/
public function getEdiGroups()
{
return $this->ediGroups;
}
/**
* Set EDI groups.
*
* @return array
*/
public function setEdiGroups($groups)
{
$this->ediGroups = $groups;
}
/**
* Get errors
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* Get splitted messages.
*/
public function getMessages(): array
{
return $this->msgs;
}
/**
* Get service segments.
*
* @return array
*/
public function getServiceSegments()
{
return $this->serviceSeg;
}
/**
* Get json service segments.
*
*
* @return false|string
*/
public function getJsonServiceSegments(bool $pretty = false)
{
if ($pretty) {
return \json_encode($this->serviceSeg, \JSON_PRETTY_PRINT);
}
return \json_encode($this->serviceSeg);
}
/**
* Split multiple messages
*
* @param array $parsed An array coming from EDI\Parser
* @param array $errors
*/
private function splitMessages(&$parsed, &$errors): array
{
// init
$messages = [];
$tmpmsg = [];
$service = [];
$hasInterchangeDelimiters = 0;
$hasMessageDelimiters = 0;
foreach ($parsed as $c => $segment) {
switch ($segment[0]) {
case 'UNB':
$hasInterchangeDelimiters = 0;
$hasInterchangeDelimiters++;
$service['UNB'] = $segment;
break;
case 'UNZ':
$hasInterchangeDelimiters--;
if ($hasInterchangeDelimiters != 0) {
$sid = ($hasInterchangeDelimiters < 0) ? 'UNB' : 'UNZ';
$errors[] = [
'text' => $this->messageTextConf['MISSINGINTERCHANGEDELIMITER'],
'position' => $c,
'segmentId' => $sid,
];
}
$service['UNZ'] = $segment;
if ($this->patchFiles && $hasMessageDelimiters > 0) {
$segment = ['UNT', '0', '1'];
$hasMessageDelimiters--;
$tmpmsg[] = $segment;
$messages[] = $tmpmsg;
}
break;
case 'UNH':
$hasMessageDelimiters = 0;
$hasMessageDelimiters++;
$tmpmsg = [$segment];
break;
case 'UNT':
$hasMessageDelimiters--;
$tmpmsg[] = $segment;
$messages[] = $tmpmsg;
if ($hasMessageDelimiters != 0) {
$sid = ($hasMessageDelimiters < 0) ? 'UNH' : 'UNT';
$errors[] = [
'text' => $this->messageTextConf['MISSINGMESSAGEDELIMITER'],
'position' => $c,
'segmentId' => $sid,
];
}
break;
default:
$tmpmsg[] = $segment;
break;
}
}
if ($hasInterchangeDelimiters != 0) {
$sid = ($hasInterchangeDelimiters < 0) ? 'UNB' : 'UNZ';
$errors[] = [
'text' => $this->messageTextConf['MISSINGINTERCHANGEDELIMITER'],
'position' => $c ?? '',
'segmentId' => $sid,
];
}
if ($hasMessageDelimiters != 0) {
$sid = ($hasMessageDelimiters < 0) ? 'UNH' : 'UNT';
$errors[] = [
'text' => $this->messageTextConf['MISSINGMESSAGEDELIMITER'],
'position' => $c ?? '',
'segmentId' => $sid,
];
}
$messages['service'] = $service;
return $messages;
}
/**
* Transform a parsed edi in its groupings
*
* @param array $message Single message (Without UNB and UNZ)
* @param \SimpleXMLElement $xml The xml representation of the message
*/
private function loopMessage(array &$message, \SimpleXMLElement $xml, array &$errors): array
{
// init
$groupedEdi = [];
$segmentIdx = 0;
foreach ($xml->children() as $elm) {
if ($elm->getName() == 'group') {
$this->processXmlGroup($elm, $message, $segmentIdx, $groupedEdi, $errors);
} elseif ($elm->getName() == 'segment') {
$this->processXmlSegment($elm, $message, $segmentIdx, $groupedEdi, $errors);
}
}
if ($segmentIdx != \count($message)) {
$errors[] = [
'text' => $this->messageTextConf['NOTCONFORMANT'],
'position' => $segmentIdx,
'segmentId' => $message[$segmentIdx][0],
];
}
return [
'message' => $groupedEdi,
'errors' => $errors,
];
}
/**
* Process an XML Group
*
*
* @return void
*/
private function processXmlGroup(\SimpleXMLElement $elm, array &$message, int &$segmentIdx, array &$array, array &$errors)
{
// init
$groupVisited = false;
$newGroup = [];
$this->currentGroupHeader = $elm->children()[0]['id']->__toString();
$this->currentGroup = $elm['id']->__toString();
for ($g = 0; $g < $elm['maxrepeat']; $g++) {
$grouptemp = [];
if ($message[$segmentIdx][0] != $elm->children()[0]['id']) {
if (
! $groupVisited
&&
isset($elm['required'])
) {
$elmType = $elm['id']->__toString();
$fixed = false;
if ($this->patchFiles && isset($this->groupTemplates[$elmType])) {
\array_splice($message, $segmentIdx, 0, $this->groupTemplates[$elmType]);
$fixed = true;
}
$errors[] = [
'text' => $this->messageTextConf['MISSINGREQUIREDGROUP'].' '.($fixed ? ' (patched)' : ''),
'position' => $segmentIdx,
'segmentId' => $elmType,
];
} else {
break;
}
}
foreach ($elm->children() as $elm2) {
if ($elm2->getName() == 'group') {
$this->processXmlGroup($elm2, $message, $segmentIdx, $grouptemp, $errors);
$this->currentGroupHeader = $elm->children()[0]['id']->__toString();
$this->currentGroup = $elm['id']->__toString();
} else {
$this->processXmlSegment($elm2, $message, $segmentIdx, $grouptemp, $errors);
}
$groupVisited = true;
}
$newGroup[] = $grouptemp;
}
// if additional groups are detected we are violating the maxrepeat attribute
while (isset($message[$segmentIdx]) && \call_user_func($this->comparisonFunction, $message[$segmentIdx], $elm->children()[0])) {
$errors[] = [
'text' => $this->messageTextConf['TOOMANYGROUPS'],
'position' => $segmentIdx,
'segmentId' => (string) $elm['id'],
];
$this->currentGroup = $elm['id']->__toString();
foreach ($elm->children() as $elm2) {
if ($elm2->getName() == 'group') {
$this->processXmlGroup($elm2, $message, $segmentIdx, $grouptemp, $errors);
$this->currentGroupHeader = $elm->children()[0]['id']->__toString();
$this->currentGroup = $elm['id']->__toString();
} else {
$this->processXmlSegment($elm2, $message, $segmentIdx, $grouptemp, $errors);
}
$groupVisited = true;
}
$newGroup[] = $grouptemp;
}
$this->currentGroupHeader = '';
$this->currentGroup = '';
if (\count($newGroup) === 0) {
return;
}
$array[$elm['id']->__toString()] = $newGroup;
}
/**
* Process an XML Segment.
*
*
* @return void
*/
private function processXmlSegment(\SimpleXMLElement $elm, array &$message, int &$segmentIdx, array &$array, array &$errors)
{
// init
$segmentVisited = false;
for ($i = 0; $i < $elm['maxrepeat']; $i++) {
if (\call_user_func($this->comparisonFunction, $message[$segmentIdx], $elm)) {
$jsonMessage = $this->processSegment($message[$segmentIdx], $this->xmlSeg, $segmentIdx, $errors);
$segmentVisited = true;
$this->doAddArray($array, $jsonMessage, (int) $elm['maxrepeat']);
$segmentIdx++;
} elseif ($this->replacementFunction !== null && $replacementSegment = \call_user_func($this->replacementFunction, $message[$segmentIdx], $elm)) {
//the function shall return false, true or a new segment
$fixed = false;
if ($elm['replacewith'] !== null) {
$elmType = (string) $elm['replacewith'];
} else {
$elmType = (string) $elm['id'];
}
if ($this->patchFiles && $replacementSegment === true && isset($this->segmentTemplates[$elmType])) {
$jsonMessage = $this->processSegment($this->segmentTemplates[$elmType], $this->xmlSeg, $segmentIdx, $errors);
$fixed = true;
$this->doAddArray($array, $jsonMessage, (int) $elm['maxrepeat']);
}
if ($this->patchFiles && $replacementSegment !== true) {
$jsonMessage = $this->processSegment($replacementSegment, $this->xmlSeg, $segmentIdx, $errors);
$fixed = true;
$this->doAddArray($array, $jsonMessage, (int) $elm['maxrepeat']);
}
$errors[] = [
'text' => $this->messageTextConf['MISSINGREQUIREDSEGMENT'].' '.($fixed ? ' (replaced)' : ''),
'position' => $segmentIdx,
'segmentId' => (string) $elm['id'],
];
$segmentIdx++;
continue;
} else {
if (! $segmentVisited && isset($elm['required'])) {
$segmentVisited = true;
if (isset($message[$segmentIdx + 1]) && \call_user_func($this->comparisonFunction, $message[$segmentIdx + 1], $elm)) {
$errors[] = [
'text' => $this->messageTextConf['SPURIOUSSEGMENT'].($this->patchFiles ? ' (skipped)' : ''),
'position' => $segmentIdx,
'segmentId' => (string) $message[$segmentIdx][0],
];
$segmentIdx++; //just move the index
$i--; //but don't count as repetition
continue;
}
if ($elm['replacewith'] !== null) {
$elmType = (string) $elm['replacewith'];
} else {
$elmType = (string) $elm['id'];
}
$fixed = false;
if ($this->patchFiles && isset($this->segmentTemplates[$elmType])) {
$jsonMessage = $this->processSegment($this->segmentTemplates[$elmType], $this->xmlSeg, $segmentIdx, $errors);
$fixed = true;
$this->doAddArray($array, $jsonMessage, (int) $elm['maxrepeat']);
}
$errors[] = [
'text' => $this->messageTextConf['MISSINGREQUIREDSEGMENT'].' '.($fixed ? ' (patched)' : ''),
'position' => $segmentIdx,
'segmentId' => (string) $elm['id'],
];
}
return;
}
}
// if additional segments are detected we are violating the maxrepeat attribute
$loopMove = 0;
while (
isset($message[$segmentIdx]) &&
\call_user_func($this->comparisonFunction, $message[$segmentIdx + $loopMove], $elm) &&
(string) $elm['id'] !== $this->currentGroupHeader
) {
$errors[] = [
'text' => $this->messageTextConf['TOOMANYSEGMENTS'].($this->patchFiles ? ' (skipped)' : ''),
'position' => $segmentIdx,
'segmentId' => (string) $elm['id'],
];
if ($this->patchFiles) {
$segmentIdx++;
} else {
$loopMove++; //we move to the next segment only for this loop if the patching isn't active
}
}
}
/**
* Adds a processed segment to the current group.
*
* @param array $array a reference to the group
* @param array $jsonMessage a segment processed by processSegment()
* @return void
*/
private function doAddArray(array &$array, array &$jsonMessage, $maxRepeat = 1)
{
if (isset($array[$jsonMessage['key']])) {
if (
isset($array[$jsonMessage['key']]['segmentCode'])
||
$jsonMessage['key'] === 'UnrecognisedType'
) {
$temp = $array[$jsonMessage['key']];
$array[$jsonMessage['key']] = [];
$array[$jsonMessage['key']][] = $temp;
}
$array[$jsonMessage['key']][] = $jsonMessage['value'];
} else {
$array[$jsonMessage['key']] = $jsonMessage['value'];
// if segment can be repeated then the flag forces to be an array also
// if there's only one segment
if ($maxRepeat > 1 && $this->forceArrayWhenRepeatable) {
$array[$jsonMessage['key']] = [$jsonMessage['value']];
}
}
}
/**
* Add human readable keys as in Analyser.
*
* @param int|null $segmentIdx
*/
private function processSegment(array &$segment, array &$xmlMap, $segmentIdx, ?array &$errors = null): array
{
$id = $segment[0];
$jsonsegment = [];
if (isset($xmlMap[$id])) {
$attributes = $xmlMap[$id]['attributes'];
$details_desc = $xmlMap[$id]['details'];
$jsonelements = [
'segmentIdx' => $segmentIdx,
'segmentCode' => $id,
];
if ($this->segmentGroup) {
$jsonelements['segmentGroup'] = $this->currentGroup;
}
foreach ($segment as $idx => $detail) {
$n = $idx - 1;
if ($idx == 0) {
continue;
}
if (! isset($details_desc[$n])) {
$errors[] = [
'text' => $this->messageTextConf['TOOMANYELEMENTS'],
'position' => $segmentIdx,
'segmentId' => $id,
];
$jsonelements['Extension'.$n] = $detail;
continue;
}
$d_desc_attr = $details_desc[$n]['attributes'];
$jsoncomposite = [];
if (
$detail !== ''
&&
isset($details_desc[$n]['details'])
) {
$sub_details_desc = $details_desc[$n]['details'];
if (\is_array($detail)) {
foreach ($detail as $d_n => $d_detail) {
if (! isset($sub_details_desc[$d_n])) {
$errors[] = [
'text' => $this->messageTextConf['TOOMANYELEMENTS_COMPOSITE'],
'position' => $segmentIdx.'/'.$idx,
'segmentId' => $id,
];
$jsoncomposite['CompositeExtension'.$d_n] = $d_detail;
continue;
}
$d_sub_desc_attr = $sub_details_desc[$d_n]['attributes'];
//print_r($d_sub_desc_attr);
//print_r($d_detail);
//die();
if (isset($this->codes) && isset($this->codes[$d_sub_desc_attr['id']]) && is_array($this->codes[$d_sub_desc_attr['id']])) { //if codes is set enable translation of the value
if (isset($this->codes[$d_sub_desc_attr['id']][$d_detail])) {
$d_detail = $this->codes[$d_sub_desc_attr['id']][$d_detail];
}
}
if (! isset($jsoncomposite[$d_sub_desc_attr[$this->outputKey]])) { //New
$jsoncomposite[$d_sub_desc_attr[$this->outputKey]] = $d_detail;
} elseif (\is_string($jsoncomposite[$d_sub_desc_attr[$this->outputKey]])) { // More data than one string
$jsoncomposite[$d_sub_desc_attr[$this->outputKey]] = [
$jsoncomposite[$d_sub_desc_attr[$this->outputKey]],
$d_detail,
];
} else { // More and more
$jsoncomposite[$d_sub_desc_attr[$this->outputKey]][] = $d_detail;
}
}
} else {
$d_sub_desc_attr = $sub_details_desc[0]['attributes'];
if (isset($this->codes) && isset($this->codes[$d_sub_desc_attr['id']]) && is_array($this->codes[$d_sub_desc_attr['id']])) { //if codes is set enable translation of the value
if (isset($this->codes[$d_sub_desc_attr['id']][$detail]) && $this->codes[$d_sub_desc_attr['id']][$detail]) {
$detail = $this->codes[$d_sub_desc_attr['id']][$detail];
}
}
$jsoncomposite[$d_sub_desc_attr[$this->outputKey]] = $detail;
}
} else {
if (isset($this->codes) && isset($this->codes[$d_desc_attr['id']]) && is_array($this->codes[$d_desc_attr['id']])) { //if codes is set enable translation of the value
if (isset($this->codes[$d_desc_attr['id']][$detail]) && $this->codes[$d_desc_attr['id']][$detail]) {
$detail = $this->codes[$d_desc_attr['id']][$detail];
}
}
$jsoncomposite = $detail;
}
if (\array_key_exists($d_desc_attr[$this->outputKey], $jsonelements)) {
$jsonelements[$d_desc_attr[$this->outputKey].$n] = $jsoncomposite;
} else {
$jsonelements[$d_desc_attr[$this->outputKey]] = $jsoncomposite;
}
}
$jsonsegment['key'] = $attributes[$this->outputKey];
$jsonsegment['value'] = $jsonelements;
} elseif ($xmlMap !== $this->xmlSvc) {
$jsonsegment = $this->processSegment($segment, $this->xmlSvc, $segmentIdx, $errors);
} else {
$jsonsegment['key'] = 'UnrecognisedType';
$jsonsegment['value'] = $segment;
}
return $jsonsegment;
}
/**
* Process UNB / UNZ segments
*/
private function processService(array &$segments): array
{
// init
$processed = [];
foreach ($segments as &$seg) {
$jsonsegment = $this->processSegment($seg, $this->xmlSvc, null);
$processed[$jsonsegment['key']] = $jsonsegment['value'];
}
return $processed;
}
public function rebuildArray()
{
if (isset($this->codes)) {
throw new \LogicException('Run the Interpreter without calling setCodes()');
}
$unh = $this->serviceSeg['interchangeHeader'];
unset($unh['segmentIdx']);
unset($unh['segmentGroup']);
$unz = $this->serviceSeg['interchangeTrailer'];
unset($unz['segmentIdx']);
unset($unz['segmentGroup']);
$rebuilt = $this->recursionReconstruct($this->ediGroups);
array_unshift($rebuilt, $unh);
$rebuilt[] = $unz;
return $rebuilt;
}
private function recursionReconstruct($tempArr)
{
$reconstructArr = [];
if (is_array($tempArr)) {
foreach ($tempArr as $idx => $arr) {
if (! isset($arr['segmentIdx'])) {
$recurseArr = $this->recursionReconstruct($arr);
foreach ($recurseArr as $k => $i) {
$reconstructArr[$k] = $i;
}
} else {
$idx = $arr['segmentIdx'];
unset($arr['segmentIdx']);
if ($this->segmentGroup) {
unset($arr['segmentGroup']);
}
$reconstructArr[$idx] = $arr;
}
}
}
return $reconstructArr;
}
}