1: <?php
2:
3: namespace BN\Compiler\Postfix\Token;
4:
5: use BN\Compiler\Token\Token;
6: use BN\Compiler\Token\TokenType;
7: use BN\Compiler\Postfix\Operands\Operands;
8: use BN\Compiler\Postfix\Operands\OperandsSummary;
9: use BN\Compiler\Postfix\Variables;
10:
11: class ProcessKeyword
12: {
13: private $variables;
14: private $strategy;
15: private $accumulator;
16:
17: public function __construct($accumulator, Variables $variables, ProcessKeywordStrategy $strategy)
18: {
19: $this->accumulator = $accumulator;
20: $this->variables = $variables;
21: $this->strategy = $strategy;
22: }
23:
24: public function process(Token $token)
25: {
26: $operands = $this->strategy->getOperands();
27: $operandsSummary = $this->getOperands($operands);
28:
29: if ($this->accumulator->continueInCalculation()) {
30: if ($operandsSummary->areOperandsValid) {
31: $result = $this->evaluate($operandsSummary);
32: $this->accumulator->pushNumber($result);
33: } else {
34: $this->accumulator->stopCalculation('invalidOperands', $token->value, $operandsSummary);
35: }
36: }
37: }
38:
39: private function getOperands(Operands $operands)
40: {
41: $summary = $operands->getOperands($this->accumulator->getStack());
42: foreach ($summary->operands as $i => $token) {
43: if ($token->type == TokenType::VARIABLE) {
44: if ($i == 0 && $this->strategy->isFirstOperandVariable()) {
45: continue;
46: } elseif ($this->variables->exists($token)) {
47: $token->value = $this->variables->get($token);
48: $summary->operands[$i] = $token;
49: } else {
50: $this->accumulator->stopCalculation('undefinedVariable', $token->value);
51: }
52: }
53: }
54: return $summary;
55: }
56:
57: private function evaluate(OperandsSummary $summary)
58: {
59: $evaluator = $this->strategy->getEvaluator();
60: $operands = $this->strategy->tokensToOperands($summary->operands);
61: return $evaluator($operands);
62: }
63: }
64: