Completed
Branch master (d78aad)
by Dominik
04:36 queued 02:12
created

ScalarToNodeConverter::convert()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 9

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.2
c 0
b 0
f 0
cc 4
eloc 9
nc 3
nop 2
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
     *
30
     * @return AbstractNode
31
     *
32
     * @throws \InvalidArgumentException
33
     */
34 6
    public function convert($value, string $path = ''): AbstractNode
35
    {
36 6
        if (null === $value) {
37 1
            return NullNode::create();
38
        }
39
40 5
        $type = gettype($value);
41
42 5
        if (!isset($this->typeMapping[$type])) {
43 1
            throw new \InvalidArgumentException(
44 1
                sprintf('Type %s is not supported, at path %s', is_object($value) ? get_class($value) : $type, $path)
45
            );
46
        }
47
48 4
        $node = $this->typeMapping[$type];
49
50 4
        return $node::create($value);
51
    }
52
}
53