|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace LegalThings\DataEnricher\Processor; |
|
4
|
|
|
|
|
5
|
|
|
use LegalThings\DataEnricher\Node; |
|
6
|
|
|
use LegalThings\DataEnricher\Processor; |
|
7
|
|
|
use Hoa; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Description of Math |
|
11
|
|
|
* |
|
12
|
|
|
* @author arnold |
|
13
|
|
|
*/ |
|
14
|
|
|
class Math implements Processor |
|
15
|
|
|
{ |
|
16
|
|
|
use Processor\Implementation; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var Hoa\Compiler\Llk\Parser |
|
20
|
|
|
*/ |
|
21
|
|
|
protected static $parser; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Create a parser for arithmitic expressions |
|
25
|
|
|
* |
|
26
|
|
|
* @return Hoa\Compiler\Llk\Parser |
|
27
|
|
|
*/ |
|
28
|
6 |
|
protected function getParser() |
|
29
|
|
|
{ |
|
30
|
6 |
|
if (!isset(static::$parser)) { |
|
31
|
1 |
|
static::$parser = Hoa\Compiler\Llk\Llk::load( |
|
32
|
1 |
|
new Hoa\File\Read('hoa://Library/Math/Arithmetic.pp') |
|
33
|
1 |
|
); |
|
34
|
1 |
|
} |
|
35
|
|
|
|
|
36
|
6 |
|
return static::$parser; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Apply processing to a single node |
|
41
|
|
|
* |
|
42
|
|
|
* @param Node $node |
|
43
|
|
|
*/ |
|
44
|
6 |
|
public function applyToNode(Node $node) |
|
45
|
|
|
{ |
|
46
|
6 |
|
$expression = $node->getInstruction($this); |
|
47
|
6 |
|
$ast = $this->getParser()->parse($expression); |
|
48
|
|
|
|
|
49
|
5 |
|
$variables = $node->getResult() ?: []; |
|
50
|
5 |
|
$arithmetic = new Hoa\Math\Visitor\Arithmetic(); |
|
51
|
|
|
|
|
52
|
5 |
|
foreach ($variables as $name => $value) { |
|
53
|
|
|
// Constants are upper case and variables lower case. We don't really care, so using a workaround. |
|
54
|
2 |
|
if (preg_match('/^[A-Z_][A-Z0-9_]*$/', $name)) { |
|
55
|
1 |
|
$arithmetic->addConstant($name, $value); |
|
56
|
1 |
|
} else { |
|
57
|
|
|
$arithmetic->addVariable($name, function() use ($value) { return $value; }); |
|
58
|
|
|
} |
|
59
|
5 |
|
} |
|
60
|
|
|
|
|
61
|
5 |
|
$result = $arithmetic->visit($ast); |
|
62
|
|
|
|
|
63
|
4 |
|
$node->setResult($result); |
|
64
|
4 |
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|