-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
YAML.php
1448 lines (1334 loc) · 50.9 KB
/
YAML.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
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
/**
* YAML handler (last modified: 2023.03.24).
*
* This file is a part of the "common classes package", utilised by a number of
* packages and projects, including CIDRAM and phpMussel.
* @link https://github.com/Maikuolan/Common
*
* License: GNU/GPLv2
* @see LICENSE.txt
*
* "COMMON CLASSES PACKAGE" COPYRIGHT 2019 and beyond by Caleb Mazalevskis.
* *This particular class*, COPYRIGHT 2016 and beyond by Caleb Mazalevskis.
*
* Note: Some parts of the YAML specification aren't supported by this class.
* See the included documentation for more information.
*/
namespace Maikuolan\Common;
class YAML
{
/**
* @var array An array to contain all the data processed by the handler.
*/
public $Data = [];
/**
* @var array Used as a data source for inline variables.
*/
public $Refs = [];
/**
* @var string Default indent to use when reconstructing YAML data.
*/
public $Indent = ' ';
/**
* @var string Last indent used when processing YAML data.
*/
public $LastIndent = '';
/**
* @var string Captured header comments from the YAML data.
*/
public $CapturedHeader = '';
/**
* @var int Single line to folded multi-line string length limit.
*/
public $FoldedAt = 120;
/**
* @var array Used to cache any anchors found in the document.
* @link https://yaml.org/spec/1.2.2/#692-node-anchors
*/
public $Anchors = [];
/**
* @var bool Whether to escape according to the YAML specification.
* @link https://yaml.org/spec/1.2.2/#57-escaped-characters
*/
public $EscapeBySpec = false;
/**
* @var string The preferred style of quotes to use for strings.
*/
public $Quotes = '"';
/**
* @var string Which PHP string functions tag coercion can leverage.
*/
public $AllowedStringTagsPattern = '~^(?:addslashes|bin2hex|hex2bin|html(?:_entity_decode|entities|specialchars(?:_decode)?)|lcfirst|nl2br|ord|quotemeta|str(?:_rot13|_shuffle|ip(?:_tags|c?slashes)|len|rev|tolower|toupper)|ucfirst|ucwords)$~';
/**
* @var string Which numeric PHP functions tag coercion can leverage.
*/
public $AllowedNumericTagsPattern = '~^(?:a(?:bs|cosh?|sinh?|tanh?)|ceil|chr|cosh?|dec(?:bin|hex|oct)|deg2rad|exp(?:m1)?|floor|log1[0p]|rad2deg|round|sinh?|tanh?|sqrt)$~';
/**
* @var int The depth at which flows will be rebuilt.
*/
public $FlowRebuildDepth = 32;
/**
* @var bool Whether to quote keys.
*/
public $QuoteKeys = false;
/**
* @var bool Whether to render multi-line values.
*/
private $MultiLine = false;
/**
* @var bool Whether to render folded multi-line values.
*/
private $MultiLineFolded = false;
/**
* @var string Whether to use chomping for the current multiline block.
*/
private $Chomp = '';
/**
* @var array Used to determine which anchors have been reconstructed.
*/
private $AnchorsDone = [];
/**
* @var bool Whether to try reconstructing anchors during reconstruction.
*/
private $DoWithAnchors = false;
/**
* @var string Encoding used by the most recent process input.
*/
private $LastInputEncoding = '';
/**
* @var \Maikuolan\Common\Demojibakefier Used to support various encodings.
*/
private $Demojibakefier = null;
/**
* @var string Used for coercing blocks.
*/
private $LastResolvedTag = '';
/**
* @var string The tag/release the version of this file belongs to (might
* be needed by some implementations to ensure compatibility).
* @link https://github.com/Maikuolan/Common/tags
*/
public const VERSION = '2.9.6';
/**
* Can optionally begin processing data as soon as the object is
* instantiated, or just instantiate first, and manually make any needed
* calls afterwards if preferred.
*
* @param string $In The data to process.
* @return void
*/
public function __construct(string $In = '')
{
if ($In) {
$this->process($In, $this->Data, 0, true);
}
}
/**
* PHP's magic "__toString" method to act as an alias for "reconstruct".
*
* @return string
*/
public function __toString(): string
{
return $this->reconstruct($this->Data);
}
/**
* Process YAML data.
*
* @param string $In The data to be processed.
* @param array $Arr Where to store the processed data.
* @param int $Depth Tab depth (inherited through recursion; ignore it).
* @param bool $Refs Whether to set refs for inline variables.
* @return bool True when entire process completes successfully. False to exit early.
*/
public function process(string $In, array &$Arr, int $Depth = 0, bool $Refs = false): bool
{
/** Assign refs array for inline variables. */
if ($Refs) {
$this->Refs = &$Arr;
}
/** Things to do at the beginning of the process execution. */
if ($Depth === 0) {
$this->MultiLine = false;
$this->MultiLineFolded = false;
$this->LastIndent = '';
$this->CapturedHeader = '';
$Captured = [];
/** Support various encodings. */
if (class_exists('\Maikuolan\Common\Demojibakefier')) {
$this->Demojibakefier = new \Maikuolan\Common\Demojibakefier();
/**
* Attempt to determine input encoding.
* @link https://yaml.org/spec/1.2.2/#52-character-encodings
*/
if (preg_match('~^\0\0(?:\0|\xFE\xFF)~', $In)) {
$In = substr($In, 4);
$this->LastInputEncoding = 'UTF-32BE';
} elseif (preg_match('~^(?:\xFF\xFE|.\0)\0\0~', $In)) {
$In = substr($In, 4);
$this->LastInputEncoding = 'UTF-32LE';
} elseif (preg_match('~^(?:\xFE\xFF|\0)~', $In)) {
$In = substr($In, 2);
$this->LastInputEncoding = 'UTF-16BE';
} elseif (preg_match('~^(?:\xFF\xFE|.\0)~', $In)) {
$In = substr($In, 2);
$this->LastInputEncoding = 'UTF-16LE';
} else {
if (substr($In, 0, 3) === "\xEF\xBB\xBF") {
$In = substr($In, 3);
}
$this->LastInputEncoding = 'UTF-8';
}
/** Fail if non-compliant. */
if (!$this->Demojibakefier->checkConformity($In, $this->LastInputEncoding)) {
return false;
}
/** Attempt to normalise encoding if not already UTF-8. */
if ($this->LastInputEncoding !== 'UTF-8') {
/** Suppress errors to avoid potentially flooding logs. */
set_error_handler(function ($errno) {
return;
});
$Attempt = iconv($this->LastInputEncoding, 'UTF-8', $In);
if (
$Attempt === false ||
!$this->Demojibakefier->checkConformity($Attempt, 'UTF-8') ||
strcmp(iconv('UTF-8', $this->LastInputEncoding, $Attempt), $In) !== 0
) {
return false;
}
$In = $Attempt;
/** We're done.. Restore the error handler. */
restore_error_handler();
}
}
/** Attempt to capture header comments. */
if (preg_match('~^(##\\\\(?:\n#[^\n]*)+\n##/\n\n|(?:#[^\n]*\n)+\n)~m', $In, $Captured)) {
$this->CapturedHeader = $Captured[0];
}
}
$In = str_replace("\r", '', $Depth === 0 ? trim($In) : $In);
$Key = '';
$Value = '';
$SendTo = '';
/** In case of processing JSON data, or YAML data contained entirely by flow collections. */
foreach ([['[', ']'], ['{', '}']] as $Braces) {
if (substr($In, 0, 1) === $Braces[0] && substr($In, -1) === $Braces[1]) {
return $this->flowControl($In, $Arr, $Braces[0]);
}
}
$TabLen = 0;
$SoL = 0;
/** Continues until there aren't any new lines to process remaining. */
while ($SoL !== false) {
/** @var int|false End position of the current line. */
$EoL = strpos($In, "\n", $SoL);
/** @var string The current line. */
$ThisLine = ($EoL === false) ? substr($In, $SoL) : substr($In, $SoL, $EoL - $SoL);
/** @var int|false Start position of the next line. */
$SoL = ($EoL === false) ? false : $EoL + 1;
/** Strip comments and whitespace. */
if (!($ThisLine = preg_replace(['/(?<!\\\)#.*$/', '/\s+$/'], '', $ThisLine))) {
/** Line preservation for multiline and folded blocks. .*/
if (($this->MultiLine || $this->MultiLineFolded) && strlen($SendTo)) {
$SendTo .= "\n";
}
/** Skip ahead if line is empty. */
continue;
}
$ThisTab = 0;
/** Determine the indent of the current line. */
while (($Chr = substr($ThisLine, $ThisTab, 1)) && ($Chr === ' ' || $Chr === "\t")) {
$ThisTab++;
}
/** Used for reconstruction. */
if ($this->LastIndent === '') {
$this->LastIndent = str_repeat(substr($ThisLine, 0, 1), $ThisTab);
}
/**
* Data indented further than the current depth can be gathered to
* be processed recursively (e.g., sequences, multiline data, etc).
*/
if ($ThisTab > $Depth) {
if ($TabLen === 0) {
$TabLen = $ThisTab;
}
if (!$this->MultiLine && !$this->MultiLineFolded) {
$SendTo .= $ThisLine . "\n";
} else {
if ($SendTo) {
if ($this->MultiLine) {
$SendTo .= "\n";
} elseif (substr($ThisLine, $TabLen, 1) !== ' ' && substr($SendTo, -1) !== ' ') {
$SendTo .= ' ';
}
}
$SendTo .= substr($ThisLine, $TabLen);
}
continue;
}
/**
* Data indentation less than the current depth should be
* impossible. It could suggest bad data, or an error, so we'll
* exit here immediately.
*/
if ($ThisTab < $Depth) {
return false;
}
/** Process here any data gathered to be processed recursively. */
if ($SendTo) {
/** Guard. */
if (!isset($Key) || ($Key !== 0 && $Key !== '' && empty($Key))) {
return false;
}
$Success = true;
if (!$this->MultiLine && !$this->MultiLineFolded) {
if (!isset($Arr[$Key]) || !is_array($Arr[$Key])) {
$Arr[$Key] = [];
}
$Success = $this->process(preg_replace('~\n$~m', '', $SendTo), $Arr[$Key], $TabLen);
} else {
$this->tryStringDataTraverseByRef($SendTo);
if ($this->Chomp === '-') {
$SendTo = preg_replace('~[\r\n]+$~m', '', $SendTo);
} elseif ($this->Chomp === '') {
$SendTo = preg_replace('~([\r\n])[\r\n]+$~m', '\1', $SendTo);
}
$Arr[$Key] = $SendTo;
}
$HasMerged = false;
if (isset($ThisBlockTag) && $ThisBlockTag !== '') {
if ($ThisBlockTag === '!merge' && is_array($Arr[$Key])) {
$MergeData = $Arr[$Key];
unset($Arr[$Key]);
$Arr += $this->merge($MergeData);
$HasMerged = true;
} else {
$Arr[$Key] = $this->coerce($Arr[$Key], false, $ThisBlockTag);
}
}
if (!$HasMerged && $Key === '<<' && is_array($Arr[$Key])) {
$MergeData = $Arr[$Key];
unset($Arr[$Key]);
$Arr += $this->merge($MergeData);
}
if (!$Success) {
return false;
}
$SendTo = '';
}
/** Process the current line of the data at the current depth. */
if (!$this->processLine($ThisLine, $ThisTab, $Key, $Value, $Arr)) {
return false;
}
/** Needed for non-scalar coercion (sequences, merges, etc). */
$ThisBlockTag = $this->LastResolvedTag;
}
$Success = true;
/** Needed for processing any remaining data. */
if ($SendTo) {
if (!$this->MultiLine && !$this->MultiLineFolded) {
if (!isset($Arr[$Key]) || !is_array($Arr[$Key])) {
$Arr[$Key] = [];
}
$Success = $this->process(preg_replace('~\n$~m', '', $SendTo), $Arr[$Key], $TabLen);
} else {
$this->tryStringDataTraverseByRef($SendTo);
if ($this->Chomp === '-') {
$SendTo = preg_replace('~[\r\n]+$~m', '', $SendTo);
} elseif ($this->Chomp === '') {
$SendTo = preg_replace('~([\r\n])[\r\n]+$~m', '\1', $SendTo);
}
$Arr[$Key] = $SendTo;
}
$HasMerged = false;
if (isset($ThisBlockTag) && $ThisBlockTag !== '') {
if ($ThisBlockTag === '!merge' && is_array($Arr[$Key])) {
$MergeData = $Arr[$Key];
unset($Arr[$Key]);
$Arr += $this->merge($MergeData);
$HasMerged = true;
} else {
$Arr[$Key] = $this->coerce($Arr[$Key], false, $ThisBlockTag);
}
}
if (!$HasMerged && $Key === '<<' && is_array($Arr[$Key])) {
$MergeData = $Arr[$Key];
unset($Arr[$Key]);
$Arr += $this->merge($MergeData);
}
}
/** Exit. */
return $Success;
}
/**
* Reconstruct YAML.
*
* @param array $Arr The array to reconstruct from.
* @param bool $UseCaptured Whether to use captured values.
* @param bool $DoWithAnchors Whether to try reconstructing anchors.
* @return string The reconstructed YAML.
*/
public function reconstruct(array $Arr, bool $UseCaptured = false, bool $DoWithAnchors = false): string
{
$Out = '';
$this->DoWithAnchors = (count($this->Anchors) && $DoWithAnchors);
if ($UseCaptured) {
if ($this->LastIndent !== '') {
$this->Indent = $this->LastIndent;
}
if ($this->CapturedHeader !== '') {
$Out .= $this->CapturedHeader;
}
}
$this->processInner($Arr, $Out);
$this->AnchorsDone = [];
$this->DoWithAnchors = false;
return $Out;
}
/**
* Traverse data path.
*
* @param mixed $Data The data to traverse.
* @param string|array $Path The path to traverse.
* @param bool $AllowNonScalar Whether to allow non-scalar returns.
* @return mixed The traversed data, or an empty string on failure.
*/
public function dataTraverse(&$Data, $Path = [], bool $AllowNonScalar = false)
{
if (!is_array($Path)) {
$Path = preg_split('~(?<!\\\)\.~', $Path) ?: [];
}
$Segment = array_shift($Path);
if ($Segment === null || strlen($Segment) === 0) {
return $AllowNonScalar || is_scalar($Data) ? $Data : '';
}
$Segment = str_replace('\.', '.', $Segment);
if (is_array($Data) && isset($Data[$Segment])) {
return $this->dataTraverse($Data[$Segment], $Path, $AllowNonScalar);
}
if (is_object($Data) && property_exists($Data, $Segment)) {
return $this->dataTraverse($Data->$Segment, $Path, $AllowNonScalar);
}
if (is_string($Data)) {
if (preg_match('~^(?:trim|str(?:tolower|toupper|len))\(\)~i', $Segment)) {
$Segment = substr($Segment, 0, -2);
$Data = $Segment($Data);
}
}
return $this->dataTraverse($Data, $Path, $AllowNonScalar);
}
/**
* Attempt string data path traverse by reference.
*
* @param mixed $Data The data to traverse.
* @return void
*/
public function tryStringDataTraverseByRef(&$Data): void
{
if (
empty($this->Refs) ||
!is_string($Data) ||
!preg_match_all('~\{\{ ?([^\r\n{}]+) ?\}\}~', $Data, $VarMatches) ||
!isset($VarMatches[0][0], $VarMatches[1][0])
) {
return;
}
$MatchCount = count($VarMatches[0]);
for ($Index = 0; $Index < $MatchCount; $Index++) {
if (($Extracted = $this->dataTraverse($this->Refs, $VarMatches[1][$Index])) && is_string($Extracted)) {
$Data = str_replace($VarMatches[0][$Index], $Extracted, $Data);
}
}
}
/**
* Normalises the values defined by the processLine method.
*
* @param string $Value The value to be normalised.
* @param bool $EnforceScalar Whether to enforce using scalar data.
* @return void
*/
private function normaliseValue(string &$Value, bool $EnforceScalar = false): void
{
/** Avoid mistyping due to excess whitespace. */
$Value = trim($Value);
/** Resolve tags. */
if (preg_match('~^!([!\dA-Za-z_:,-]+)(?: (.*))?$~', $Value, $Resolved)) {
$Tag = strtolower($Resolved[1]);
if (!$EnforceScalar) {
$this->LastResolvedTag = $Tag;
}
$Value = $Resolved[2] ?? '';
if ($Value === '|' || $Value === '') {
return;
}
} else {
$Tag = '';
}
/** Not executed for keys. */
if (!$EnforceScalar) {
/** Check for anchors and populate if necessary. */
$AnchorMatches = [];
if (
preg_match('~^&([\dA-Za-z]+) +(.*)$~', $Value, $AnchorMatches) &&
isset($AnchorMatches[1], $AnchorMatches[2])
) {
$Value = $AnchorMatches[2];
$this->Anchors[$AnchorMatches[1]] = $Value;
} elseif (
preg_match('~^\*([\dA-Za-z]+)$~', $Value, $AnchorMatches) &&
isset($AnchorMatches[1], $this->Anchors[$AnchorMatches[1]])
) {
$Value = $this->Anchors[$AnchorMatches[1]];
}
/** Check for inline variables. */
$this->tryStringDataTraverseByRef($Value);
/** In case of processing JSON data or flow collections. */
foreach ([['[', ']'], ['{', '}']] as $Braces) {
if (substr($Value, 0, 1) === $Braces[0] && substr($Value, -1) === $Braces[1]) {
$NewArr = [];
$this->flowControl($Value, $NewArr, $Braces[0]);
$Value = $NewArr;
if ($Tag !== '') {
$Value = $this->coerce($Value, $EnforceScalar, $Tag);
}
return;
}
}
}
$ValueLen = strlen($Value);
/** Check for string quotes. */
foreach ([
['"', '"', 1],
["'", "'", 1],
['`', '`', 1],
["\x91", "\x92", 1],
["\x93", "\x94", 1],
["\xe2\x80\x98", "\xe2\x80\x99", 3],
["\xe2\x80\x9c", "\xe2\x80\x9d", 3]
] as $Wrapper) {
if (substr($Value, 0, $Wrapper[2]) === $Wrapper[0] && substr($Value, $ValueLen - $Wrapper[2]) === $Wrapper[1]) {
$Value = substr($Value, $Wrapper[2], $ValueLen - ($Wrapper[2] * 2));
$Value = $this->unescape($Value, $Wrapper[0]);
if ($Tag !== '') {
$Value = $this->coerce($Value, $EnforceScalar, $Tag);
}
return;
}
}
/** Executed only for keys. */
if ($EnforceScalar) {
$Value = trim($Value);
if ($Tag !== '') {
$Value = $this->coerce($Value, $EnforceScalar, $Tag);
} elseif (preg_match('~^\d+$~', $Value)) {
$Value = (int)$Value;
}
return;
}
if ($Tag !== '') {
$Value = $this->coerce($Value, $EnforceScalar, $Tag);
return;
}
$ValueLow = strtolower($Value);
if ($ValueLow === 'true' || $ValueLow === 'on' || $ValueLow === 'y' || $ValueLow === 'yes' || $Value === '+') {
$Value = true;
} elseif ($ValueLow === 'false' || $ValueLow === 'n' || $ValueLow === 'no' || $ValueLow === 'off' || $Value === '-' || $ValueLen === 0) {
$Value = false;
} elseif ($ValueLow === 'null' || $Value === '~') {
$Value = null;
} elseif ($ValueLow === '.inf') {
$Value = INF;
} elseif ($ValueLow === '-.inf') {
$Value = -INF;
} elseif ($ValueLow === '.nan') {
$Value = NAN;
} elseif (preg_match('~^0x[\dA-Fa-f]+$~', $Value)) {
$Value = hexdec(str_replace('_', '', substr($Value, 2)));
} elseif (preg_match('~^0o[0-8]+$~', $Value)) {
$Value = octdec(str_replace('_', '', substr($Value, 2)));
} elseif (preg_match('~^0b[01]+$~', $Value)) {
$Value = bindec(str_replace('_', '', substr($Value, 2)));
} elseif (preg_match('~^\d+$~', $Value)) {
$Value = (int)str_replace('_', '', $Value);
} elseif (preg_match('~^(?:\d+\.\d+|\d+(?:\.\d+)?[Ee][-+]\d+)$~', $Value)) {
$Value = (float)str_replace('_', '', $Value);
}
}
/**
* Process a single line of YAML input.
*
* @param string $ThisLine The line to be processed.
* @param int $ThisTab The size of the line indentation.
* @param string|int $Key Line key.
* @param string|int|bool $Value Line value.
* @param array $Arr Where to store the data.
* @return bool True when entire process completes successfully. False to exit early.
*/
private function processLine(string &$ThisLine, int &$ThisTab, &$Key, &$Value, array &$Arr): bool
{
/** Reset last resolved tag. */
$this->LastResolvedTag = '';
if ($ThisLine === '---') {
$Key = '---';
$Value = null;
$Arr[$Key] = $Value;
} elseif ($ThisLine === '...') {
$Key = '...';
$Value = null;
$Arr[$Key] = $Value;
} elseif (substr($ThisLine, -1) === ':' && strpos($ThisLine, ': ') === false) {
$Key = substr($ThisLine, $ThisTab, -1);
$this->normaliseValue($Key, true);
if (!isset($Arr[$Key])) {
$Arr[$Key] = null;
}
$Value = null;
} elseif (substr($ThisLine, $ThisTab, 2) === '? ') {
$Key = substr($ThisLine, $ThisTab + 2);
$this->normaliseValue($Key, true);
$Value = null;
$Arr[$Key] = null;
} elseif (substr($ThisLine, $ThisTab, 2) === '- ') {
$Value = substr($ThisLine, $ThisTab + 2);
$ValueLen = strlen($Value);
$this->normaliseValue($Value);
if ($ValueLen > 0) {
if ($this->LastResolvedTag === '!merge' && is_array($Value)) {
$Arr += $this->merge($Value);
} else {
$Arr[] = $Value;
}
}
$Key = $this->arrayKeyLast($Arr);
} elseif (substr($ThisLine, $ThisTab) === '-') {
$Value = null;
$Arr[] = $Value;
$Key = $this->arrayKeyLast($Arr);
} elseif (($DelPos = strpos($ThisLine, ': ')) !== false) {
$Key = substr($ThisLine, $ThisTab, $DelPos - $ThisTab);
$KeyLen = strlen($Key);
$this->normaliseValue($Key, true);
if (!$Key) {
if (substr($ThisLine, $ThisTab, $DelPos - $ThisTab + 2) !== '0: ') {
return false;
}
$Key = 0;
}
$Value = substr($ThisLine, $ThisTab + $KeyLen + 2);
$ValueLen = strlen($Value);
$this->normaliseValue($Value);
if ($ValueLen > 0) {
if (($this->LastResolvedTag === '!merge' || $Key === '<<') && is_array($Value)) {
$Arr += $this->merge($Value);
} else {
$Arr[$Key] = $Value;
}
}
} elseif (strpos($ThisLine, ':') === false && strlen($ThisLine) > 1) {
$Key = $ThisLine;
$this->normaliseValue($Key, true);
if (!isset($Arr[$Key])) {
$Arr[$Key] = null;
}
$Value = null;
}
/**
* Chomping.
* @link https://yaml.org/spec/1.2.2/#8112-block-chomping-indicator
*/
if (is_string($Value) && strlen($Value) === 2) {
$Chomp = substr($Value, -1);
if ($Chomp === '-') {
$this->Chomp = '-';
$Value = substr($Value, 0, 1);
} elseif ($Chomp === '+') {
$this->Chomp = '+';
$Value = substr($Value, 0, 1);
} else {
$this->Chomp = '';
}
} else {
$this->Chomp = '';
}
$this->MultiLine = ($Value === '|');
$this->MultiLineFolded = ($Value === '>');
return true;
}
/**
* Reconstruct an inner level of YAML (shouldn't be called directly).
*
* @param array $Arr The array to reconstruct from.
* @param string $Out The reconstructed YAML.
* @param int $Depth The level depth.
* @return void
*/
private function processInner(array $Arr, string &$Out, int $Depth = 0): void
{
$Sequential = (array_keys($Arr) === range(0, count($Arr) - 1));
$NullSet = $this->isNullSet($Arr);
if ($Depth >= $this->FlowRebuildDepth) {
$Out .= $Sequential ? '[' : '{';
$First = true;
foreach ($Arr as $Key => $Value) {
if ($First) {
$First = false;
} else {
$Out .= ',';
}
if (!$Sequential) {
$Out .= ($this->QuoteKeys ? $this->scalarToString($Key) : $Key) . ':';
}
if (is_array($Value)) {
$this->processInner($Value, $Out, $Depth + 1);
continue;
}
$ToAdd = $this->scalarToString($Value);
if ($this->DoWithAnchors) {
foreach ($this->Anchors as $Name => $Data) {
if ($Data === $ToAdd) {
if (empty($this->AnchorsDone[$Name])) {
$ToAdd = '&' . $Name . ' ' . $ToAdd;
$this->AnchorsDone[$Name] = true;
} else {
$ToAdd = '*' . $Name;
}
break;
}
}
}
$Out .= $ToAdd;
}
$Out .= $Sequential ? ']' : '}';
if ($Depth === $this->FlowRebuildDepth) {
$Out .= "\n";
}
return;
}
foreach ($Arr as $Key => $Value) {
if ($Key === '---' && $Value === null) {
$Out .= "---\n";
continue;
}
if ($Key === '...' && $Value === null) {
$Out .= "...\n";
continue;
}
$ThisDepth = str_repeat($this->Indent, $Depth);
if ($NullSet && !$Sequential) {
$Out .= $ThisDepth . '?';
$Value = $Key;
} else {
$Out .= $ThisDepth . ($Sequential ? '-' : ($this->QuoteKeys ? $this->scalarToString($Key) : $Key) . ':');
}
if (is_array($Value)) {
if ($Depth < $this->FlowRebuildDepth - 1) {
$Out .= "\n";
}
$this->processInner($Value, $Out, $Depth + 1);
continue;
}
$Out .= ' ';
if (is_string($Value)) {
$HasHash = strpos($Value, '#') !== false;
if (!$HasHash && strpos($Value, "\n") !== false) {
if (preg_match('~\n{2,}$~m', $Value)) {
$ToAdd = "|+\n" . $ThisDepth . $this->Indent;
} else {
$ToAdd = "|\n" . $ThisDepth . $this->Indent;
}
$ToAdd .= preg_replace('~\n(?=[^\n])~m', "\n" . $ThisDepth . $this->Indent, $Value);
} elseif (!$HasHash && $this->FoldedAt > 0 && strpos($Value, ' ') !== false && strlen($Value) >= $this->FoldedAt) {
$ToAdd = ">\n" . $ThisDepth . $this->Indent . wordwrap(
$Value,
$this->FoldedAt,
"\n" . $ThisDepth . $this->Indent
);
} else {
$ToAdd = $this->Quotes . $this->escape($Value) . $this->Quotes;
}
} else {
$ToAdd = $this->scalarToString($Value);
}
if ($this->DoWithAnchors) {
foreach ($this->Anchors as $Name => $Data) {
if ($Data === $ToAdd) {
if (empty($this->AnchorsDone[$Name])) {
$ToAdd = '&' . $Name . ' ' . $ToAdd;
$this->AnchorsDone[$Name] = true;
} else {
$ToAdd = '*' . $Name;
}
break;
}
}
}
$Out .= $ToAdd . "\n";
}
}
/**
* Escape according to the YAML specification.
*
* @param string $Value The string to escape.
* @param bool $Newlines Whether to escape newlines.
* @return string The escaped string.
*/
private function escape(string $Value = '', bool $Newlines = true): string
{
if ($this->Quotes === "'") {
return str_replace("'", "''", $Value);
}
if ($this->Quotes !== '"') {
return $Value;
}
$Value = str_replace("\\", "\\\\", $Value);
if ($Newlines) {
$Value = str_replace("\n", '\n', $Value);
}
$Value = str_replace(
['#', "\0", "\7", "\8", "\t", "\x0B", "\x0C", "\x0D", "\x1B", "\xC2\x85", "\xC2\xA0", "\xE2\x80\xA8", "\xE2\x80\xA9"],
['\#', '\0', '\a', '\b', '\t', '\v', '\f', '\r', '\e', '\N', '\_', '\L', '\P'],
$Value
);
$Value = preg_replace_callback([
'~[\x01-\x06\x0E\x0F\x10-\x1A\x1C-\x1F\x7F\xC0\xC1\xF5-\xFF]~',
'~[\xC2-\xDF](?![\x80-\xBF])~',
'~\xE0(?![\xA0-\xBF][\x80-\xBF])~',
'~[\xE1-\xEC](?![\x80-\xBF]{2})~',
'~\xED(?![\x80-\x9F][\x80-\xBF])~',
'~\xF0(?![\x90-\xBF][\x80-\xBF]{2})~',
'~[\xF1-\xF3](?![\x80-\xBF]{3})~',
'~\xF4(?![\x80-\x8F][\x80-\xBF]{2})~',
'~(?<=[\x00-\x7F\xF5-\xFF])[\x80-\xBF]~',
'~(?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF])~',
'~(?<=[\xF0-\xF4])[\x80-\xBF](?![\x80-\xBF]{2})~',
'~(?<=[\xF0-\xF4][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF])~'
], function ($Match) {
return '\\x' . bin2hex($Match[0]);
}, $Value);
if ($this->EscapeBySpec) {
$Value = str_replace(['"', '/'], ['\"', '\/'], $Value);
}
return $Value;
}
/**
* Unescape according to the YAML specification.
*
* @param string $Value The string to unescape.
* @param string $Style The quote style used.
* @return string The unescaped string.
*/
private function unescape(string $Value = '', string $Style = '"'): string
{
if ($Style === '"' || $Style === "\xe2\x80\x9c" || $Style === "\x91") {
$Value = str_replace(
['\#', '\0', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\e', '\"', '\/', '\N', '\_', '\L', '\P', "\\\\"],
['#', "\0", "\x07", "\x08", "\t", "\n", "\x0B", "\x0C", "\x0D", "\x1B", '"', '/', "\xC2\x85", "\xC2\xA0", "\xE2\x80\xA8", "\xE2\x80\xA9", "\\"],
$Value
);
$Captured = [];
if (preg_match_all('~\\\\x([\dA-Fa-f]{2})~', $Value, $Captured)) {
$Captured = array_unique($Captured[1]);
foreach ($Captured as $Bytes) {
$Value = str_replace('\\x' . $Bytes, hex2bin($Bytes), $Value);
}
}
$Captured = [];
if (preg_match_all('~\\\\u([\dA-Fa-f]{4})~', $Value, $Captured)) {
set_error_handler(function ($errno) {
return;
});
$Captured = array_unique($Captured[1]);
foreach ($Captured as $Bytes) {
$Decoded = hex2bin($Bytes);
$Attempt = iconv('UTF-16BE', 'UTF-8', $Decoded);
$Reversed = $Attempt === false ? '' : iconv('UTF-8', 'UTF-16BE', $Attempt);
if ($Attempt !== false && strcmp($Reversed, $Decoded) === 0) {
$Decoded = $Attempt;
}
$Value = str_replace('\\u' . $Bytes, $Decoded, $Value);
}
restore_error_handler();
}
$Captured = [];
if (preg_match_all('~\\\\U([\dA-Fa-f]{8})~', $Value, $Captured)) {
set_error_handler(function ($errno) {
return;
});
$Captured = array_unique($Captured[1]);
foreach ($Captured as $Bytes) {
$Decoded = hex2bin($Bytes);
$Attempt = iconv('UTF-32BE', 'UTF-8', $Decoded);
$Reversed = $Attempt === false ? '' : iconv('UTF-8', 'UTF-32BE', $Attempt);
if ($Attempt !== false && strcmp($Reversed, $Decoded) === 0) {
$Decoded = $Attempt;
}
$Value = str_replace('\\U' . $Bytes, $Decoded, $Value);
}
restore_error_handler();
}
return $Value;
}
if ($Style === "'" || $Style === "\xe2\x80\x98" || $Style === "\x93") {
return str_replace("''", "'", $Value);
}
return $Value;
}
/**
* Check whether an array is a null set.
*
* @param array $Arr The array.
* @return bool True for null set; False otherwise.
*/
private function isNullSet(array $Arr): bool
{
foreach ($Arr as $Value) {
if ($Value !== null) {
return false;
}
}
return true;
}
/**
* Coerces a value according to the specified tag.
*
* @param mixed $Value The value to be coerced.
* @param bool $EnforceScalar Whether to enforce using scalar data.
* @param string $Tag The resolved tag.
* @return mixed The coerced value.
*/
private function coerce($Value, bool $EnforceScalar, string $Tag)
{
/**
* @link https://yaml.org/type/null.html
*/
if ($Tag === '!null') {
return null;
}
/** Not executed for keys. */
if (!$EnforceScalar) {
/**
* A "map" in YAML <-> An "associative array" in PHP.
* Because PHP arrays always have an "order" (i.e., a key index), I
* see no effective difference between !!map and !!omap in the
* context of a YAML handler written for PHP.
* @link https://yaml.org/type/map.html
* @link https://yaml.org/type/omap.html
*/
if ($Tag === '!map' || $Tag === '!omap') {
if (!is_array($Value)) {
if (is_string($Value)) {
$this->normaliseValue($Value);
}