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

ArrayNode   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 4
Bugs 0 Features 2
Metric Value
wmc 11
c 4
b 0
f 2
lcom 1
cbo 0
dl 0
loc 87
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getName() 0 4 1
A add() 0 10 2
A remove() 0 8 2
B serialize() 0 20 5
1
<?php
2
3
namespace Saxulum\ElasticSearchQueryBuilder\Node;
4
5
class ArrayNode 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 (false !== $index = array_search($node, $this->children, true)) {
47
            throw new \InvalidArgumentException(sprintf('Child already added index: %d', $index));
48
        }
49
50
        $this->children[] = $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 (false !== $index = array_search($node, $this->children, true)) {
62
            unset($this->children[$index]);
63
        }
64
65
        return $this;
66
    }
67
68
    /**
69
     * @return \stdClass|null
70
     */
71
    public function serialize()
72
    {
73
        $serialzedChildren = [];
74
        $serialzedChildrenCount = 0;
75
        foreach ($this->children as $child) {
76
            if (null !== $serialzedChild = $child->serialize()) {
77
                $serialzedChildren[] = $serialzedChild;
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