Passed
Push — master ( c7bb8d...42feb8 )
by Dominik
02:16
created

ObjectNode::serializeEmpty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Saxulum\ElasticSearchQueryBuilder\Node;
6
7
final class ObjectNode extends AbstractParentNode implements ObjectNodeSerializeInterface
8
{
9
    /**
10
     * @param bool $allowSerializeEmpty
11
     */
12 8
    public function __construct(bool $allowSerializeEmpty = false)
13
    {
14 8
        $this->allowSerializeEmpty = $allowSerializeEmpty;
15 8
    }
16
17
    /**
18
     * @param string       $key
19
     * @param AbstractNode $node
20
     *
21
     * @return $this
22
     *
23
     * @throws \InvalidArgumentException
24
     */
25 5
    public function add($key, AbstractNode $node)
26
    {
27 5
        if (isset($this->children[$key])) {
28 1
            throw new \InvalidArgumentException(sprintf('There is already a node with key %s!', $key));
29
        }
30
31 5
        $node->setParent($this);
32
33 5
        $this->children[$key] = $node;
34
35 5
        return $this;
36
    }
37
38
    /**
39
     * @return \stdClass
40
     */
41 1
    public function serializeEmpty(): \stdClass
42
    {
43 1
        return new \stdClass();
44
    }
45
46
    /**
47
     * @return \stdClass|null
48
     */
49 4 View Code Duplication
    public function serialize()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
50
    {
51 4
        $serialized = new \stdClass();
52 4
        foreach ($this->children as $key => $child) {
53 3
            $this->serializeChild($serialized, $key, $child);
54
        }
55
56 4
        if ([] === (array) $serialized) {
57 2
            return;
58
        }
59
60 2
        return $serialized;
61
    }
62
63
    /**
64
     * @param \stdClass         $serialized
65
     * @param string            $key
66
     * @param AbstractNode $child
67
     */
68 3
    private function serializeChild(\stdClass $serialized, string $key, AbstractNode $child)
69
    {
70 3
        if (null !== $serializedChild = $child->serialize()) {
71 1
            $serialized->$key = $serializedChild;
72 2
        } elseif ($child->isAllowSerializeEmpty()) {
73 1
            $serialized->$key = $child->serializeEmpty();
74
        }
75 3
    }
76
}
77