Passed
Push — master ( f8387b...b124c6 )
by Martijn
02:24
created

Range::parse()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 5
nop 3
dl 0
loc 27
ccs 16
cts 16
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
namespace Vanderlee\Comprehend\Parser\Terminal;
4
5
use Vanderlee\Comprehend\Core\Context;
6
use Vanderlee\Comprehend\Parser\Parser;
7
8
/**
9
 * Description of RangeParser
10
 *
11
 * @author Martijn
12
 */
13
class Range extends Parser
14
{
15
16
    use CaseSensitiveTrait;
17
18
    private $first = null;
19
    private $last  = null;
20
    private $in    = true;
21
22 21
    public function __construct($first, $last, $in = true)
23
    {
24 21
        if ($first === null
25 21
            && $last === null) {
26
27 1
            throw new \InvalidArgumentException('Empty arguments');
28
        }
29
30 20
        $this->first = $first === null
31 1
            ? null
32 19
            : self::parseCharacter($first);
33
34 18
        $this->last = $last === null
35 1
            ? null
36 17
            : self::parseCharacter($last);
37
38 16
        $this->in = (bool)$in;
39 16
    }
40
41 76
    protected function parse(&$input, $offset, Context $context)
42
    {
43 76
        if ($offset >= mb_strlen($input)) {
44 25
            return $this->failure($input, $offset);
45
        }
46
47
48 74
        $isSuccess = !$this->in; // By default not successful if required to match only within range
49
50 74
        $this->pushCaseSensitivityToContext($context);
51
52 74
        $first = ord($context->handleCase($this->first));
53 74
        $last  = ord($context->handleCase($this->last));
54 74
        $ord   = ord($context->handleCase($input[$offset]));
55
56 74
        $this->popCaseSensitivityFromContext($context);
57
58 74
        if ($first <= $ord
59 67
            && ($this->last === null
60 74
                || $ord <= $last)) {
61
62 61
            $isSuccess = !$isSuccess;
63
        }
64
65 74
        return $isSuccess
66 62
            ? $this->success($input, $offset, 1)
67 74
            : $this->failure($input, $offset);
68
    }
69
70 59
    public function __toString()
71
    {
72 59
        return sprintf('x%02x-x%02x', ord($this->first), ord($this->last));
73
    }
74
75
}
76