Xml   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 19
c 3
b 0
f 0
dl 0
loc 56
ccs 21
cts 21
cp 1
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A toXml() 0 8 2
A flatten() 0 7 2
A fromXml() 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 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 21
    public static function fromXml(string $xml)
37
    {
38 21
        libxml_use_internal_errors(true);
39 21
        if (!$obj = simplexml_load_string($xml)) {
40 1
            return [];
41
        }
42 20
        if ($obj->attributes()) {
43 13
            $items = [];
44 13
            foreach ($obj->children() as $child) {
45 13
                $items[] = static::flatten($child);
46
            }
47 13
            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 20
    public static function flatten(SimpleXMLElement $item)
59
    {
60 20
        $parsedItem = [];
61 20
        foreach ($item as $key => $value) {
62 19
            $parsedItem[$key] = (string) $value;
63
        }
64 20
        return $parsedItem;
65
    }
66
}
67