Completed
Pull Request — master (#45)
by Jose Manuel
02:24
created

AbstractItem::jsonSerialize()   A

Complexity

Conditions 6
Paths 5

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 5
nop 0
crap 6
1
<?php
2
3
namespace Softonic\GraphQL\DataObjects;
4
5
use JsonSerializable;
6
use Softonic\GraphQL\DataObjects\Mutation\FilteredCollection;
7
use Softonic\GraphQL\Traits\ItemIterator;
8
9
abstract class AbstractItem extends AbstractObject implements \Iterator
10
{
11
    use ItemIterator;
12
13 8
    public function has(string $key): bool
14
    {
15 8
        $keyPath  = explode('.', $key);
16 8
        $firstKey = array_shift($keyPath);
17
18 8
        if (!array_key_exists($firstKey, $this->arguments)) {
19 8
            return false;
20
        }
21
22 8
        if (empty($keyPath)) {
23 8
            return true;
24
        }
25
26 4
        $nextKey = implode('.', $keyPath);
27
28 4
        return $this->arguments[$firstKey]->has($nextKey);
29
    }
30
31 100
    public function __get(string $key)
32
    {
33 100
        return array_key_exists($key, $this->arguments) ? $this->arguments[$key] : null;
34
    }
35
36 34
    public function __set(string $key, $value): void
37
    {
38 34
        $this->arguments[$key] = $value;
39 34
    }
40
41 4
    public function equals(array $data): bool
42
    {
43 4
        return $data === $this->arguments;
44
    }
45
46 52
    public function jsonSerialize()
47
    {
48 52
        $item = [];
49 52
        foreach ($this->arguments as $key => $value) {
50 52
            if ($value instanceof FilteredCollection && !$value->hasChildren()) {
51 2
                continue;
52
            }
53
54 52
            if ($value instanceof JsonSerializable) {
0 ignored issues
show
Bug introduced by
The class JsonSerializable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
55 52
                if (!empty($valueSerialized = $value->jsonSerialize())) {
56 52
                    $item[$key] = $valueSerialized;
57
                }
58
            } else {
59 52
                $item[$key] = $value;
60
            }
61
        }
62
63 52
        return $item;
64
    }
65
}
66