Completed
Pull Request — master (#20)
by X
03:52
created

Source::peek()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Input for parser
4
 */
5
namespace xKerman\Restricted;
6
7
/**
8
 * Parser Input
9
 */
10
class Source
11
{
12
    /** @var string $str given string to deserialize */
13
    private $str;
14
15
    /** @var int $current current position of parser */
16
    private $current;
17
18
    /**
19
     * constructor
20
     *
21
     * @param string $str parser input
22
     * @throws \InvalidArgumentException
23
     */
24 36
    public function __construct($str)
25
    {
26 36
        if (!is_string($str)) {
27 1
            throw new \InvalidArgumentException('expected string, but got: ' . gettype($str));
28
        }
29 35
        $this->str = $str;
30 35
        $this->current = 0;
31 35
    }
32
33
    /**
34
     * throw error with currnt position
35
     *
36
     * @return void
37
     * @throws UnserializeFailedException
38
     */
39 1
    public function triggerError()
40
    {
41 1
        $bytes = strlen($this->str);
42 1
        throw new UnserializeFailedException("unserialize(): Error at offset {$this->current} of {$bytes} bytes");
43
    }
44
45
    /**
46
     * return current character
47
     *
48
     * @return string
49
     */
50 34
    public function peek()
51
    {
52 34
        return substr($this->str, $this->current, 1);
53
    }
54
55
    /**
56
     * go ahead one character
57
     *
58
     * @return void
59
     */
60 30
    public function next()
61
    {
62 30
        ++$this->current;
63 30
    }
64
65
    /**
66
     * consume given string if it is as expected
67
     *
68
     * @param string $expected expected string
69
     * @return void
70
     * @throws UnserializeFailedException
71
     */
72 35
    public function consume($expected)
73
    {
74 35
        if (strpos($this->str, $expected, $this->current) !== $this->current) {
75 1
            return $this->triggerError();
76
        }
77 34
        $this->current += strlen($expected);
78 34
    }
79
80
    /**
81
     * read givin length substring
82
     *
83
     * @param integer $length length to read
84
     * @return string
85
     * @throws UnserializeFailedException
86
     */
87 11
    public function read($length)
88
    {
89 11
        if ($length < 0) {
90 1
            return $this->triggerError();
91
        }
92
93 10
        $result = substr($this->str, $this->current, $length);
94 10
        if (strlen($result) !== $length) {
95 1
            return $this->triggerError();
96
        }
97 9
        $this->current += $length;
98 9
        return $result;
99
    }
100
}
101