Completed
Push — master ( dd0467...e12d2b )
by Dominik
02:01
created

ObjectNode::remove()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
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
     * @var boolean
19
     */
20
    protected $allowNoChildren;
21
22
    /**
23
     * @param string $name
24
     * @param boolean $allowNoChildren
25
     */
26
    public function __construct($name, $allowNoChildren = false)
27
    {
28
        $this->name = $name;
29
        $this->allowNoChildren = $allowNoChildren;
30
    }
31
32
    /**
33
     * @return string
34
     */
35
    public function getName()
36
    {
37
        return $this->name;
38
    }
39
40
    /**
41
     * @param NodeInterface $node
42
     * @return $this
43
     */
44
    public function add(NodeInterface $node)
45
    {
46
        if (isset($this->children[$node->getName()])) {
47
            throw new \InvalidArgumentException(sprintf('There is already a child with name: %s', $node->getName()));
48
        }
49
50
        $this->children[$node->getName()] = $node;
51
52
        return $this;
53
    }
54
55
    /**
56
     * @param NodeInterface $node
57
     * @return $this
58
     */
59
    public function remove(NodeInterface $node)
60
    {
61
        if (isset($this->children[$node->getName()])) {
62
            unset($this->children[$node->getName()]);
63
        }
64
65
        return $this;
66
    }
67
68
    /**
69
     * @return \stdClass|null
70
     */
71
    public function serialize()
72
    {
73
        $serialzedChildren = new \stdClass();
74
        $serialzedChildrenCount = 0;
75
        foreach ($this->children as $child) {
76
            if (null !== $serialzedChild = $child->serialize()) {
77
                $serialzedChildren->{$child->getName()} = $serialzedChild->{$child->getName()};
78
                $serialzedChildrenCount++;
79
            }
80
        }
81
82
        if (0 === $serialzedChildrenCount && !$this->allowNoChildren) {
83
            return null;
84
        }
85
86
        $serialized = new \stdClass();
87
        $serialized->{$this->getName()} = $serialzedChildren;
88
89
        return $serialized;
90
    }
91
}
92