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

XmlFormatter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 49
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A format() 0 9 1
A dataToNodes() 0 13 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