1: <?php
2:
3: namespace BN\Compiler\Postfix;
4:
5: use BN\Collections\Stack;
6: use BN\Compiler\Token\Token;
7: use BN\Compiler\Token\TokenType;
8:
9: class StackAccumulator
10: {
11: private $errorHandler;
12: private $stack;
13: private $continueInCalculation;
14:
15: public function __construct(CalculatorErrorHandler $errorHandler)
16: {
17: $this->errorHandler = $errorHandler;
18: $this->stack = new Stack();
19: }
20:
21: public function init()
22: {
23: $this->stack->clear();
24: $this->continueInCalculation = true;
25: }
26:
27: public function continueInCalculation()
28: {
29: return $this->continueInCalculation;
30: }
31:
32: public function pushToken(Token $token)
33: {
34: $this->stack->push($token);
35: }
36:
37: public function pushNumber($number)
38: {
39: $this->pushToken(
40: new Token(TokenType::NUMBER, $number)
41: );
42: }
43:
44: public function stopCalculation()
45: {
46: $args = func_get_args();
47: $method = array_shift($args);
48:
49: $this->continueInCalculation = false;
50: call_user_func_array(array($this->errorHandler, $method), $args);
51: }
52:
53: public function getStack()
54: {
55: return $this->stack;
56: }
57:
58: public function getResult()
59: {
60: $size = $this->stack->size();
61: if ($size == 1) {
62: return $this->stack->pop()->value;
63: } elseif ($size > 0) {
64: $this->stopCalculation('missingOperator', $size);
65: }
66: return 0;
67: }
68: }
69: