Completed
Push — master ( 303994...b7dcca )
by Martin
02:06
created

MarshalXml::processNodes()   C

Complexity

Conditions 7
Paths 17

Size

Total Lines 36
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 22
cts 22
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 21
nc 17
nop 2
crap 7
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace KingsonDe\Marshal;
6
7
use KingsonDe\Marshal\Data\DataStructure;
8
9
/**
10
 * @method static string serializeItem(AbstractMapper $mapper, ...$data)
11
 * @method static string serializeItemCallable(callable $mappingFunction, ...$data)
12
 * @method static string serializeCollection(AbstractMapper $mapper, ...$data)
13
 * @method static string serializeCollectionCallable(callable $mappingFunction, ...$data)
14
 */
15
class MarshalXml extends Marshal {
16
17
    const ATTRIBUTES_KEY = '@attributes';
18
    const DATA_KEY       = '@data';
19
20
    /**
21
     * @var string
22
     */
23
    protected static $version = '1.0';
24
25
    /**
26
     * @var string
27
     */
28
    protected static $encoding = 'UTF-8';
29
30 1
    public static function setVersion(string $version) {
31 1
        static::$version = $version;
32 1
    }
33
34 1
    public static function setEncoding(string $encoding) {
35 1
        static::$encoding = $encoding;
36 1
    }
37
38
    /**
39
     * @param DataStructure $dataStructure
40
     * @return string
41
     */
42 5
    public static function serialize(DataStructure $dataStructure) {
43 5
        $data = static::buildDataStructure($dataStructure);
44 5
        $xml  = new \DOMDocument(static::$version, static::$encoding);
45
46 5
        if (null === $data) {
47 1
            $xmlRootNode = $xml->createElement('root');
48 1
            $xml->appendChild($xmlRootNode);
49
50 1
            return $xml->saveXML();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $xml->saveXML(); (string) is incompatible with the return type of the parent method KingsonDe\Marshal\Marshal::serialize of type null|array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
51
        }
52
53 4
        \reset($data);
54 4
        $rootNode = \key($data);
55
56 4
        if (isset($data[$rootNode][static::DATA_KEY])) {
57 1
            $xmlRootNode = $xml->createElement($rootNode, static::castValueToString($data[$rootNode][static::DATA_KEY]));
58 1
            unset($data[$rootNode][static::DATA_KEY]);
59
        } else {
60 3
            $xmlRootNode = $xml->createElement($rootNode);
61
        }
62
63 4
        if (isset($data[$rootNode][static::ATTRIBUTES_KEY])) {
64 3
            static::addAttributes($data[$rootNode][static::ATTRIBUTES_KEY], $xmlRootNode);
65 3
            unset($data[$rootNode][static::ATTRIBUTES_KEY]);
66
        }
67 4
        $xml->appendChild($xmlRootNode);
68
69 4
        static::processNodes($data[$rootNode], $xmlRootNode);
70
71 4
        return $xml->saveXML();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $xml->saveXML(); (string) is incompatible with the return type of the parent method KingsonDe\Marshal\Marshal::serialize of type null|array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
72
    }
73
74 4
    protected static function processNodes(array $nodes, \DOMElement $parentXmlNode) {
75 4
        foreach ($nodes as $node => $value) {
76 3
            $attributes = [];
77
78 3
            if (isset($value[static::ATTRIBUTES_KEY])) {
79 2
                $attributes = $value[static::ATTRIBUTES_KEY];
80 2
                unset($value[static::ATTRIBUTES_KEY]);
81
            }
82
83 3
            if (isset($value[static::DATA_KEY])) {
84 2
                $value = $value[static::DATA_KEY];
85
            }
86
87
            // new node with scalar value
88 3
            if (\is_scalar($value)) {
89 2
                $xmlNode = $parentXmlNode->ownerDocument->createElement($node, static::castValueToString($value));
90 2
                static::addAttributes($attributes, $xmlNode);
91 2
                $parentXmlNode->appendChild($xmlNode);
92 2
                continue;
93
            }
94
95
            // node collection of the same type
96 2
            if (\is_int($node)) {
97 2
                static::processNodes($value, $parentXmlNode);
98 2
                continue;
99
            }
100
101
            // new node that might contain other nodes
102 2
            $xmlNode = $parentXmlNode->ownerDocument->createElement($node);
103 2
            static::addAttributes($attributes, $xmlNode);
104 2
            $parentXmlNode->appendChild($xmlNode);
105 2
            if (\is_array($value)) {
106 2
                static::processNodes($value, $xmlNode);
107
            }
108
        }
109 4
    }
110
111 4
    protected static function addAttributes(array $attributes, \DOMElement $xmlNode) {
112 4
        foreach ($attributes as $name => $value) {
113 3
            $xmlNode->setAttribute($name, static::castValueToString($value));
114
        }
115 4
    }
116
117 4
    protected static function castValueToString($value): string {
118 4
        return (\is_string($value) ? $value : var_export($value, true));
119
    }
120
}
121