Completed
Push — master ( 52b305...ed76d4 )
by Guillermo A.
01:49
created

Xml::flatten()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Guillermoandrae\Highrise\Helpers;
4
5
use Guillermoandrae\Common\Collection;
6
use Guillermoandrae\Common\CollectionInterface;
7
use SimpleXMLElement;
8
9
final class Xml
10
{
11
    /**
12
     * Converts a one-dimensional associative array to an XML string using the
13
     * provided data.
14
     *
15
     * @param string $root  The name of the root element.
16
     * @param array $data  The XML data.
17
     * @return string
18
     */
19 3
    public static function toXml(string $root, array $data)
20
    {
21 3
        $body = sprintf('<%s>', $root);
22 3
        foreach ($data as $key => $value) {
23 3
            $body .= sprintf('<%s>%s</%s>', $key, $value, $key);
24
        }
25 3
        $body .= sprintf('</%s>', $root);
26 3
        return $body;
27
    }
28
29
    /**
30
     * Converts an XML string into either an associative array or an array of
31
     * associative arrays.
32
     *
33
     * @param string $xml The XML string.
34
     * @return array|CollectionInterface
35
     */
36 20
    public static function fromXml(string $xml)
37
    {
38 20
        libxml_use_internal_errors(true);
39 20
        if (!$obj = simplexml_load_string($xml)) {
40 1
            return [];
41
        }
42 19
        if ($obj->attributes()) {
43 12
            $items = [];
44 12
            foreach ($obj->children() as $child) {
45 12
                $items[] = static::flatten($child);
46
            }
47 12
            return Collection::make($items);
48
        }
49 7
        return (array) static::flatten($obj);
50
    }
51
52
    /**
53
     * Removes attributes from SimpleXMLElement objects.
54
     *
55
     * @param SimpleXMLElement $item The SimpleXMLElement object.
56
     * @return array
57
     */
58 19
    public static function flatten(SimpleXMLElement $item)
59
    {
60 19
        $parsedItem = [];
61 19
        foreach ($item as $key => $value) {
62 18
            $parsedItem[$key] = (string) $value;
63
        }
64 19
        return $parsedItem;
65
    }
66
}
67