DumpTrait::composeXML()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.7666
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
namespace Mhor\MediaInfo;
4
5
trait DumpTrait
6
{
7
    /**
8
     * Convert the object into json.
9
     *
10
     * @return array
11
     */
12 5
    public function jsonSerialize(): array
13
    {
14 5
        return get_object_vars($this);
15
    }
16
17
    /**
18
     * Dump object to array.
19
     *
20
     * @return array
21
     */
22 1
    public function __toArray(): array
23
    {
24 1
        return $this->jsonSerialize();
25
    }
26
27 2
    public function __toXML()
28
    {
29 2
        $components = explode('\\', get_class($this));
30 2
        $rootNode = end($components);
31 2
        $xml = new \SimpleXMLElement("<?xml version=\"1.0\"?><$rootNode></$rootNode>");
32 2
        $array = json_decode(json_encode($this), true);
33
34 2
        $this->composeXML($array, $xml);
35
36 2
        return $xml;
37
    }
38
39 2
    protected function composeXML($data, &$xml): void
40
    {
41 2
        foreach ($data as $key => $value) {
42 2
            if (is_array($value)) {
43 2
                if (is_numeric($key)) {
44 1
                    $key = 'item'.$key;
45
                }
46
47 2
                $subnode = $xml->addChild($key);
48 2
                $this->composeXML($value, $subnode);
49
            } else {
50 2
                $xml->addChild("$key", htmlspecialchars("$value"));
51
            }
52
        }
53 2
    }
54
}
55