Completed
Branch master (9de2b1)
by Dominik
03:28 queued 01:13
created

ObjectNode::getDefault()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
nc 1
cc 1
eloc 2
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, $allowDefault = false)
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
        $this->allowDefault[$name] = $allowDefault;
23
24
        return $this;
25
    }
26
27
    /**
28
     * @return array
29
     */
30
    public function getDefault()
31
    {
32
        return new \stdClass();
33
    }
34
35
    /**
36
     * @return \stdClass|null
37
     */
38
    public function serialize()
39
    {
40
        $serialized = new \stdClass();
41
        foreach ($this->children as $name => $child) {
42
            if (null !== $serializedChild = $child->serialize()) {
43
                $serialized->$name = $serializedChild;
44
            } elseif ($this->allowDefault[$name]) {
45
                $serialized->$name = $child->getDefault();
46
            }
47
        }
48
49
        if ([] === (array) $serialized) {
50
            return;
51
        }
52
53
        return $serialized;
54
    }
55
}
56