KeyParser::checkForBadlyFormedKey()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4286
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace PhpHocon\Token\Parser;
4
5
use PhpHocon\Token\Key;
6
use PhpHocon\Token\Tokens;
7
use Symfony\Component\Yaml\Exception\ParseException;
8
9
class KeyParser implements Parser
10
{
11
    /**
12
     * @var array
13
     */
14
    private $breakCharacters = [
15
        Tokens::EQUALS,
16
        Tokens::COLON,
17
        Tokens::SPACE
18
    ];
19
20
    /**
21
     * @param ParserState $state
22
     * @return boolean
23
     */
24
    public function canParse(ParserState $state)
25
    {
26
        return $state->isParsingKey() && !in_array($state->getHeadCharacter(), $this->breakCharacters);
27
    }
28
29
    /**
30
     * @param ParserState $state
31
     * @return ParseResult
32
     */
33
    public function parse(ParserState $state)
34
    {
35
        $characters = $state->getCharacters();
36
        $keyName = '';
37
38
        while ($this->canParseKey($characters)) {
39
            $keyName .= array_shift($characters);
40
        }
41
42
        $this->checkForBadlyFormedKey($keyName);
43
44
        return new ParseResult(
45
            new ParserState($characters, $state->getBraceCount(), false, true),
46
            new Key($keyName)
47
        );
48
    }
49
50
    /**
51
     * @param string[] $characters
52
     * @return bool
53
     */
54
    private function canParseKey(array $characters)
55
    {
56
        return !empty($characters) && !in_array($characters[0], $this->breakCharacters);
57
    }
58
59
    private function checkForBadlyFormedKey($keyName)
60
    {
61
        if ($keyName[strlen($keyName) - 1] === '.') {
62
            throw new ParseException('Malformed key: ' . $keyName);
63
        }
64
    }
65
}
66