Completed
Push — master ( b6cc57...033934 )
by Harry
8s
created

State::match()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 5
nc 3
nop 2
crap 3
1
<?php
2
3
namespace Graze\CsvToken\Tokeniser;
4
5
use RuntimeException;
6
7
class State
8
{
9
    const S_ANY             = 0;
10
    const S_IN_QUOTE        = 1;
11
    const S_IN_ESCAPE       = 2;
12
    const S_IN_QUOTE_ESCAPE = 4;
13
14
    const S_ANY_TOKENS             = Token::T_ANY & ~Token::T_DOUBLE_QUOTE;
15
    const S_IN_QUOTE_TOKENS        = Token::T_CONTENT | Token::T_QUOTE | Token::T_DOUBLE_QUOTE | Token::T_ESCAPE;
16
    const S_IN_ESCAPE_TOKENS       = Token::T_CONTENT;
17
    const S_IN_QUOTE_ESCAPE_TOKENS = Token::T_CONTENT;
18
19
    /** @var array */
20
    private $types;
21
    /** @var State[] */
22
    private $states;
23
24
    /**
25
     * State constructor.
26
     *
27
     * @param array $types
28
     */
29 20
    public function __construct(array $types)
30
    {
31 20
        $this->types = $types;
32 20
    }
33
34
    /**
35
     * @param int $token
36
     *
37
     * @return State|null
38
     */
39 17
    public function getNextState($token)
40
    {
41 17
        foreach ($this->states as $mask => $state) {
42 17
            if ($mask & $token) {
43 17
                return $state;
44
            }
45
        }
46
47 1
        throw new RuntimeException("The supplied token: {$token} has no target state");
48
    }
49
50
    /**
51
     * @param int   $tokenMask
52
     * @param State $target
53
     */
54 20
    public function addStateTarget($tokenMask, State $target)
55
    {
56 20
        $this->states[$tokenMask] = $target;
57 20
    }
58
59
    /**
60
     * @param int    $position
61
     * @param string $buffer
62
     *
63
     * @return Token
64
     */
65 16
    public function match($position, $buffer)
66
    {
67 16
        foreach ($this->types as $search => $tokenType) {
68 16
            if (substr($buffer, 0, strlen($search)) == $search) {
69 16
                return new Token($tokenType, $search, $position);
70
            }
71
        }
72
73 16
        return new Token(Token::T_CONTENT, $buffer[0], $position);
74
    }
75
}
76