-
Notifications
You must be signed in to change notification settings - Fork 88
/
Parser.php
683 lines (584 loc) · 17.8 KB
/
Parser.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
<?php
declare(strict_types=1);
namespace EDI;
/**
* EDIFACT Messages Parser
* (c)2018 Stefano Sabatini
*/
class Parser
{
/**
* @var array|string[]
*/
private $rawSegments = [];
/**
* @var array
*/
private $parsedfile = [];
/**
* @var array
*/
private $errors = [];
/**
* @var string
*/
private $stripChars = "/[\x01-\x1F\x80-\xFF]/"; // UNOB encoding set
/**
* @var string
*/
private static $DELIMITER = '/';
/**
* @var string Component separator character
*/
private $sepComp = "\:";
/**
* @var string Component separator character
*/
private $sepUnescapedComp = ':';
/**
* @var string Data separator character
*/
private $sepData = "\+";
/**
* @var string Dec separator character (no use but here)
*/
private $sepDec = '.';
/**
* @var string Release character
*/
private $symbRel = "\?";
/**
* @var string (default ?)
*/
private $symbUnescapedRel = '?';
/**
* @var string Repetition character (no use but here)
*/
private $symbRep = '*';
/**
* @var string End character
*/
private $symbEnd = "'";
/**
* @var string Safe string
*/
private $stringSafe = '§SS§';
/**
* @var string UNB Syntax identifier
*/
private string $syntaxID = '';
/**
* @var string|null Message format from UNH
*/
private $messageFormat;
/**
* @var string Message directory
*/
private $messageDirectory;
/**
* @var string Message number
*/
private $messageNumber;
private ?string $sourceEncoding = null;
/**
* @var array<string,string>
*/
private static $encodingToStripChars = [
'UNOA' => "/[\x01-\x1F\x80-\xFF]/", // not as restrictive as it should be
'UNOB' => "/[\x01-\x1F\x80-\xFF]/",
'UNOC' => "/[\x01-\x1F\x7F-\x9F]/",
'UNOE' => "/[\x20-\x7E]\xA0-\xFF/",
];
private static $charsets = [
// ISO 646, except lower case letters, alternative graphic chars, national or application-oriented graphic chars
'UNOA' => 'ASCII',
// ISO 646, except alternative graphic chars and national or application-oriented graphic chars
'UNOB' => 'ASCII',
'UNOC' => 'ISO-8859-1',
'UNOD' => 'ISO-8859-2',
'UNOE' => 'ISO-8859-5',
'UNOF' => 'ISO-8859-7',
];
/**
* @var bool TRUE when UNA characters are known.
*/
private $unaChecked = false;
/**
* @var bool TRUE when UNB encoding is known.
*/
private $unbChecked = false;
/**
* Optionally disable workarounds.
*/
private bool $strict = false;
/**
* Parse EDI array.
*/
public function parse(): self
{
$rawSegments = $this->getRawSegments();
if ($this->sourceEncoding && isset(self::$charsets[$this->syntaxID]) && self::$charsets[$this->syntaxID] !== $this->sourceEncoding) {
$rawSegments = $this->convertEncoding($this->rawSegments, $this->sourceEncoding, self::$charsets[$this->syntaxID]);
}
$i = 0;
foreach ($rawSegments as $line) {
$i++;
// Null byte and carriage return removal. (CR+LF)
$line = \str_replace(["\x00", "\r", "\n"], '', $line);
// Basic sanitization, remove non-printable chars.
$lineTrim = \trim($line);
$line = (string) \preg_replace($this->stripChars, '', $lineTrim);
$line_bytes = \strlen($line);
if ($line_bytes !== \strlen($lineTrim)) {
$this->errors[] = 'Non-printable character on line '.$i.': '.$lineTrim;
}
if ($line_bytes < 2) {
continue;
}
switch (\substr($line, 0, 3)) {
case 'UNA':
if (! $this->unaChecked) {
$this->analyseUNA(\substr($line, 4, 6));
}
break;
case 'UNB':
$line = $this->splitSegment($line);
if (! $this->unbChecked) {
$this->analyseUNB($line[1]);
}
$this->parsedfile[] = $line;
break;
case 'UNH':
$line = $this->splitSegment($line);
$this->analyseUNH($line);
$this->parsedfile[] = $line;
break;
default:
$line = $this->splitSegment($line);
$this->parsedfile[] = $line;
break;
}
}
return $this;
}
/**
* Read UNA's characters definition.
*
* @param string $line UNA definition line (without UNA tag). Example : :+.? '
* @return void
*/
public function analyseUNA(string $line)
{
$line = \substr($line, 0, 6);
if (isset($line[0])) {
$this->sepComp = \preg_quote($line[0], self::$DELIMITER);
$this->sepUnescapedComp = $line[0];
if (isset($line[1])) {
$this->sepData = \preg_quote($line[1], self::$DELIMITER);
if (isset($line[2])) {
$this->sepDec = $line[2]; // See later if a preg_quote is needed
if (isset($line[3])) {
$this->symbRel = \preg_quote($line[3], self::$DELIMITER);
$this->symbUnescapedRel = $line[3];
if (isset($line[4])) {
$this->symbRep = $line[4]; // See later if a preg_quote is needed
if (isset($line[5])) {
$this->symbEnd = \preg_quote($line[5], self::$DELIMITER);
}
}
}
}
}
$this->unaChecked = true;
}
}
/**
* UNB line analysis.
*
* @param string|string[] $line UNB definition line (without UNB tag). Example UNOA:2
*/
public function analyseUNB($line): void
{
if (\is_array($line)) {
$line = $line[0];
}
$this->syntaxID = $line;
// If there's a regex defined for this character set, use it.
/** @noinspection OffsetOperationsInspection */
if (isset(self::$encodingToStripChars[$line])) {
/** @noinspection OffsetOperationsInspection */
$this->setStripRegex(self::$encodingToStripChars[$line]);
}
$this->unbChecked = true;
}
/**
* Identify message type.
*
* @param array<mixed|string> $line UNH segment
*/
public function analyseUNH(array $line): void
{
if (\count($line) < 3) {
return;
}
$this->messageNumber = $line[1];
$lineElement = $line[2];
if (! \is_array($lineElement)) {
$this->messageFormat = $lineElement;
return;
}
$this->messageFormat = $lineElement[0];
$this->messageDirectory = $lineElement[2];
}
/**
* Check if the file's character encoding actually matches the one declared in the UNB header.
*
* @throws \LogicException
* @throws \RuntimeException
*/
public function checkEncoding(): bool
{
if (empty($this->parsedfile)) {
throw new \LogicException('No text has been parsed yet');
}
if (! isset(self::$charsets[$this->syntaxID])) {
throw new \RuntimeException('Unsupported syntax identifier: '.$this->syntaxID);
}
$check = mb_check_encoding($this->parsedfile, self::$charsets[$this->syntaxID]);
if (! $check) {
$this->errors[] = 'Character encoding does not match declaration in UNB interchange header';
}
return $check;
}
/**
* Get errors.
*/
public function errors(): array
{
return $this->errors;
}
/**
* (Un)Set strict parsing.
*/
public function setStrict(bool $strict): void
{
$this->strict = $strict;
}
public function setSourceEncoding(string $sourceEncoding): void
{
$this->sourceEncoding = $sourceEncoding;
}
/**
* Get parsed lines/segments.
*/
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);
}
return $data;
}
/**
* Get raw segments array.
*
* @return array|string[]
*/
public function getRawSegments(): array
{
return $this->rawSegments;
}
/**
* Get syntax identifier from the UNB header.
* Does not necessarily mean that the text is actually encoded as such.
*
* @throws \RuntimeException
*/
public function getSyntaxIdentifier(): string
{
return $this->syntaxID;
}
/**
* Load the message from file.
*
* @param string $location Either a local file path or a URL
*/
public function load(string $location): self
{
$contents = file_get_contents($location);
if ($contents === false) {
throw new \RuntimeException('File could not be retrieved');
}
$this->loadString($contents);
return $this;
}
/**
* Load the message from a string.
*/
public function loadString(string $txt): self
{
$this->resetUNA();
$this->resetUNB();
$this->rawSegments = $this->unwrap($txt);
return $this;
}
/**
* Load a raw or parsed message from an array of strings.
*
* @param bool $raw If the data hasn't been parsed yet
*/
public function loadArray(array $lines, bool $raw = true): self
{
if ($raw) {
$this->resetUNA();
$this->resetUNB();
$this->rawSegments = $lines;
if (\count($lines) === 1) {
$this->loadString($lines[0]);
}
} else {
$this->rawSegments = [];
$this->parsedfile = $lines;
}
return $this;
}
/**
* Change the default regex used for stripping invalid characters.
*
* @return void
*/
public function setStripRegex(string $regex)
{
$this->stripChars = $regex;
}
/**
* Get the message type ID.
*
* @return string|null
*/
public function getMessageFormat()
{
return $this->messageFormat;
}
/**
* Get the message type release number.
*
* @return string|null
*/
public function getMessageDirectory()
{
return $this->messageDirectory;
}
/**
* @return string|null
*/
public function getMessageNumber()
{
return $this->messageNumber;
}
/**
* Reset UNA character definition to defaults.
*/
private function resetUNA(): void
{
$this->sepComp = "\:";
$this->sepUnescapedComp = ':';
$this->sepData = "\+";
$this->sepDec = '.'; // See later if a preg_quote is needed
$this->symbRel = "\?";
$this->symbUnescapedRel = '?';
$this->symbRep = '*'; // See later if a preg_quote is needed
$this->symbEnd = "'";
$this->stringSafe = '§SS§';
$this->unaChecked = false;
}
/**
* Reset UNB encoding definition to defaults.
*/
private function resetUNB(): void
{
$this->syntaxID = '';
$this->unbChecked = false;
}
/**
* Unwrap string splitting rows on terminator (if not escaped).
*
* @return string[]
*/
private function unwrap(string &$string): array
{
if (
! $this->unaChecked
&&
\strpos($string, 'UNA') === 0
) {
$this->analyseUNA(
\substr(\substr($string, 3), 0, 9)
);
}
$unbRegex = sprintf(
'/^(UNA[^%1$s]+%1$s\W?\W?)?UNB%2$s(?<syntax_identifier>\w{4})%3$s/m',
$this->symbEnd,
$this->sepData,
$this->sepComp,
);
if (
! $this->unbChecked
&& false !== preg_match($unbRegex, $string, $unbMatches)
&& isset($unbMatches['syntax_identifier'])
) {
$this->analyseUNB($unbMatches['syntax_identifier']);
}
if (preg_match_all("/[A-Z0-9]+(?:\?'|$)[\r\n]+/i", $string, $matches, PREG_OFFSET_CAPTURE) > 0) {
$this->errors[] = 'This file contains some segments without terminators';
}
$terminatorRegex = '/(([^'.$this->symbRel.']'.$this->symbRel.'{2})+|[^'.$this->symbRel.'])'.$this->symbEnd.'|[\r\n]+/';
if ($this->strict) {
$terminatorRegex = '/(([^'.$this->symbRel.']'.$this->symbRel.'{2})+|[^'.$this->symbRel.'])'.$this->symbEnd.'/';
}
$string = (string) \preg_replace(
$terminatorRegex,
'$1'.$this->stringSafe,
$string
);
$file = \preg_split(
self::$DELIMITER.$this->stringSafe.self::$DELIMITER.'i',
$string
);
// fallback
if ($file === false) {
$file = [];
}
$end = \stripslashes($this->symbEnd.'');
foreach ($file as $fc => &$line) {
if (\trim($line) == '') {
/* @noinspection OffsetOperationsInspection */
unset($file[$fc]);
}
$line .= $end;
}
return $file;
}
/**
* Split segment.
*
* @return array|string[]
*/
private function splitSegment(string &$str): array
{
// remove ending "symbEnd"
$str = \trim(
(string) \preg_replace(
self::$DELIMITER.$this->symbEnd.'$'.self::$DELIMITER,
'',
$str
)
);
// replace duplicate "symbRel"
$str = \str_replace(
$this->symbUnescapedRel.$this->symbUnescapedRel.'',
$this->stringSafe ?? '',
$str
);
// split on "sepData" if not escaped (negative lookbehind)
$matches = \preg_split(
self::$DELIMITER.'(?<!'.$this->symbRel.')'.$this->sepData.self::$DELIMITER,
$str
);
// fallback
if ($matches === false) {
$matches = [];
}
foreach ($matches as &$value) {
if ($value === '') {
continue;
}
// INFO:
//
// ? immediately preceding one of the characters '+:? restores their normal meaning
//
// e.g. 10?+10=20 means 10+10=20
//
// Question mark is represented by ??
if (
$this->symbEnd
&&
\strpos($value, $this->symbEnd) !== false
) {
if (\preg_match(self::$DELIMITER.'(?<!'.$this->symbRel.')'.$this->symbEnd.self::$DELIMITER, $value)) {
$this->errors[] = "There's a ".\stripslashes($this->symbEnd).' not escaped in the data; string '.$str;
}
}
if (
$this->symbUnescapedRel
&&
\strpos($value, $this->symbUnescapedRel) !== false
) {
if (\preg_match(self::$DELIMITER.'(?<!'.$this->symbRel.')'.$this->symbRel.'(?!'.$this->symbRel.')(?!'.$this->sepData.')(?!'.$this->sepComp.')(?!'.$this->symbEnd.')'.self::$DELIMITER, $value)) {
$this->errors[] = "There's a character not escaped with ".\stripslashes($this->symbRel ?? '').' in the data; string '.$value;
}
}
// split on "sepComp"
$value = $this->splitData($value);
}
return $matches;
}
/**
* Composite data element.
*
* @return mixed
*/
private function splitData(string &$str)
{
if ($str === '') {
return $str;
}
$replace = function (&$string) {
if ($this->symbUnescapedRel && \strpos($string, $this->symbUnescapedRel) !== false) {
$string = \preg_replace(
self::$DELIMITER.$this->symbRel.'(?='.$this->symbRel.')|'.$this->symbRel.'(?='.$this->sepData.')|'.$this->symbRel.'(?='.$this->sepComp.')|'.$this->symbRel.'(?='.$this->symbEnd.')'.self::$DELIMITER,
'',
$string
);
}
return \str_replace(
$this->stringSafe ?? '',
$this->symbUnescapedRel ?? '',
$string
);
};
// check for "sepUnescapedComp" in the string
if ($this->sepUnescapedComp && \strpos($str, $this->sepUnescapedComp) === false) {
return $replace($str);
}
// split on "sepComp" if not escaped (negative lookbehind)
$array = \preg_split(
self::$DELIMITER.'(?<!'.$this->symbRel.')'.$this->sepComp.self::$DELIMITER,
$str
);
// fallback
if ($array === false) {
$array = [[]];
}
if (\count($array) === 1) {
return $replace($str);
}
foreach ($array as &$value) {
$value = $replace($value);
}
return $array;
}
}