Passed
Push — master ( 4d3943...40ff2a )
by Dominik
01:52
created

XmlFormatter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 65
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A format() 0 9 1
A dataToNodes() 0 14 4
A getValueAsString() 0 10 3
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, $this->getValueAsString($value));
52 1
                $childNode->setAttribute('type', gettype($value));
53
            }
54
55 1
            $listNode->appendChild($childNode);
56
        }
57 1
    }
58
59
    /**
60
     * @param bool|float|int|string $value
61
     * @return string
62
     */
63 1
    private function getValueAsString($value): string
64
    {
65 1
        $type = gettype($value);
66
67 1
        if ('boolean' === $type) {
68 1
            return $value ? 'true' : 'false';
69
        }
70
71 1
        return (string) $value;
72
    }
73
}
74