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

ObjectNode::serialize()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 12
Bugs 2 Features 1
Metric Value
c 12
b 2
f 1
dl 0
loc 17
rs 8.8571
cc 5
eloc 10
nc 8
nop 0
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