Passed
Push — master ( cb463c...b11a9d )
by Jesse
01:56
created

DefaultXmlFormatter::from()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 10
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 14
rs 9.9332
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\RestResource;
4
5
use SimpleXMLElement;
6
use function htmlspecialchars;
7
use function is_array;
8
use function is_numeric;
9
use function str_replace;
10
use const ENT_XML1;
11
12
final class DefaultXmlFormatter extends XmlFormatter
13
{
14
    protected function toSimpleXML(
15
        array $input,
16
        SimpleXMLElement $parent,
17
        bool $alreadySingularized = false
18
    ): void {
19
        foreach ($input as $key => $value) {
20
21
            if (is_numeric($key)) {
22
                $name = $alreadySingularized ?
23
                    'item' : $this->singularizer->convert($parent->getName());
24
                $singularized = true;
25
            } else {
26
                $name = str_replace(['<', '>'], '', (string) $key);
27
                $singularized = false;
28
            }
29
30
            if (is_array($value)) {
31
                $node = $parent->addChild($name);
32
                $this->toSimpleXML($value, $node, $singularized);
33
            } else {
34
                $parent->addChild(
35
                    $name,
36
                    htmlspecialchars((string) $value, ENT_XML1)
37
                );
38
            }
39
40
        }
41
    }
42
}
43