Completed
Push — master ( 8844e1...b4c347 )
by Christian
04:21 queued 02:03
created

XmlSerializer::toXml()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 13
rs 9.2
cc 4
eloc 9
nc 4
nop 2
1
<?php
2
3
namespace Ntb\RestAPI;
4
5
/**
6
 * Serializer for xml.
7
 * @author Christian Blank <[email protected]>
8
 */
9
class XmlSerializer extends \Object implements IRestSerializer {
10
11
    /**
12
     * @config
13
     */
14
    private static $is_active = true;
0 ignored issues
show
Unused Code introduced by
The property $is_active is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
15
    
16
    /**
17
     * The content type.
18
     * @var string
19
     */
20
    private $contentType = "application/xml";
21
22
    /**
23
     * Serializes the given data into a xml string.
24
     *
25
     * @param array $data the data that should be serialized
26
     * @return string a xml formatted string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
27
     */
28
    public function serialize($data) {
29
        $xml = new \SimpleXMLElement('<result/>');
30
        $this->toXml($xml, $data);
31
        return $xml->asXML();
32
    }
33
34
    public function contentType() {
35
        return $this->contentType;
36
    }
37
38
    private function toXml(\SimpleXMLElement $object, array $data) {
39
        foreach( $data as $key => $value ) {
40
            if(is_array($value) ) {
41
                if( is_numeric($key) ){
42
                    $key = 'item'.$key; //dealing with <0/>..<n/> issues
43
                }
44
                $subnode = $object->addChild($key);
45
                $this->toXml($subnode, $value);
46
            } else {
47
                $object->addChild("$key",htmlspecialchars("$value"));
48
            }
49
        }
50
    }
51
52
    /**
53
     * Indicates if the serializer is active.
54
     * Serializers can be deactivated to use another implementation for the same mime type.
55
     *
56
     * @return boolean
57
     */
58
    public function active() {
59
        return $this->config()->get('is_active');
60
    }
61
}
62