Completed
Push — master ( f908b5...38f4f8 )
by Maxime
02:16
created

DumpTrait::composeXML()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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