HoconTokenizer::createCharacterList()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4286
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
3
namespace PhpHocon\Token;
4
5
use PhpHocon\Exception\ParseException;
6
use PhpHocon\Token\Parser\AssignmentParser;
7
use PhpHocon\Token\Parser\KeyParser;
8
use PhpHocon\Token\Parser\Parser;
9
use PhpHocon\Token\Parser\ParserState;
10
use PhpHocon\Token\Parser\ValueParser;
11
use PhpHocon\Token\Parser\WhitespaceParser;
12
13
class HoconTokenizer implements Tokenizer
14
{
15
    /**
16
     * @var array
17
     */
18
    private $tokens;
19
20
    /**
21
     * @var Parser[]
22
     */
23
    private $parserChain;
24
25
    public function __construct()
26
    {
27
        $this->parserChain = [
28
            new KeyParser(),
29
            new ValueParser(),
30
            new AssignmentParser(),
31
            new WhitespaceParser()
32
        ];
33
    }
34
35
    /**
36
     * @param string $input
37
     * @return array
38
     */
39
    public function tokenize($input)
40
    {
41
        $this->tokens = [];
42
        $chars = $this->createCharacterList($input);
43
44
        $initialState = new ParserState($chars, 0, false, true);
45
        $endState = $this->parseState($initialState);
46
47
        $this->checkParserState($endState);
48
49
        return $this->tokens;
50
    }
51
52
    /**
53
     * @param ParserState $state
54
     */
55
    private function checkParserState(ParserState $state)
56
    {
57
        if (count($state->getCharacters())) {
58
            throw new ParseException(
59
                'Config file was not parsed completely. Remaining: ' . implode($state->getCharacters())
60
            );
61
        }
62
    }
63
64
    /**
65
     * @param $input
66
     * @return array
67
     */
68
    private function createCharacterList($input)
69
    {
70
        $chars = str_split($input);
71
72
        if ($chars[0] !== Tokens::LEFT_BRACE) {
73
            return $chars;
74
        }
75
76
        if ($chars[count($chars) - 1] !== Tokens::RIGHT_BRACE) {
77
            throw new ParseException('Brace count is not equal');
78
        }
79
80
        return array_slice($chars, 1, -1);
81
    }
82
83
    private function parseState(ParserState $state)
84
    {
85
        if (count($state->getCharacters()) === 0) {
86
            return $state;
87
        }
88
89
        foreach ($this->parserChain as $parser) {
90
            if ($parser->canParse($state)) {
91
                $result = $parser->parse($state);
92
                if (null !== $element = $result->getElement()) {
93
                    $this->tokens[] = $result->getElement();
94
                }
95
                return $this->parseState($result->getState());
96
            }
97
        }
98
99
        return $state;
100
    }
101
}
102