Passed
Branch master (b4f9b9)
by Maxime
03:00
created

DumpTrait::composeXML()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 12
cts 12
cp 1
rs 9.2
cc 4
eloc 9
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 3 View Code Duplication
    public function jsonSerialize()
13
    {
14 3
        $array = get_object_vars($this);
15
16 3
        if (isset($array['attributes'])) {
17
            $array = $array['attributes'];
18
        }
19
20 3
        return $array;
21
    }
22
23
    /**
24
     * Dump object to array.
25
     *
26
     * @return array
27
     */
28 1
    public function __toArray()
29
    {
30 1
        return $this->jsonSerialize();
31
    }
32
33 2
    public function __toXML()
34
    {
35 2
        $components = explode('\\', get_class($this));
36 2
        $rootNode = end($components);
37 2
        $xml = new \SimpleXMLElement("<?xml version=\"1.0\"?><$rootNode></$rootNode>");
38 2
        $array = json_decode(json_encode($this), true);
39
40 2
        $this->composeXML($array, $xml);
41
42 2
        return $xml;
43
    }
44
45 2
    protected function composeXML($data, &$xml)
46
    {
47 2
        foreach ($data as $key => $value) {
48 2
            if (is_array($value)) {
49 1
                if (is_numeric($key)) {
50 1
                    $key = 'item'.$key;
51 1
                }
52
53 1
                $subnode = $xml->addChild($key);
54 1
                $this->composeXML($value, $subnode);
55 1
            } else {
56 2
                $xml->addChild("$key", htmlspecialchars("$value"));
57
            }
58 2
        }
59 2
    }
60
}
61