1 | <?php |
||
12 | class CalcOperation |
||
13 | { |
||
14 | |||
15 | static protected $operators = [ |
||
16 | '+' => 'add', |
||
17 | '*' => 'multiply', |
||
18 | '=' => 'equalto', |
||
19 | '<' => 'lessthan', |
||
20 | '>' => 'greaterthan', |
||
21 | '^' => 'exponent', |
||
22 | '/' => 'divide', |
||
23 | '-' => 'subtract', |
||
24 | ]; |
||
25 | |||
26 | /** |
||
27 | * @param string $operator |
||
28 | * @param $operand2 |
||
29 | * @param $operand1 |
||
30 | * |
||
31 | * @throws \Exception |
||
32 | * @return bool|number |
||
33 | */ |
||
34 | public static function calc($operator, $operand1, $operand2) |
||
35 | { |
||
36 | if(isset(static::$operators[$operator])) { |
||
37 | return call_user_func(array('self', static::$operators[$operator]), self::reduce($operand1), self::reduce($operand2)); |
||
38 | } |
||
39 | throw new \Exception('Unknown operator "' . $operator . '".'); |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * @param $operand |
||
44 | * |
||
45 | * @return number|string |
||
46 | * @throws \Exception |
||
47 | */ |
||
48 | public static function reduce($operand) |
||
58 | |||
59 | /** |
||
60 | * @param number $operand1 |
||
61 | * @param number $operand2 |
||
62 | * |
||
63 | * @return bool|number |
||
64 | */ |
||
65 | protected static function add($operand1, $operand2) |
||
69 | |||
70 | /** |
||
71 | * @param number $operand1 |
||
72 | * @param number $operand2 |
||
73 | * |
||
74 | * @return bool|number |
||
75 | */ |
||
76 | protected static function multiply($operand1, $operand2) |
||
80 | |||
81 | /** |
||
82 | * @param number $operand1 |
||
83 | * @param number $operand2 |
||
84 | * |
||
85 | * @return bool|number |
||
86 | */ |
||
87 | protected static function subtract($operand1, $operand2) |
||
91 | |||
92 | /** |
||
93 | * @param number $operand1 |
||
94 | * @param number $operand2 |
||
95 | * |
||
96 | * @return bool|number |
||
97 | */ |
||
98 | protected static function divide($operand1, $operand2) |
||
102 | |||
103 | /** |
||
104 | * @param number $operand1 |
||
105 | * @param number $operand2 |
||
106 | * |
||
107 | * @return bool|number |
||
108 | */ |
||
109 | protected static function exponent($operand1, $operand2) |
||
113 | |||
114 | /** |
||
115 | * @param number $operand1 |
||
116 | * @param number $operand2 |
||
117 | * |
||
118 | * @return bool |
||
119 | */ |
||
120 | protected static function greaterthan($operand1, $operand2) |
||
124 | |||
125 | /** |
||
126 | * @param number $operand1 |
||
127 | * @param number $operand2 |
||
128 | * |
||
129 | * @return bool |
||
130 | */ |
||
131 | protected static function lessthan($operand1, $operand2) |
||
135 | |||
136 | /** |
||
137 | * @param number $operand1 |
||
138 | * @param number $operand2 |
||
139 | * |
||
140 | * @return bool |
||
141 | */ |
||
142 | protected static function equalto($operand1, $operand2) |
||
146 | } |
||
147 |