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

DumpTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 17.86 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 92.59%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 8
c 2
b 1
f 0
lcom 0
cbo 0
dl 10
loc 56
ccs 25
cts 27
cp 0.9259
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
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