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

DumpTrait::jsonSerialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 10
loc 10
ccs 4
cts 5
cp 0.8
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2.032
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