Completed
Push — master ( 17974d...3e8f03 )
by Ilias
02:15
created

Parser::parseTokenStream()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 15
ccs 10
cts 10
cp 1
rs 9.4285
cc 2
eloc 8
nc 2
nop 2
crap 2
1
<?php
2
3
4
namespace CondParse;
5
6
7
use CondParse\Exception\ParserException;
8
9
class Parser implements ParserInterface
10
{
11
    /** @var TokenParser */
12
    private $tokenParser;
13
14 14
    public function __construct(TokenParser $tokenParser = null)
15
    {
16 14
        $this->tokenParser = $tokenParser ?: new TokenParser;
17 14
    }
18
19
    /**
20
     * @param \Traversable $tokenStream
21
     * @param TokenMap $tokenMap
22
     * @return OperandInterface
23
     * @throws ParserException
24
     */
25 14
    public function parseTokenStream(\Traversable $tokenStream, TokenMap $tokenMap)
26
    {
27 14
        $operandStack = new OperandStack();
28 14
        $operatorStack = new \SplStack();
29
30 14
        foreach ($tokenStream as $lexerToken) {
31 13
            $this->tokenParser->parseToken(
32 13
                new TokenParserParameter($lexerToken, $operandStack, $operatorStack, $tokenMap)
33 13
            );
34 14
        }
35
36 14
        $this->unfoldStack($tokenMap, $operatorStack, $operandStack);
37
38 14
        return $operandStack->top();
39
    }
40
41
    /**
42
     * @param TokenMap $tokenMap
43
     * @param \SplStack $operatorStack
44
     * @param OperandStack $operandStack
45
     */
46 14
    protected function unfoldStack(TokenMap $tokenMap, $operatorStack, $operandStack)
47
    {
48 14
        while (!$operatorStack->isEmpty()) {
49 7
            $operandStack->push(
50
                $tokenMap
51 7
                    ->buildOperand($operatorStack->pop())
52 7
                    ->consumeTokens($operandStack)
53 7
            );
54 7
        }
55 14
    }
56
}
57