Completed
Branch master (343030)
by Dominik
05:26 queued 02:33
created

ObjectNode::serializeChild()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 5
nc 3
nop 3
crap 3
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 5
    public function add($name, AbstractNode $node, $allowDefault = false)
14
    {
15 5
        if (isset($this->children[$name])) {
16 1
            throw new \InvalidArgumentException(sprintf('There is already a node with name %s!', $name));
17
        }
18
19 5
        $node->setParent($this);
20
21 5
        $this->children[$name] = $node;
22 5
        $this->allowDefault[$name] = $allowDefault;
23
24 5
        return $this;
25
    }
26
27
    /**
28
     * @return array
29
     */
30 1
    public function getDefault()
31
    {
32 1
        return new \stdClass();
33
    }
34
35
    /**
36
     * @return \stdClass|null
37
     */
38 4
    public function serialize()
39
    {
40 4
        $serialized = new \stdClass();
41 4
        foreach ($this->children as $name => $child) {
42 3
            $this->serializeChild($serialized, $name, $child);
43 4
        }
44
45 4
        if ([] === (array) $serialized) {
46 2
            return;
47
        }
48
49 2
        return $serialized;
50
    }
51
52
    /**
53
     * @param \stdClass    $serialized
54
     * @param string       $name
55
     * @param AbstractNode $child
56
     */
57 3
    private function serializeChild(\stdClass $serialized, $name, AbstractNode $child)
58
    {
59 3
        if (null !== $serializedChild = $child->serialize()) {
60 1
            $serialized->$name = $serializedChild;
61 3
        } elseif ($this->allowDefault[$name]) {
62 1
            $serialized->$name = $child->getDefault();
63 1
        }
64 3
    }
65
}
66