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

Evaluator::getModule()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
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