Passed
Push — master ( 4a3e7e...eed543 )
by Guillermo A.
01:38
created

Xml::parse()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
ccs 10
cts 10
cp 1
crap 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A Xml::toXml() 0 8 2
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 14
     */
19
    public static function toXml(string $root, array $data)
20 14
    {
21 14
        $body = sprintf('<%s>', $root);
22 1
        foreach ($data as $key => $value) {
23
            $body .= sprintf('<%s>%s</%s>', $key, $value, $key);
24 13
        }
25 6
        $body .= sprintf('</%s>', $root);
26 6
        return $body;
27 6
    }
28
29 6
    /**
30
     * Converts an XML string into either an associative array or an array of
31 7
     * associative arrays.
32
     *
33
     * @param string $xml The XML string.
34
     * @return array|CollectionInterface
35
     */
36
    public static function fromXml(string $xml)
37
    {
38
        libxml_use_internal_errors(true);
39
        if (!$obj = simplexml_load_string($xml)) {
40 13
            return [];
41
        }
42 13
        if ($obj->attributes()) {
43 13
            $items = [];
44 12
            foreach ($obj->children() as $child) {
45
                $items[] = static::flatten($child);
46 13
            }
47
            return Collection::make($items);
48
        }
49
        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
    public static function flatten(SimpleXMLElement $item)
59
    {
60
        $parsedItem = [];
61
        foreach ($item as $key => $value) {
62
            $parsedItem[$key] = (string) $value;
63
        }
64
        return $parsedItem;
65
    }
66
}
67