Skip to content

Commit

Permalink
ecs, improvements in rebuildArray
Browse files Browse the repository at this point in the history
  • Loading branch information
sabas committed Oct 22, 2024
1 parent cce1d49 commit ab27826
Show file tree
Hide file tree
Showing 13 changed files with 350 additions and 257 deletions.
6 changes: 1 addition & 5 deletions src/EDI/Encoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,8 @@ public function __construct($array = null, $compact = true)
/**
* @param array[] $array
* @param bool $compact All segments on a single line?
* @param bool $filterKeys
*/
public function encode(array $array, $compact = true, $filterKeys = false): string
public function encode(array $array, $compact = true): string
{
$this->originalArray = $array;
$this->compact = $compact;
Expand All @@ -92,9 +91,6 @@ public function encode(array $array, $compact = true, $filterKeys = false): stri
$k = 0;
foreach ($array as $row) {
$k++;
if ($filterKeys) {
unset($row['segmentIdx']);
}
$row = \array_values($row);
$edistring .= $this->encodeSegment($row);
if (! $compact && $k < $count) {
Expand Down
44 changes: 34 additions & 10 deletions src/EDI/Interpreter.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class Interpreter
'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'
'SPURIOUSSEGMENT' => 'This segment is spurious',
];

/**
Expand Down Expand Up @@ -160,16 +160,17 @@ public function __construct(string $xmlMsg, array $xmlSeg, array $xmlSvc, array
public function togglePatching(bool $flag)
{
$this->patchFiles = $flag;

return $this;
}


/**
* @return void
*/
public function toggleSegmentGroup(bool $flag)
{
$this->segmentGroup = $flag;

return $this;
}

Expand All @@ -179,6 +180,7 @@ public function toggleSegmentGroup(bool $flag)
public function forceArrayWhenRepeatable(bool $flag)
{
$this->forceArrayWhenRepeatable = $flag;

return $this;
}

Expand All @@ -191,6 +193,7 @@ public function forceArrayWhenRepeatable(bool $flag)
public function setMessageTextConf(array $messageTextConf)
{
$this->messageTextConf = \array_replace($this->messageTextConf, $messageTextConf);

return $this;
}

Expand All @@ -203,6 +206,7 @@ public function setMessageTextConf(array $messageTextConf)
public function setSegmentTemplates(array $segmentTemplates)
{
$this->segmentTemplates = $segmentTemplates;

return $this;
}

Expand All @@ -215,6 +219,7 @@ public function setSegmentTemplates(array $segmentTemplates)
public function setGroupTemplates(array $groupTemplates)
{
$this->groupTemplates = $groupTemplates;

return $this;
}

Expand All @@ -227,6 +232,7 @@ public function setGroupTemplates(array $groupTemplates)
public function setCodes(array $codes)
{
$this->codes = $codes;

return $this;
}

Expand All @@ -239,6 +245,7 @@ public function setCodes(array $codes)
public function setComparisonFunction(callable $func)
{
$this->comparisonFunction = $func;

return $this;
}

Expand All @@ -251,6 +258,7 @@ public function setComparisonFunction(callable $func)
public function setReplacementFunction(callable $func)
{
$this->replacementFunction = $func;

return $this;
}

Expand All @@ -267,6 +275,7 @@ public function toggleUseIdInsteadOfNameForOutput(bool $toggle)
} else {
$this->outputKey = 'name';
}

return $this;
}

Expand Down Expand Up @@ -599,7 +608,7 @@ private function processXmlSegment(\SimpleXMLElement $elm, array &$message, int
$segmentVisited = true;
$this->doAddArray($array, $jsonMessage, (int) $elm['maxrepeat']);
$segmentIdx++;
} else if ($this->replacementFunction !== null && $replacementSegment = \call_user_func($this->replacementFunction, $message[$segmentIdx], $elm)) {
} 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;

Expand Down Expand Up @@ -627,18 +636,20 @@ private function processXmlSegment(\SimpleXMLElement $elm, array &$message, int
'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)) {
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;
}

