Completed
Push — master ( 42b27a...b5bf54 )
by Martin
01:41
created

MarshalXml::serializeCollectionCallable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace KingsonDe\Marshal;
6
7
use KingsonDe\Marshal\Data\Collection;
8
use KingsonDe\Marshal\Data\CollectionCallable;
9
use KingsonDe\Marshal\Data\DataStructure;
10
use KingsonDe\Marshal\Exception\XmlSerializeException;
11
12
/**
13
 * @method static string serializeItem(AbstractMapper $mapper, ...$data)
14
 * @method static string serializeItemCallable(callable $mappingFunction, ...$data)
15
 */
16
class MarshalXml extends Marshal {
17
18
    const ATTRIBUTES_KEY = '@attributes';
19
    const DATA_KEY       = '@data';
20
21
    /**
22
     * @var string
23
     */
24
    protected static $version = '1.0';
25
26
    /**
27
     * @var string
28
     */
29
    protected static $encoding = 'UTF-8';
30
31 1
    public static function setVersion(string $version) {
32 1
        static::$version = $version;
33 1
    }
34
35 1
    public static function setEncoding(string $encoding) {
36 1
        static::$encoding = $encoding;
37 1
    }
38
39
    /**
40
     * @param DataStructure $dataStructure
41
     * @return string
42
     * @throws \KingsonDe\Marshal\Exception\XmlSerializeException
43
     */
44 7
    public static function serialize(DataStructure $dataStructure) {
45 7
        if ($dataStructure instanceof Collection || $dataStructure instanceof CollectionCallable) {
46 1
            throw new XmlSerializeException('Collections in XML cannot be generated at root level.');
47
        }
48
49 6
        $data = static::buildDataStructure($dataStructure);
50
51
        try {
52 6
            $xml  = new \DOMDocument(static::$version, static::$encoding);
53
54 6
            if (null === $data) {
55 1
                $xmlRootNode = $xml->createElement('root');
56 1
                $xml->appendChild($xmlRootNode);
57
58 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...
59
            }
60
61 5
            \reset($data);
62 5
            $rootNode = \key($data);
63
64 5
            if (isset($data[$rootNode][static::DATA_KEY])) {
65 1
                $xmlRootNode = $xml->createElement($rootNode, static::castValueToString($data[$rootNode][static::DATA_KEY]));
66 1
                unset($data[$rootNode][static::DATA_KEY]);
67
            } else {
68 4
                $xmlRootNode = $xml->createElement($rootNode);
69
            }
70
71 5
            if (isset($data[$rootNode][static::ATTRIBUTES_KEY])) {
72 3
                static::addAttributes($data[$rootNode][static::ATTRIBUTES_KEY], $xmlRootNode);
73 3
                unset($data[$rootNode][static::ATTRIBUTES_KEY]);
74
            }
75 5
            $xml->appendChild($xmlRootNode);
76
77 5
            static::processNodes($data[$rootNode], $xmlRootNode);
78
79 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...
80 1
        } catch (\Exception $e) {
81 1
            throw new XmlSerializeException($e->getMessage(), $e->getCode(), $e);
82
        }
83
    }
84
85 1
    public static function serializeCollection(AbstractMapper $mapper, ...$data) {
86 1
        throw new XmlSerializeException('Collections in XML cannot be generated at root level.');
87
    }
88
89 1
    public static function serializeCollectionCallable(callable $mappingFunction, ...$data) {
90 1
        throw new XmlSerializeException('Collections in XML cannot be generated at root level.');
91
    }
92
93 5
    protected static function processNodes(array $nodes, \DOMElement $parentXmlNode) {
94 5
        foreach ($nodes as $node => $value) {
95 4
            $attributes = [];
96
97 4
            if (isset($value[static::ATTRIBUTES_KEY])) {
98 2
                $attributes = $value[static::ATTRIBUTES_KEY];
99 2
                unset($value[static::ATTRIBUTES_KEY]);
100
            }
101
102 4
            if (isset($value[static::DATA_KEY])) {
103 2
                $value = $value[static::DATA_KEY];
104
            }
105
106
            // new node with scalar value
107 4
            if (\is_scalar($value)) {
108 3
                $xmlNode = $parentXmlNode->ownerDocument->createElement($node, static::castValueToString($value));
109 2
                static::addAttributes($attributes, $xmlNode);
110 2
                $parentXmlNode->appendChild($xmlNode);
111 2
                continue;
112
            }
113
114
            // node collection of the same type
115 2
            if (\is_int($node)) {
116 2
                static::processNodes($value, $parentXmlNode);
117 2
                continue;
118
            }
119
120
            // new node that might contain other nodes
121 2
            $xmlNode = $parentXmlNode->ownerDocument->createElement($node);
122 2
            static::addAttributes($attributes, $xmlNode);
123 2
            $parentXmlNode->appendChild($xmlNode);
124 2
            if (\is_array($value)) {
125 2
                static::processNodes($value, $xmlNode);
126
            }
127
        }
128 4
    }
129
130 4
    protected static function addAttributes(array $attributes, \DOMElement $xmlNode) {
131 4
        foreach ($attributes as $name => $value) {
132 3
            $xmlNode->setAttribute($name, static::castValueToString($value));
133
        }
134 4
    }
135
136 5
    protected static function castValueToString($value): string {
137 5
        return (\is_string($value) ? $value : var_export($value, true));
138
    }
139
}
140