Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Use proper NULL value when we wanna use with XSD #225

Merged
merged 1 commit into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/ArrayToXml.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
class ArrayToXml
{
protected DOMDocument $document;
protected DOMElement $rootNode;

protected bool $replaceSpacesByUnderScoresInKeyNames = true;

Expand Down Expand Up @@ -46,11 +47,11 @@ public function __construct(
throw new DOMException('Invalid Character Error');
}

$root = $this->createRootElement($rootElement);
$this->rootNode = $this->createRootElement($rootElement);

$this->document->appendChild($root);
$this->document->appendChild($this->rootNode);

$this->convertElement($root, $array);
$this->convertElement($this->rootNode, $array);
}

public function setNumericTagNamePrefix(string $prefix): void
Expand Down Expand Up @@ -201,10 +202,24 @@ protected function addNode(DOMElement $element, string $key, mixed $value): void
}

$child = $this->document->createElement($key);

$this->addNodeTypeAttribute($child, $value);

$element->appendChild($child);
$this->convertElement($child, $value);
}

protected function addNodeTypeAttribute(DOMElement $element, mixed $value): void
{
if (is_null($value)) {
if (!$this->rootNode->hasAttribute('xmlns:xsi')) {
$this->rootNode->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
}

$element->setAttribute('xsi:nil', 'true');
}
}

protected function addCollectionNode(DOMElement $element, mixed $value): void
{
if ($element->childNodes->length === 0 && $element->attributes->length === 0) {
Expand Down
5 changes: 3 additions & 2 deletions tests/ArrayToXmlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -480,9 +480,10 @@
assertMatchesSnapshot($arrayToXml->dropXmlDeclaration()->toXml());
});

it('can convert an array with null value to xml', function () {
it('can convert an array with empty string and null value to xml', function () {
$arr = [
'test' => null,
'testString' => '',
'testNull' => null,
];

assertMatchesXmlSnapshot(ArrayToXml::convert($arr));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<testString/>
<testNull xsi:nil="true"/>
</root>

This file was deleted.