Passed
Pull Request — master (#233)
by Dmitriy
02:37
created

XmlResponseFormatter::setVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Yiisoft\Yii\Web\Formatter;
4
5
use DOMDocument;
6
use DOMElement;
7
use DOMException;
8
use DOMText;
9
use Psr\Http\Message\ResponseInterface;
10
use Yiisoft\Strings\StringHelper;
11
use Yiisoft\Yii\Web\WebResponse;
12
13
final class XmlResponseFormatter implements ResponseFormatterInterface
14
{
15
    /**
16
     * @var string the Content-Type header for the response
17
     */
18
    private string $contentType = 'application/xml';
19
    /**
20
     * @var string the XML version
21
     */
22
    private string $version = '1.0';
23
    /**
24
     * @var string the XML encoding.
25
     */
26
    private string $encoding = 'UTF-8';
27
    /**
28
     * @var string the name of the root element. If set to false, null or is empty then no root tag should be added.
29
     */
30
    private string $rootTag = 'response';
31
    /**
32
     * @var string the name of the elements that represent the array elements with numeric keys.
33
     */
34
    private string $itemTag = 'item';
35
    /**
36
     * @var bool whether to interpret objects implementing the [[\Traversable]] interface as arrays.
37
     * Defaults to `true`.
38
     */
39
    private bool $useTraversableAsArray = true;
40
    /**
41
     * @var bool if object tags should be added
42
     */
43
    private bool $useObjectTags = true;
44
45
    public function format(WebResponse $webResponse): ResponseInterface
46
    {
47
        $content = '';
48
        $data = $webResponse->getData();
49
        if ($data !== null) {
50
            $dom = new DOMDocument($this->version, $this->encoding);
51
            if (!empty($this->rootTag)) {
52
                $root = new DOMElement($this->rootTag);
0 ignored issues
show
Bug introduced by
The call to DOMElement::__construct() has too few arguments starting with value. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

52
                $root = /** @scrutinizer ignore-call */ new DOMElement($this->rootTag);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
53
                $dom->appendChild($root);
54
                $this->buildXml($root, $data);
55
            } else {
56
                $this->buildXml($dom, $data);
0 ignored issues
show
Bug introduced by
$dom of type DOMDocument is incompatible with the type DOMElement expected by parameter $element of Yiisoft\Yii\Web\Formatte...seFormatter::buildXml(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

56
                $this->buildXml(/** @scrutinizer ignore-type */ $dom, $data);
Loading history...
57
            }
58
            $content = $dom->saveXML();
59
        }
60
        $response = $webResponse->getResponse();
61
        $response->getBody()->write($content);
62
63
        return $response->withHeader('Content-Type', $this->contentType . '; ' . $this->encoding);
64
    }
65
66
    public function setVersion(string $version): void
67
    {
68
        $this->version = $version;
69
    }
70
71
    public function setEncoding(string $encoding): void
72
    {
73
        $this->encoding = $encoding;
74
    }
75
76
    public function setRootTag(string $rootTag): void
77
    {
78
        $this->rootTag = $rootTag;
79
    }
80
81
    public function setItemTag(string $itemTag): void
82
    {
83
        $this->itemTag = $itemTag;
84
    }
85
86
    public function setUseTraversableAsArray(bool $useTraversableAsArray): void
87
    {
88
        $this->useTraversableAsArray = $useTraversableAsArray;
89
    }
90
91
    public function setUseObjectTags(bool $useObjectTags): void
92
    {
93
        $this->useObjectTags = $useObjectTags;
94
    }
95
96
    public function setContentType(string $contentType):void
97
    {
98
        $this->contentType = $contentType;
99
    }
100
101
    /**
102
     * @param DOMElement $element
103
     * @param mixed $data
104
     */
105
    protected function buildXml($element, $data): void
106
    {
107
        if (is_array($data) ||
108
            ($data instanceof \Traversable && $this->useTraversableAsArray)
109
        ) {
110
            foreach ($data as $name => $value) {
111
                if (is_int($name) && is_object($value)) {
112
                    $this->buildXml($element, $value);
113
                } elseif (is_array($value) || is_object($value)) {
114
                    $child = new DOMElement($this->getValidXmlElementName($name));
0 ignored issues
show
Bug introduced by
The call to DOMElement::__construct() has too few arguments starting with value. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

114
                    $child = /** @scrutinizer ignore-call */ new DOMElement($this->getValidXmlElementName($name));

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
115
                    $element->appendChild($child);
116
                    $this->buildXml($child, $value);
117
                } else {
118
                    $child = new DOMElement($this->getValidXmlElementName($name));
119
                    $element->appendChild($child);
120
                    $child->appendChild(new DOMText($this->formatScalarValue($value)));
121
                }
122
            }
123
        } elseif (is_object($data)) {
124
            if ($this->useObjectTags) {
125
                $child = new DOMElement(StringHelper::basename(get_class($data)));
126
                $element->appendChild($child);
127
            } else {
128
                $child = $element;
129
            }
130
            $array = [];
131
            foreach ($data as $name => $value) {
132
                $array[$name] = $value;
133
            }
134
            $this->buildXml($child, $array);
135
        } else {
136
            $element->appendChild(new DOMText($this->formatScalarValue($data)));
137
        }
138
    }
139
140
    /**
141
     * Formats scalar value to use in XML text node.
142
     *
143
     * @param int|string|bool|float $value a scalar value.
144
     * @return string string representation of the value.
145
     */
146
    protected function formatScalarValue($value): string
147
    {
148
        if ($value === true) {
149
            return 'true';
150
        }
151
        if ($value === false) {
152
            return 'false';
153
        }
154
        if (is_float($value)) {
155
            return StringHelper::floatToString($value);
156
        }
157
        return (string)$value;
158
    }
159
160
    /**
161
     * Returns element name ready to be used in DOMElement if
162
     * name is not empty, is not int and is valid.
163
     *
164
     * Falls back to [[itemTag]] otherwise.
165
     *
166
     * @param mixed $name
167
     * @return string
168
     */
169
    protected function getValidXmlElementName($name): string
170
    {
171
        if (empty($name) || is_int($name) || !$this->isValidXmlName($name)) {
172
            return $this->itemTag;
173
        }
174
175
        return $name;
176
    }
177
178
    /**
179
     * Checks if name is valid to be used in XML.
180
     *
181
     * @param mixed $name
182
     * @return bool
183
     * @see http://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name/2519943#2519943
184
     */
185
    protected function isValidXmlName($name): bool
186
    {
187
        try {
188
            new DOMElement($name);
0 ignored issues
show
Bug introduced by
The call to DOMElement::__construct() has too few arguments starting with value. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

188
            /** @scrutinizer ignore-call */ 
189
            new DOMElement($name);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
189
            return true;
190
        } catch (DOMException $e) {
191
            return false;
192
        }
193
    }
194
}
195