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

CondensedXmlFormatter::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 is_array;
7
use function is_numeric;
8
use function str_replace;
9
10
final class CondensedXmlFormatter extends XmlFormatter
11
{
12
    protected function toSimpleXML(
13
        array $input,
14
        SimpleXMLElement $parent,
15
        bool $alreadySingularized = false
16
    ): void {
17
        foreach ($input as $key => $value) {
18
19
            if (is_numeric($key)) {
20
                $name = $alreadySingularized ?
21
                    'item' : $this->singularizer->convert($parent->getName());
22
                $singularized = true;
23
            } else {
24
                $name = str_replace(['<', '>'], '', (string) $key);
25
                $singularized = false;
26
            }
27
28
            if (is_array($value)) {
29
                $node = $parent->addChild($name);
30
                $this->toSimpleXML($value, $node, $singularized);
31
            } elseif ($singularized) {
32
                $child = $parent->addChild($name);
33
                $child->addAttribute('value', (string) $value);
34
            } else {
35
                $parent->addAttribute($name, (string) $value);
36
            }
37
38
        }
39
    }
40
}
41