XmlSerializer::contentType()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Ntb\RestAPI;
4
5
/**
6
 * Serializer for xml.
7
 * @author Christian Blank <[email protected]>
8
 */
9
class XmlSerializer extends \SS_Object implements IRestSerializer {
10
11
    /**
12
     * @config
13
     */
14
    private static $is_active = true;
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