Codeception / Codeception/lib-xml

Xml::arrayToXml fails on nested arrays

Abierto
#7 0 comentarios 0 reacciones 0 asignados Ver en GitHub
Lenguaje dominante
PHP
Estrellas
17
Forks
1
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

The helper function arrayToXml has code indended to handle nested arrays, but currently always throws PHP errors. This means nested arrays can't be used when testing soap functions with array data either.

### Reproduce

Code:

```PHP
$dom = new \DOMDocument();
$array = [
'foo' => [
'bar' => '1'
]
];
echo \Codeception\Util\Xml::arrayToXml($dom, $dom, $array)->saveXML();
```

Expected output:

```XML

1
```

Result:
```
Undefined property: DOMDocument::$foo
```

### Cause

When the function encounters an array, it calls itself to parse the array, with `$domNode->$el` as the new $domNode parameter. The problem is that that node `->$el` will never exist, since that's the node this function was supposed to create in the first place.

### Fix

Create a new element first, to pass to the recursive call, and then append that new node to the xml structure.

Current code:
```PHP
if (is_array($val)) {
self::arrayToXml($xml, $domNode->$el, $val);
} else {
$domNode->appendChild($xml->createElement($el, $val));
}
```

Fixed code:
```PHP
if (is_array($val)) {
$elementNode = $xml->createElement($el);
self::arrayToXml($xml, $elementNode, $val);
$domNode->appendChild($elementNode);
} else {
$domNode->appendChild($xml->createElement($el, $val));
}
```

Alternatively, we could make it a little more consistent by always creating and appending the element in the same way, and only set the value inside the if-condition. That code would look like this:
```PHP
$elementNode = $xml->createElement($el);
if (is_array($val)) {
self::arrayToXml($xml, $elementNode, $val);
} else {
$elementNode->nodeValue = $val;
}
$domNode->appendChild($elementNode);
```

Both solutions result in working code for nested arrays.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.