Passed
Push — master ( 42feb8...1cd426 )
by Dominik
02:11
created

ObjectNode::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Saxulum\ElasticSearchQueryBuilder\Node;
6
7
final class ObjectNode extends AbstractParentNode implements ObjectNodeSerializeInterface
8
{
9
    /**
10
     * @param bool $allowSerializeEmpty
11
     * @return ObjectNode
12
     */
13 8
    public static function create(bool $allowSerializeEmpty = false): ObjectNode
14
    {
15 8
        $node = new self;
16 8
        $node->allowSerializeEmpty = $allowSerializeEmpty;
17
18 8
        return $node;
19
    }
20
21
    /**
22
     * @param string       $key
23
     * @param AbstractNode $node
24
     *
25
     * @return $this
26
     *
27
     * @throws \InvalidArgumentException
28
     */
29 5
    public function add($key, AbstractNode $node)
30
    {
31 5
        if (isset($this->children[$key])) {
32 1
            throw new \InvalidArgumentException(sprintf('There is already a node with key %s!', $key));
33
        }
34
35 5
        $node->setParent($this);
36
37 5
        $this->children[$key] = $node;
38
39 5
        return $this;
40
    }
41
42
    /**
43
     * @return \stdClass
44
     */
45 1
    public function serializeEmpty(): \stdClass
46
    {
47 1
        return new \stdClass();
48
    }
49
50
    /**
51
     * @return \stdClass|null
52
     */
53 4 View Code Duplication
    public function serialize()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
    {
55 4
        $serialized = new \stdClass();
56 4
        foreach ($this->children as $key => $child) {
57 3
            $this->serializeChild($serialized, $key, $child);
58
        }
59
60 4
        if ([] === (array) $serialized) {
61 2
            return;
62
        }
63
64 2
        return $serialized;
65
    }
66
67
    /**
68
     * @param \stdClass         $serialized
69
     * @param string            $key
70
     * @param AbstractNode $child
71
     */
72 3
    private function serializeChild(\stdClass $serialized, string $key, AbstractNode $child)
73
    {
74 3
        if (null !== $serializedChild = $child->serialize()) {
75 1
            $serialized->$key = $serializedChild;
76 2
        } elseif ($child->isAllowSerializeEmpty()) {
77 1
            $serialized->$key = $child->serializeEmpty();
78
        }
79 3
    }
80
}
81