Completed
Push — master ( 4e71b2...dd0467 )
by Dominik
01:55
created

ObjectNode::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Saxulum\ElasticSearchQueryBuilder\Node;
4
5
class ObjectNode implements NodeInterface
6
{
7
    /**
8
     * @var string
9
     */
10
    protected $name;
11
12
    /**
13
     * @var NodeInterface[]|array
14
     */
15
    protected $children = [];
16
17
    /**
18
     * @param string $name
19
     */
20
    public function __construct($name)
21
    {
22
        $this->name = $name;
23
    }
24
25
    /**
26
     * @return string
27
     */
28
    public function getName()
29
    {
30
        return $this->name;
31
    }
32
33
    /**
34
     * @param NodeInterface $node
35
     * @return $this
36
     */
37
    public function add(NodeInterface $node)
38
    {
39
        if (isset($this->children[$node->getName()])) {
40
            throw new \InvalidArgumentException(sprintf('There is already a child with name: %s', $node->getName()));
41
        }
42
        
43
        $this->children[$node->getName()] = $node;
44
        
45
        return $this;
46
    }
47
48
    /**
49
     * @param NodeInterface $node
50
     * @return $this
51
     */
52
    public function remove(NodeInterface $node)
53
    {
54
        if (isset($this->children[$node->getName()])) {
55
            unset($this->children[$node->getName()]);
56
        }
57
        
58
        return $this;
59
    }
60
61
    /**
62
     * @return \stdClass
63
     */
64
    public function serialize()
65
    {
66
        $serialzedChildren = new \stdClass();
67
        foreach ($this->children as $child) {
68
            $serialzedChildren->{$child->getName()} = $child->serialize()->{$child->getName()};
69
        }
70
        
71
        $serialized = new \stdClass();
72
        $serialized->{$this->getName()} = $serialzedChildren;
73
        
74
        return $serialized;
75
    }
76
}
77