ScalarToNodeConverter::convert()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 9
cts 9
cp 1
rs 9.6666
c 0
b 0
f 0
cc 4
nc 3
nop 3
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Saxulum\ElasticSearchQueryBuilder\Converter;
6
7
use Saxulum\ElasticSearchQueryBuilder\Node\AbstractNode;
8
use Saxulum\ElasticSearchQueryBuilder\Node\BoolNode;
9
use Saxulum\ElasticSearchQueryBuilder\Node\FloatNode;
10
use Saxulum\ElasticSearchQueryBuilder\Node\IntNode;
11
use Saxulum\ElasticSearchQueryBuilder\Node\NullNode;
12
use Saxulum\ElasticSearchQueryBuilder\Node\StringNode;
13
14
final class ScalarToNodeConverter implements ScalarToNodeConverterInterface
15
{
16
    /**
17
     * @var array
18
     */
19
    private $typeMapping = [
20
        'boolean' => BoolNode::class,
21
        'double' => FloatNode::class,
22
        'integer' => IntNode::class,
23
        'string' => StringNode::class,
24
    ];
25
26
    /**
27
     * @param bool|float|int|null|string $value
28
     * @param string                     $path
29
     * @param bool                       $allowSerializeEmpty
30
     *
31
     * @return AbstractNode
32
     *
33
     * @throws \InvalidArgumentException
34
     */
35 8
    public function convert($value, string $path = '', bool $allowSerializeEmpty = false): AbstractNode
36
    {
37 8
        if (null === $value) {
38 1
            return NullNode::create();
39
        }
40
41 7
        $type = gettype($value);
42
43 7
        if (!isset($this->typeMapping[$type])) {
44 1
            throw new \InvalidArgumentException(
45 1
                sprintf('Type %s is not supported, at path %s', is_object($value) ? get_class($value) : $type, $path)
46
            );
47
        }
48
49 6
        $node = $this->typeMapping[$type];
50
51 6
        return $node::create($value, $allowSerializeEmpty);
52
    }
53
}
54