Completed
Push — master ( ddfb7b...c3a867 )
by Michele
04:20
created

StringReader::setPosition()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 0
cp 0
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 12
1
<?php
2
3
namespace CHMLib\Reader;
4
5
use Exception;
6
7
/**
8
 * Read data from a raw string of bytes.
9
 */
10
class StringReader extends Reader
11
{
12
    /**
13
     * The raw string of bytes.
14
     *
15
     * @var string
16
     */
17
    protected $string;
18
19
    /**
20
     * The current position in the string.
21
     *
22
     * @var int
23
     */
24
    protected $position;
25
26
    /**
27
     * The string length.
28
     *
29
     * @var int
30
     */
31
    protected $length;
32
33
    /**
34
     * Initializes the instance.
35
     *
36
     * @param string $string The raw string containing the data to be read.
37
     */
38 23
    public function __construct($string)
39
    {
40 23
        $this->string = (string) $string;
41 23
        $this->position = 0;
42 23
        $this->length = strlen($this->string);
43 23
    }
44
45
    /**
46
     * {@inheritdoc}
47
     *
48
     * @see Reader::setPosition()
49
     */
50
    public function setPosition($position)
51
    {
52
        if ($position < 0 || $position > $this->length) {
53
            throw new Exception('Failed to seek string to to position '.$position);
54
        }
55
        $this->position = $position;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     *
61
     * @see Reader::getPosition()
62
     */
63
    public function getPosition()
64
    {
65
        return $this->position;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     *
71
     * @see Reader::getLength()
72
     */
73
    public function getLength()
74
    {
75
        return $this->length;
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     *
81
     * @see Reader::readString()
82
     */
83 23
    public function readString($length)
84
    {
85 23
        if (!$length) {
86
            $result = '';
87 23
        } elseif ($this->position + $length > $this->length) {
88
            throw new Exception('Read after end-of-string');
89
        } else {
90 23
            $result = substr($this->string, $this->position, $length);
91 23
            $this->position += $length;
92
        }
93
94 23
        return $result;
95
    }
96
}
97