Skip to content

Commit f380948

Browse files
committed
forceArrayWhenRepeatable in Interpreter, fixes #52
1 parent 7cea68c commit f380948

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

src/EDI/Interpreter.php

+25-3
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ class Interpreter
4242
*/
4343
private $patchFiles = true;
4444

45+
/**
46+
* @var bool
47+
*/
48+
private $forceArrayWhenRepeatable = false;
49+
50+
4551
/**
4652
* @var \SimpleXMLElement
4753
*/
@@ -141,6 +147,16 @@ public function togglePatching(bool $flag)
141147
$this->patchFiles = $flag;
142148
}
143149

150+
/**
151+
* @param bool $flag
152+
*
153+
* @return void
154+
*/
155+
public function forceArrayWhenRepeatable(bool $flag)
156+
{
157+
$this->forceArrayWhenRepeatable = $flag;
158+
}
159+
144160
/**
145161
* Patch the error messages array
146162
*
@@ -525,7 +541,7 @@ private function processXmlSegment(\SimpleXMLElement $elm, array &$message, int
525541
if (\call_user_func($this->comparisonFunction, $message[$segmentIdx], $elm)) {
526542
$jsonMessage = $this->processSegment($message[$segmentIdx], $this->xmlSeg, $segmentIdx, $errors);
527543
$segmentVisited = true;
528-
$this->doAddArray($array, $jsonMessage);
544+
$this->doAddArray($array, $jsonMessage, (int)$elm['maxrepeat']);
529545
++$segmentIdx;
530546
} else {
531547
if (!$segmentVisited && isset($elm['required'])) {
@@ -540,7 +556,7 @@ private function processXmlSegment(\SimpleXMLElement $elm, array &$message, int
540556
if ($this->patchFiles && isset($this->segmentTemplates[$elmType])) {
541557
$jsonMessage = $this->processSegment($this->segmentTemplates[$elmType], $this->xmlSeg, $segmentIdx, $errors);
542558
$fixed = true;
543-
$this->doAddArray($array, $jsonMessage);
559+
$this->doAddArray($array, $jsonMessage, (int)$elm['maxrepeat']);
544560
}
545561

546562
$errors[] = [
@@ -563,7 +579,7 @@ private function processXmlSegment(\SimpleXMLElement $elm, array &$message, int
563579
*
564580
* @return void
565581
*/
566-
private function doAddArray(array &$array, array &$jsonMessage)
582+
private function doAddArray(array &$array, array &$jsonMessage, $maxRepeat = 1)
567583
{
568584
if (isset($array[$jsonMessage['key']])) {
569585
if (
@@ -578,6 +594,12 @@ private function doAddArray(array &$array, array &$jsonMessage)
578594
$array[$jsonMessage['key']][] = $jsonMessage['value'];
579595
} else {
580596
$array[$jsonMessage['key']] = $jsonMessage['value'];
597+
// if segment can be repeated then the flag forces to be an array also
598+
// if there's only one segment
599+
if ($maxRepeat > 1 && $this->forceArrayWhenRepeatable) {
600+
d('lol', $jsonMessage, $maxRepeat);
601+
$array[$jsonMessage['key']] = [$jsonMessage['value']];
602+
}
581603
}
582604
}
583605

0 commit comments

Comments
 (0)