ExpressionParser   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 48
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setTypeMap() 0 3 1
A setType() 0 3 1
A parse() 0 17 3
1
<?php
2
/**
3
 * @author Aleksandar Panic
4
 * @license http://www.apache.org/licenses/LICENSE-2.0
5
 * @since 1.0.0
6
 **/
7
8
namespace ArekX\ArrayExpression;
9
10
use ArekX\ArrayExpression\Exceptions\TypeNotMappedException;
11
use \ArekX\ArrayExpression\Interfaces\ExpressionParser as ExpressionParserInterface;
12
use ArekX\ArrayExpression\Interfaces\Operator;
13
14
/**
15
 * Class ExpressionParser
16
 * Expression parser which converts array expressions into Operator instances.
17
 *
18
 * @package ArekX\ArrayExpression
19
 */
20
class ExpressionParser implements ExpressionParserInterface
21
{
22
    /**
23
     * Type map used to resolve types in arrays.
24
     * @var array
25
     */
26
    protected $typeMap = [];
27
28
    /**
29
     * @inheritDoc
30
     */
31 4
    public function setTypeMap(array $typeMap)
32
    {
33 4
        $this->typeMap = $typeMap;
34 4
    }
35
36
    /**
37
     * Sets a type resolver.
38
     *
39
     * @param string $type Type name
40
     * @param callable|string $resolver Callable resolver or a class which gets created.
41
     */
42 78
    public function setType(string $type, $resolver)
43
    {
44 78
        $this->typeMap[$type] = $resolver;
45 78
    }
46
47
    /**
48
     * @inheritDoc
49
     * @throws TypeNotMappedException
50
     */
51 43
    public function parse(array $expression)
52
    {
53 43
        if (empty($this->typeMap[$expression[0]])) {
54 1
            throw new TypeNotMappedException($expression[0]);
55
        }
56
57 42
        $resolver = $this->typeMap[$expression[0]];
58
59 42
        if (is_callable($resolver)) {
60 21
            return $resolver(...$expression);
61
        }
62
63
        /** @var Operator $resolver */
64 21
        $resolver = new $resolver();
65 21
        $resolver->setParser($this);
66 21
        $resolver->configure($expression);
67 21
        return $resolver;
68
    }
69
}