1
|
|
|
<?php |
2
|
|
|
namespace SimpleMath; |
3
|
|
|
|
4
|
|
|
abstract class TerminalExpression { |
5
|
|
|
|
6
|
|
|
protected $value = ''; |
7
|
|
|
protected $precidence = 0; |
8
|
|
|
protected $leftAssoc = true; |
9
|
|
|
|
10
|
|
|
public function __construct($value) { |
11
|
|
|
$this->value = $value; |
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
public function getPrecidence() { |
15
|
|
|
return $this->precidence; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function isLeftAssoc() { |
19
|
|
|
return $this->leftAssoc; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function isOpen() { |
23
|
|
|
return false; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public static function factory($value) { |
27
|
|
|
if (is_object($value) && $value instanceof TerminalExpression) { |
28
|
|
|
return $value; |
29
|
|
|
} elseif (is_numeric($value)) { |
30
|
|
|
return new Number($value); |
31
|
|
|
} elseif (preg_match('/^\$?[a-z]+$/', $value)) { |
32
|
|
|
return new Variable($value); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
switch ($value) { |
36
|
|
|
case '+': |
37
|
|
|
return new Addition($value); |
38
|
|
|
case '-': |
39
|
|
|
return new Subtraction($value); |
40
|
|
|
case '*': |
41
|
|
|
return new Multiplication($value); |
42
|
|
|
case '/': |
43
|
|
|
return new Division($value); |
44
|
|
|
case '%': |
45
|
|
|
return new Modulo($value); |
46
|
|
|
case '?': |
47
|
|
|
case ':': |
48
|
|
|
return new Ternary($value); |
49
|
|
|
case '(': |
50
|
|
|
case ')': |
51
|
|
|
return new Parenthesis($value); |
52
|
|
|
case '==': |
53
|
|
|
return new ComparisonEQ($value); |
54
|
|
|
case '<': |
55
|
|
|
return new ComparisonLT($value); |
56
|
|
|
case '>': |
57
|
|
|
return new ComparisonGT($value); |
58
|
|
|
case '<=': |
59
|
|
|
return new ComparisonLTE($value); |
60
|
|
|
case '>=': |
61
|
|
|
return new ComparisonGTE($value); |
62
|
|
|
case '!=': |
63
|
|
|
return new ComparisonNE($value); |
64
|
|
|
case '||': |
65
|
|
|
return new OperatorOr($value); |
66
|
|
|
case '&&': |
67
|
|
|
return new OperatorAnd($value); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
throw new \Exception('Undefined Value ' . $value); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
abstract public function operate(Stack $stack, $variables=array()); |
74
|
|
|
|
75
|
|
|
public function isOperator() { |
76
|
|
|
return false; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
public function isParenthesis() { |
80
|
|
|
return false; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function render() { |
84
|
|
|
return $this->value; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|