Completed
Push — master ( 8b0a23...1e5206 )
by Dominik
01:59
created

ObjectNode::add()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 2 Features 1
Metric Value
c 7
b 2
f 1
dl 0
loc 12
rs 9.4285
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
3
namespace Saxulum\ElasticSearchQueryBuilder\Node;
4
5
class ObjectNode extends AbstractParentNode
6
{
7
    /**
8
     * @param string       $name
9
     * @param AbstractNode $node
10
     *
11
     * @return $this
12
     */
13
    public function add($name, AbstractNode $node)
14
    {
15
        if (isset($this->children[$name])) {
16
            throw new \InvalidArgumentException(sprintf('There is already a node with name %s!', $name));
17
        }
18
19
        $node->setParent($this);
20
21
        $this->children[$name] = $node;
22
23
        return $this;
24
    }
25
26
    /**
27
     * @return array
28
     */
29
    public function getAddDefault()
30
    {
31
        return new \stdClass();
32
    }
33
34
    /**
35
     * @return \stdClass|null
36
     */
37
    public function serialize()
38
    {
39
        $serialized = new \stdClass();
40
        foreach ($this->children as $name => $child) {
41
            if (null !== $serializedChild = $child->serialize()) {
42
                $serialized->$name = $serializedChild;
43
            } elseif ($child->allowAddDefault()) {
44
                $serialized->$name = $child->getAddDefault();
45
            }
46
        }
47
48
        if ([] === (array) $serialized) {
49
            return;
50
        }
51
52
        return $serialized;
53
    }
54
}
55