Regex::parse()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 6
nop 3
dl 0
loc 15
ccs 10
cts 10
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 InvalidArgumentException;
6
use Vanderlee\Comprehend\Core\Context;
7
use Vanderlee\Comprehend\Parser\Parser;
8
9
/**
10
 * Matches regular expressions.
11
 *
12
 * @author Martijn
13
 */
14
class Regex extends Parser
15
{
16
    use CaseSensitiveTrait;
17
18
    /**
19
     * @var string|null
20
     */
21
    private $pattern = null;
22
23 12
    public function __construct(string $pattern)
24
    {
25 12
        if (empty($pattern)) {
26 1
            throw new InvalidArgumentException('Empty pattern');
27
        }
28
29 11
        if (@preg_match($pattern, null) === false) {
0 ignored issues
show
Bug introduced by
null of type null is incompatible with the type string expected by parameter $subject of preg_match(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

29
        if (@preg_match($pattern, /** @scrutinizer ignore-type */ null) === false) {
Loading history...
30 2
            throw new InvalidArgumentException('Invalid pattern');
31
        }
32
33 9
        $this->pattern = $pattern;
34 9
    }
35
36 9
    protected function parse(&$input, $offset, Context $context)
37
    {
38 9
        $this->pushCaseSensitivityToContext($context);
39 9
        $pattern = $this->pattern . ($context->isCaseSensitive()
40 8
                ? ''
41 9
                : 'i');
42 9
        $this->popCaseSensitivityFromContext($context);
43
44 9
        if (preg_match($pattern, $input, $match, 0, $offset) !== false) {
45 9
            if (count($match) > 0 && mb_strlen($match[0]) > 0 && strpos($input, $match[0], $offset) === $offset) {
46 6
                return $this->success($input, $offset, mb_strlen($match[0]));
47
            }
48
        }
49
50 3
        return $this->failure($input, $offset);
51
    }
52
53 9
    public function __toString()
54
    {
55 9
        return (string)$this->pattern;
56
    }
57
}
58