SimpleXMLRenderer::getSimpleXmlElement()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 1
b 0
f 0
ccs 0
cts 2
cp 0
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Phauthentic\Presentation\Renderer;
5
6
use Phauthentic\Presentation\View\ViewInterface;
7
use SimpleXMLElement;
8
9
/**
10
 * Simple XML Renderer
11
 *
12
 * @link https://stackoverflow.com/questions/1397036/how-to-convert-array-to-simplexml
13
 */
14
class SimpleXMLRenderer implements RendererInterface
15
{
16
    /**
17
     * XML Root Node
18
     *
19
     * @var string
20
     */
21
    protected $rootNode = '<?xml version="1.0"?><data></data>';
22
23
    /**
24
     * Constructor
25
     *
26
     * @param null|string $rootNode Root Node
27
     */
28
    public function __construct(?string $rootNode = null)
29
    {
30
        if ($rootNode) {
31
            $this->rootNode = $rootNode;
32
        }
33
    }
34
35
    /**
36
     * Sets the Root Node
37
     *
38
     * @param string $rootNode Root Node
39
     * @return $this
40
     */
41
    public function setRootNode(string $rootNode): self
42
    {
43
        $this->rootNode = $rootNode;
44
45
        return $this;
46
    }
47
48
    /**
49
     * Get simple XML Element
50
     *
51
     * @return \SimpleXMLElement
52
     */
53
    protected function getSimpleXmlElement(): SimpleXMLElement
54
    {
55
        return new SimpleXMLElement($this->rootNode);
56
    }
57
58
    /**
59
     * @inheritDoc
60
     */
61
    public function render(ViewInterface $view): string
62
    {
63
        $view->viewVars();
64
        $xml = $this->getSimpleXmlElement();
65
66
        $this->arrayToXml($view->viewVars(), $xml);
67
68
        return $xml->asXML();
69
    }
70
71
    /**
72
     * Array to XML
73
     *
74
     * @return void
75
     */
76
    protected function arrayToXml(array $data, SimpleXMLElement &$xmlData): void
77
    {
78
        foreach ($data as $key => $value) {
79
            if (is_array($value)) {
80
                if (!is_numeric($key)) {
81
                    $subnode = $xmlData->addChild("$key");
82
                    $this->arrayToXml($value, $subnode);
83
                } else {
84
                    $this->arrayToXml($value, $xmlData);
85
                }
86
            } else {
87
                $xmlData->addChild("$key", "$value");
88
            }
89
        }
90
    }
91
}
92