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

DumpTrait::jsonSerialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 10
loc 10
ccs 4
cts 6
cp 0.6667
rs 9.4285
cc 2
eloc 5
nc 2
nop 0
crap 2.1481
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