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

DumpTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 17.86 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 0
cbo 0
dl 10
loc 56
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A jsonSerialize() 10 10 2
A __toArray() 0 4 1
A __toXML() 0 11 1
A composeXML() 0 15 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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