Completed
Pull Request — master (#29)
by
unknown
06:43
created

DataObjectBuilder::build()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 10
cts 10
cp 1
rs 9.0111
c 0
b 0
f 0
cc 6
nc 4
nop 1
crap 6
1
<?php
2
3
namespace Softonic\GraphQL;
4
5
use Softonic\GraphQL\Query\Collection;
6
use Softonic\GraphQL\Query\Item;
7
8
class DataObjectBuilder
9
{
10 14
    public function build(array $data): array
11
    {
12 14
        $dataObject = [];
13 14
        foreach ($data as $queryName => $objectsData) {
14 14
            if (is_array($objectsData) && !empty($objectsData)) {
15 10
                if ($this->isAList($objectsData)) {
16 2
                    foreach ($objectsData as $objectData) {
17 2
                        $dataObject[$queryName][] = $this->buildItem($objectData);
18
                    }
19
                } else {
20 10
                    $dataObject[$queryName] = $this->buildItem($objectsData);
21
                }
22
            } else {
23 4
                $dataObject[$queryName] = $objectsData;
24
            }
25
        }
26
27 14
        return $dataObject;
28
    }
29
30 10
    private function isAList(array $data): bool
31
    {
32 10
        return array_values($data) === $data;
33
    }
34
35 10
    private function buildItem(array $data): Item
36
    {
37 10
        $itemData = [];
38 10
        foreach ($data as $key => $value) {
39 10
            if (is_array($value)) {
40 6
                $items = [];
41 6
                foreach ($value as $valueItemData) {
42 4
                    $items[] = $this->buildItem($valueItemData);
43
                }
44
45 6
                $itemData[$key] = new Collection($items);
46
            } else {
47 10
                $itemData[$key] = $value;
48
            }
49
        }
50
51 10
        return new Item($itemData);
52
    }
53
}
54