Test Failed
Pull Request — master (#101)
by Maxime
01:57
created

DumpTrait::__toXML()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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
                }
52
53 1
                $subnode = $xml->addChild($key);
54 1
                $this->composeXML($value, $subnode);
55
            } else {
56 2
                $xml->addChild("$key", htmlspecialchars("$value"));
57
            }
58
        }
59 2
    }
60
}
61