Skip to content

Commit dee99b2

Browse files
Ignore empty or null comment values (#249)
1 parent a4ed9e1 commit dee99b2

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,9 @@ This code will result in:
183183
</root>
184184
```
185185

186+
> [!NOTE]
187+
> A comment will be omitted if the value is an empty string "" or `null`.
188+
186189
### Using reserved characters
187190

188191
It is also possible to wrap the value of a node into a CDATA section. This allows you to use reserved characters.

src/ArrayToXml.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,9 @@ protected function convertElement(DOMElement $element, mixed $value): void
185185
} elseif (str_starts_with($key, '__custom:')) {
186186
$this->addNode($element, str_replace('\:', ':', preg_split('/(?<!\\\):/', $key)[1]), $data);
187187
} elseif (str_starts_with($key, '_comment') || str_starts_with($key, '@comment')) {
188-
$element->appendChild(new \DOMComment($data));
188+
if ($data !== null && $data !== '') {
189+
$element->appendChild(new \DOMComment($data));
190+
}
189191
} else {
190192
$this->addNode($element, $key, $data);
191193
}

tests/ArrayToXmlTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,20 @@
187187
assertMatchesXmlSnapshot(ArrayToXml::convert($withAttributes));
188188
});
189189

190+
it('null and empty comments are ignored', function () {
191+
$withAttributes = $this->testArray;
192+
$withAttributes['Another guy'] = [
193+
'_comment' => null,
194+
'name' => 'John Wick',
195+
'_comment2' => '',
196+
'weapon' => 'Pencil',
197+
'_comment_deaths' => 0,
198+
'lives' => 'more than 9 lives'
199+
];
200+
201+
assertMatchesSnapshot(ArrayToXml::convert($withAttributes, domProperties: ['formatOutput' => true]));
202+
});
203+
190204
test('and a comment also can be set in SimpleXMLElement style', function () {
191205
$withAttributes = $this->testArray;
192206
$withAttributes['Good guy']['@comment'] = 'Very short list';
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0"?>
2+
<root>
3+
<Good_guy>
4+
<name>Luke Skywalker</name>
5+
<weapon>Lightsaber</weapon>
6+
</Good_guy>
7+
<Bad_guy>
8+
<name>Sauron</name>
9+
<weapon>Evil Eye</weapon>
10+
</Bad_guy>
11+
<Another_guy>
12+
<name>John Wick</name>
13+
<weapon>Pencil</weapon>
14+
<!--0-->
15+
<lives>more than 9 lives</lives>
16+
</Another_guy>
17+
</root>

0 commit comments

Comments
 (0)