Passed
Push — master ( 4d448d...bb39f0 )
by Dominik
03:17
created

XmlFormatter::dataToNodes()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 3
nop 3
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Formatter;
6
7
use Doctrine\Common\Inflector\Inflector;
8
9
final class XmlFormatter implements FormatterInterface
10
{
11
    /**
12
     * @var bool
13
     */
14
    private $formatOutput;
15
16
    /**
17
     * @param bool $formatOutput
18
     */
19 1
    public function __construct(bool $formatOutput = false)
20
    {
21 1
        $this->formatOutput = $formatOutput;
22 1
    }
23
24
    /**
25
     * @param array $data
26
     *
27
     * @return string
28
     */
29 1
    public function format(array $data): string
30
    {
31 1
        $document = new \DOMDocument('1.0', 'UTF-8');
32 1
        $document->formatOutput = $this->formatOutput;
33
34 1
        $this->dataToNodes($document, $document, $data);
35
36 1
        return $document->saveXML();
37
    }
38
39
    /**
40
     * @param \DOMDocument $document
41
     * @param \DOMNode     $listNode
42
     * @param array        $data
43
     */
44 1
    private function dataToNodes(\DOMDocument $document, \DOMNode $listNode, array $data)
45
    {
46 1
        foreach ($data as $key => $value) {
47 1
            if (is_array($value)) {
48 1
                $childNode = $document->createElement(is_int($key) ? Inflector::singularize($listNode->nodeName) : $key);
49 1
                $this->dataToNodes($document, $childNode, $value);
50
            } else {
51 1
                $childNode = $document->createElement($key, $value);
52
            }
53
54 1
            $listNode->appendChild($childNode);
55
        }
56 1
    }
57
}
58