Completed
Pull Request — master (#43)
by Jose Manuel
02:54
created

DataObjectBuilder::isAList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Softonic\GraphQL;
4
5
use Softonic\GraphQL\DataObjects\Mutation\Collection as MutationCollection;
6
use Softonic\GraphQL\DataObjects\Mutation\Item as MutationItem;
7
use Softonic\GraphQL\DataObjects\Query\Collection as QueryCollection;
8
use Softonic\GraphQL\DataObjects\Query\Item as QueryItem;
9
10
class DataObjectBuilder
11
{
12
    const ITEM = 'item';
13
14
    const COLLECTION = 'collection';
15
16
    const QUERY_OBJECTS = [
17
        self::ITEM       => QueryItem::class,
18
        self::COLLECTION => QueryCollection::class,
19
    ];
20
21
    const MUTATION_OBJECTS = [
22
        self::ITEM       => MutationItem::class,
23
        self::COLLECTION => MutationCollection::class,
24
    ];
25
26 16
    public function buildQuery(array $data): array
27
    {
28 16
        return $this->build($data, self::QUERY_OBJECTS);
29
    }
30
31 2
    public function buildMutation(array $data): array
32
    {
33 2
        return $this->build($data, self::MUTATION_OBJECTS);
34
    }
35
36 18
    private function build(array $data, array $objects): array
37
    {
38 18
        $dataObject = [];
39 18
        foreach ($data as $key => $value) {
40 18
            if (is_array($value)) {
41 16
                if ($this->isAList($value)) {
42 14
                    if (empty($value) || is_array($value[0])) {
43 12
                        $items = [];
44 12
                        foreach ($value as $objectData) {
45 8
                            $itemData = $this->build($objectData, $objects);
46 8
                            $items[]  = (new $objects[self::ITEM]($itemData));
47
                        }
48
49 12
                        $dataObject[$key] = (new $objects[self::COLLECTION]($items));
50
                    } else {
51 14
                        $dataObject[$key] = $value;
52
                    }
53
                } else {
54 12
                    $itemData         = $this->build($value, $objects);
55 16
                    $dataObject[$key] = (new $objects[self::ITEM]($itemData));
56
                }
57
            } else {
58 16
                $dataObject[$key] = $value;
59
            }
60
        }
61
62 18
        return $dataObject;
63
    }
64
65 16
    private function isAList(array $data): bool
66
    {
67 16
        return array_values($data) === $data;
68
    }
69
}
70