Passed
Push — master ( 260da8...1d802a )
by Guillermo A.
01:55
created

Xml   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 10
c 0
b 0
f 0
ccs 15
cts 15
cp 1
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A flatten() 0 7 2
A parse() 0 14 4
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 an XML string into either an associative array or an array of
13
     * associative arrays.
14
     *
15
     * @param string $xml The XML string.
16
     * @return array|CollectionInterface
17
     */
18 14
    public static function parse(string $xml)
19
    {
20 14
        libxml_use_internal_errors(true);
21 14
        if (!$obj = simplexml_load_string($xml)) {
22 1
            return [];
23
        }
24 13
        if ($obj->attributes()) {
25 6
            $items = [];
26 6
            foreach ($obj->children() as $child) {
27 6
                $items[] = static::flatten($child);
28
            }
29 6
            return Collection::make($items);
30
        }
31 7
        return (array) static::flatten($obj);
32
    }
33
34
    /**
35
     * Removes attributes from SimpleXMLElement objects.
36
     *
37
     * @param SimpleXMLElement $item The SimpleXMLElement object.
38
     * @return array
39
     */
40 13
    public static function flatten(SimpleXMLElement $item)
41
    {
42 13
        $parsedItem = [];
43 13
        foreach ($item as $key => $value) {
44 12
            $parsedItem[$key] = (string) $value;
45
        }
46 13
        return $parsedItem;
47
    }
48
}
49