Completed
Push — master ( efe7fa...260da8 )
by Guillermo A.
01:44
created

Xml   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 13
cts 14
cp 0.9286
rs 10
c 0
b 0
f 0
wmc 6

2 Methods

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