Passed
Pull Request — master (#73)
by Dmitriy
13:17
created

XmlResponseFormatter::format()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 19
rs 9.7998
cc 3
nc 3
nop 1
1
<?php
2
3
namespace App;
4
5
use DOMDocument;
6
use DOMElement;
7
use DOMException;
8
use DOMText;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\StreamFactoryInterface;
11
use Yiisoft\Strings\StringHelper;
12
13
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. If not set, it will use the value of [[Response::charset]].
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
    private StreamFactoryInterface $streamFactory;
46
47
    public function __construct(StreamFactoryInterface $streamFactory)
48
    {
49
        $this->streamFactory = $streamFactory;
50
    }
51
52
    public function format(DeferredResponse $response): ResponseInterface
53
    {
54
        $content = '';
55
        $data = $response->getData();
56
        if ($data !== null) {
57
            $dom = new DOMDocument($this->version, $this->encoding);
58
            if (!empty($this->rootTag)) {
59
                $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

59
                $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...
60
                $dom->appendChild($root);
61
                $this->buildXml($root, $data);
62
            } else {
63
                $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 App\XmlResponseFormatter::buildXml(). ( Ignorable by Annotation )

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

63
                $this->buildXml(/** @scrutinizer ignore-type */ $dom, $data);
Loading history...
64
            }
65
            $content = $dom->saveXML();
66
        }
67
        $response = $response->getResponse();
68
        $response->getBody()->write($content);
69
70
        return $response->withHeader('Content-Type', $this->contentType . ';' . $this->encoding);
71
    }
72
73
    /**
74
     * @param DOMElement $element
75
     * @param mixed $data
76
     */
77
    protected function buildXml($element, $data): void
78
    {
79
        if (is_array($data) ||
80
            ($data instanceof \Traversable && $this->useTraversableAsArray)
81
        ) {
82
            foreach ($data as $name => $value) {
83
                if (is_int($name) && is_object($value)) {
84
                    $this->buildXml($element, $value);
85
                } elseif (is_array($value) || is_object($value)) {
86
                    $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

86
                    $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...
87
                    $element->appendChild($child);
88
                    $this->buildXml($child, $value);
89
                } else {
90
                    $child = new DOMElement($this->getValidXmlElementName($name));
91
                    $element->appendChild($child);
92
                    $child->appendChild(new DOMText($this->formatScalarValue($value)));
93
                }
94
            }
95
        } elseif (is_object($data)) {
96
            if ($this->useObjectTags) {
97
                $child = new DOMElement(StringHelper::basename(get_class($data)));
98
                $element->appendChild($child);
99
            } else {
100
                $child = $element;
101
            }
102
            $array = [];
103
            foreach ($data as $name => $value) {
104
                $array[$name] = $value;
105
            }
106
            $this->buildXml($child, $array);
107
        } else {
108
            $element->appendChild(new DOMText($this->formatScalarValue($data)));
109
        }
110
    }
111
112
    /**
113
     * Formats scalar value to use in XML text node.
114
     *
115
     * @param int|string|bool|float $value a scalar value.
116
     * @return string string representation of the value.
117
     */
118
    protected function formatScalarValue($value): string
119
    {
120
        if ($value === true) {
121
            return 'true';
122
        }
123
        if ($value === false) {
124
            return 'false';
125
        }
126
        if (is_float($value)) {
127
            return StringHelper::floatToString($value);
128
        }
129
        return (string) $value;
130
    }
131
132
    /**
133
     * Returns element name ready to be used in DOMElement if
134
     * name is not empty, is not int and is valid.
135
     *
136
     * Falls back to [[itemTag]] otherwise.
137
     *
138
     * @param mixed $name
139
     * @return string
140
     */
141
    protected function getValidXmlElementName($name): string
142
    {
143
        if (empty($name) || is_int($name) || !$this->isValidXmlName($name)) {
144
            return $this->itemTag;
145
        }
146
147
        return $name;
148
    }
149
150
    /**
151
     * Checks if name is valid to be used in XML.
152
     *
153
     * @param mixed $name
154
     * @return bool
155
     * @see http://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name/2519943#2519943
156
     */
157
    protected function isValidXmlName($name): bool
158
    {
159
        try {
160
            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

160
            /** @scrutinizer ignore-call */ 
161
            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...
161
            return true;
162
        } catch (DOMException $e) {
163
            return false;
164
        }
165
    }
166
}
167