Expand Down Expand Up @@ -672,8 +683,8 @@ private function processXmlSegment(\SimpleXMLElement $elm, array &$message, int
$loopMove = 0;
while (
isset($message[$segmentIdx]) &&
\call_user_func($this->comparisonFunction, $message[$segmentIdx+$loopMove], $elm) &&
(string)$elm['id'] !== $this->currentGroupHeader
\call_user_func($this->comparisonFunction, $message[$segmentIdx + $loopMove], $elm) &&
(string) $elm['id'] !== $this->currentGroupHeader
) {
$errors[] = [
'text' => $this->messageTextConf['TOOMANYSEGMENTS'].($this->patchFiles ? ' (skipped)' : ''),
Expand Down Expand Up @@ -735,7 +746,7 @@ private function processSegment(array &$segment, array &$xmlMap, $segmentIdx, ar

$jsonelements = [
'segmentIdx' => $segmentIdx,
'segmentCode' => $id
'segmentCode' => $id,
];

if ($this->segmentGroup) {
Expand Down Expand Up @@ -783,7 +794,9 @@ private function processSegment(array &$segment, array &$xmlMap, $segmentIdx, ar
}

$d_sub_desc_attr = $sub_details_desc[$d_n]['attributes'];

//print_r($d_sub_desc_attr);
//print_r($d_detail);
//die();
if ($this->codes !== null && 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];
Expand Down Expand Up @@ -859,9 +872,19 @@ public function rebuildArray()
if ($this->codes !== null) {
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']);

return $this->recursionReconstruct($this->ediGroups);
$rebuilt = $this->recursionReconstruct($this->ediGroups);

array_unshift($rebuilt, $unh);
$rebuilt[] = $unz;

return $rebuilt;
}

private function recursionReconstruct($tempArr)
Expand All @@ -875,7 +898,7 @@ private function recursionReconstruct($tempArr)
$reconstructArr[$k] = $i;
}
} else {
$idx=$arr['segmentIdx'];
$idx = $arr['segmentIdx'];
unset($arr['segmentIdx']);
if ($this->segmentGroup) {
unset($arr['segmentGroup']);
Expand All @@ -884,6 +907,7 @@ private function recursionReconstruct($tempArr)
}
}
}

return $reconstructArr;
}
}
20 changes: 10 additions & 10 deletions src/EDI/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,12 +291,13 @@ public function checkEncoding(): bool
throw new \LogicException('No text has been parsed yet');
}
if (! isset(self::$charsets[$this->syntaxID])) {
throw new \RuntimeException('Unsupported syntax identifier: ' . $this->syntaxID);
throw new \RuntimeException('Unsupported syntax identifier: '.$this->syntaxID);
}

$check = mb_check_encoding($this->parsedfile, self::$charsets[$this->syntaxID]);
if(!$check)
if (! $check) {
$this->errors[] = 'Character encoding does not match declaration in UNB interchange header';
}

return $check;
}
Expand All @@ -312,7 +313,7 @@ public function errors(): array
/**
* (Un)Set strict parsing.
*/
public function setStrict(bool $strict):void
public function setStrict(bool $strict): void
{
$this->strict = $strict;
}
Expand All @@ -330,24 +331,24 @@ public function get(?string $encoding = null): array
if (empty($this->parsedfile)) {
$this->parse();
}

if (null === $encoding) {
return $this->parsedfile;
}

return $this->convertEncoding($this->parsedfile, self::$charsets[$this->syntaxID], $encoding);
}

private function convertEncoding($data, string $from, string $to)
{
if (is_array($data)) {
foreach ($data as $k => $v) {
$data[$k] = $this->convertEncoding($v, $from, $to);
}
} elseif (is_string($data)) {
$data = function_exists('iconv') ? iconv($from, $to . '//TRANSLIT', $data) : mb_convert_encoding($data, $to, $from);
$data = function_exists('iconv') ? iconv($from, $to.'//TRANSLIT', $data) : mb_convert_encoding($data, $to, $from);
}

return $data;
}

Expand All @@ -365,7 +366,6 @@ public function getRawSegments(): array
* Get syntax identifier from the UNB header.
* Does not necessarily mean that the text is actually encoded as such.
*
* @return string
* @throws \RuntimeException
*/
public function getSyntaxIdentifier(): string
Expand All @@ -380,7 +380,7 @@ public function getSyntaxIdentifier(): string
*/
public function load(string $location): self
{
$contents = \file_get_contents($location);
$contents = file_get_contents($location);
if ($contents === false) {
throw new \RuntimeException('File could not be retrieved');
}
Expand Down
16 changes: 4 additions & 12 deletions src/EDI/Reader.php
Original file line number Diff line number Diff line change
Expand Up @@ -561,11 +561,6 @@ private static function unwrap($string)
}

/**
* @param array $matchingSegments
* @param int $offset
* @param bool $required
* @param mixed $segment_name
*
* @return false|mixed
*/
private function getOffsetSegmentFromResult(array $matchingSegments, int $offset, bool $required, mixed $segment_name): mixed
Expand All @@ -575,27 +570,24 @@ private function getOffsetSegmentFromResult(array $matchingSegments, int $offset
}

if ($required) {
throw new ReaderException('Segment "' . $segment_name . '" does not exist at offset "' . $offset . '"');
throw new ReaderException('Segment "'.$segment_name.'" does not exist at offset "'.$offset.'"');
}

return false;
}

/**
* @param array $matchingSegments
* @param mixed $segment_name
*
* @return false|mixed
*/
private function getSegmentFromResult(array $matchingSegments, bool $required, mixed $segment_name): mixed
{
// found more than one segment - error
if (count($matchingSegments) > 1) {
throw new ReaderException('Segment "' . $segment_name . '" is ambiguous');
throw new ReaderException('Segment "'.$segment_name.'" is ambiguous');
}

if ($required && !isset($matchingSegments[0])) {
throw new ReaderException('Segment "' . $segment_name . '" no exist');
if ($required && ! isset($matchingSegments[0])) {
throw new ReaderException('Segment "'.$segment_name.'" no exist');
}

return $matchingSegments[0] ?? false;
Expand Down
2 changes: 1 addition & 1 deletion src/EDI/ReaderException.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@

class ReaderException extends RuntimeException
{
}
}
Loading

0 comments on commit ab27826

Please sign in to comment.