Skip to content

Commit de42691

Browse files
committed
Add support for nested dictionary Arrays
1 parent 3c30bef commit de42691

2 files changed

Lines changed: 73 additions & 1 deletion

File tree

src/Document/Dictionary/DictionaryValue/Array/ArrayValue.php

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,54 @@ public static function fromValue(string $valueString): self|ReferenceValueArray|
3131
$sanitizedValueString = str_replace(['/', "\n"], [' /', ' '], rtrim(ltrim($sanitizedValueString, '[ '), ' ]'));
3232
$sanitizedValueString = preg_replace('/\s+/', ' ', $sanitizedValueString)
3333
?? throw new RuntimeException('An error occurred while removing duplicate spaces from array value');
34-
$values = explode(' ', $sanitizedValueString);
34+
35+
$values = [];
36+
$buffer = null;
37+
$strlen = strlen($sanitizedValueString);
38+
for ($i = 0; $i < $strlen; $i++) {
39+
$char = $sanitizedValueString[$i];
40+
if ($char === '[') {
41+
if ($buffer !== null) {
42+
$values[] = $buffer;
43+
$buffer = null;
44+
}
45+
46+
$nestingLevel = 0;
47+
for ($j = $i + 1; $j < $strlen; $j++) {
48+
$char = $sanitizedValueString[$j];
49+
if ($char === '[') {
50+
$nestingLevel++;
51+
continue;
52+
}
53+
54+
if ($char === ']') {
55+
if ($nestingLevel !== 0) {
56+
$nestingLevel--;
57+
continue;
58+
}
59+
60+
$values[] = substr($sanitizedValueString, $i, $j - $i + 1);
61+
$i = $j;
62+
continue 2;
63+
}
64+
}
65+
}
66+
67+
if ($char === ' ') {
68+
if ($buffer !== null) {
69+
$values[] = $buffer;
70+
$buffer = null;
71+
}
72+
73+
continue;
74+
}
75+
76+
$buffer .= $char;
77+
}
78+
if ($buffer !== null) {
79+
$values[] = $buffer;
80+
}
81+
3582
if (count($values) % 3 === 0
3683
&& array_key_exists(2, $values)
3784
&& $values[2] === 'R'

tests/Unit/Document/Dictionary/DictionaryValue/Array/ArrayValueTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,31 @@ public function testFromValue(): void {
6262
EOD,
6363
),
6464
);
65+
static::assertEquals(
66+
new ArrayValue([1, new ArrayValue([2, 3]), 4]),
67+
ArrayValue::fromValue(
68+
<<<EOD
69+
[ 1 [ 2 3 ] 4 ]
70+
EOD,
71+
),
72+
);
73+
static::assertEquals(
74+
new ArrayValue([1, new ArrayValue([2, 3]), 4]),
75+
ArrayValue::fromValue(
76+
<<<EOD
77+
[1[2 3]4]
78+
EOD,
79+
),
80+
);
81+
static::assertEquals(
82+
new ArrayValue([1, 2, new ArrayValue([3, new ArrayValue([9, 0]), 4]), new ArrayValue([5, 6]), 7, 8]),
83+
ArrayValue::fromValue(
84+
<<<EOD
85+
[1 2 [ 3 [9 0 ] 4
86+
] [ 5 6 ] 7 8]
87+
EOD,
88+
),
89+
);
6590
}
6691

6792
public function testToString(): void {

0 commit comments

Comments
 (0)