Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
95.00% |
19 / 20 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
Xml | |
95.00% |
19 / 20 |
|
50.00% |
1 / 2 |
7 | |
0.00% |
0 / 1 |
encode | |
92.31% |
12 / 13 |
|
0.00% |
0 / 1 |
4.01 | |||
traverse | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Projom\Util; |
6 | |
7 | use DOMDocument; |
8 | use DOMElement; |
9 | |
10 | class Xml |
11 | { |
12 | public static function encode(array $toEncode, string $rootNodeName): string |
13 | { |
14 | if (!$toEncode) |
15 | return ''; |
16 | |
17 | /* |
18 | * This is a rather naive approach to solving this issue. |
19 | * Theres an assumption: the $toEncode will have one "master"-key. |
20 | * Any other parallell entries will be lost. |
21 | */ |
22 | if (!$rootNodeName) { |
23 | $rootNodeName = array_key_first($toEncode); |
24 | $toEncode = array_shift($toEncode); |
25 | } |
26 | |
27 | $dom = new DOMDocument('1.0', 'UTF-8'); |
28 | #$dom->formatOutput = false; |
29 | #$dom->preserveWhiteSpace = false; |
30 | |
31 | $rootNode = $dom->createElement($rootNodeName); |
32 | static::traverse($toEncode, $rootNode); |
33 | $dom->appendChild($rootNode); |
34 | |
35 | $result = $dom->saveXML(); |
36 | if ($result === false) |
37 | return ''; |
38 | |
39 | return $result; |
40 | } |
41 | |
42 | public static function traverse(array $toEncode, DOMElement $rootNode): void |
43 | { |
44 | foreach ($toEncode as $key => $value) { |
45 | if (is_array($value)) { |
46 | $node = new DOMElement((string)$key); |
47 | $rootNode->appendChild($node); |
48 | static::traverse($value, $node); |
49 | } else { |
50 | $node = new DOMElement((string)$key, (string)$value); |
51 | $rootNode->appendChild($node); |
52 | } |
53 | } |
54 | } |
55 | } |