Passed
Push — master ( 766df6...286284 )
by Roman
55s
created

Evaluator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 4

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getRootFrame() 0 7 1
A evaluate() 0 12 1
A __invoke() 0 4 1
A getModule() 0 7 2
1
<?php
2
3
namespace PeacefulBit\Slate\Core;
4
5
use PeacefulBit\Slate\Exceptions\EvaluatorException;
6
use PeacefulBit\Slate\Parser\Parser;
7
use PeacefulBit\Slate\Parser\Tokenizer;
8
9
class Evaluator
10
{
11
    /**
12
     * @var array
13
     */
14
    private $modules;
15
16
    /**
17
     * @param array $modules
18
     */
19
    public function __construct(array $modules = [])
20
    {
21
        $this->modules = $modules;
22
    }
23
24
    /**
25
     * Initialize and return root frame.
26
     * @return Frame
27
     */
28
    private function getRootFrame()
29
    {
30
        $frame = new Frame($this);
31
        $frame->importModule('@');
32
33
        return $frame;
34
    }
35
36
    /**
37
     * @param string $code
38
     * @return mixed
39
     */
40
    public function evaluate(string $code)
41
    {
42
        $tokenizer = new Tokenizer();
43
        $tokens = $tokenizer->tokenize($code);
44
45
        $parser = new Parser();
46
        $ast = $parser->parse($tokens);
47
48
        $frame = $this->getRootFrame();
49
50
        return $frame->valueOf($ast);
51
    }
52
53
    /**
54
     * @param string $code
55
     * @return mixed
56
     */
57
    public function __invoke(string $code)
58
    {
59
        return $this->evaluate($code);
60
    }
61
62
    /**
63
     * @param $name
64
     * @return mixed
65
     * @throws EvaluatorException
66
     */
67
    public function getModule($name)
68
    {
69
        if (!array_key_exists($name, $this->modules)) {
70
            throw new EvaluatorException("Module \"$name\" does not exist");
71
        }
72
        return $this->modules[$name];
73
    }
74
}
75