Completed
Push — master ( c80620...0cd8d9 )
by Martijn
03:25
created

Regex   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 41
rs 10
c 0
b 0
f 0
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 13 6
A __construct() 0 11 3
A __toString() 0 3 1
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
 * Matches regular expressions
10
 *
11
 * @author Martijn
12
 */
13
class Regex extends Parser
14
{
15
16
    use CaseSensitiveTrait;
17
18
    /**
19
     * @var string|null
20
     */
21
    private $pattern = null;
22
23
    public function __construct($pattern)
24
    {
25
        if (empty($pattern)) {
26
            throw new \InvalidArgumentException('Empty pattern');
27
        }
28
29
        if (@preg_match($pattern, null) === false) {
30
            throw new \InvalidArgumentException('Invalid pattern');
31
        }
32
33
        $this->pattern = $pattern;
34
    }
35
36
    protected function parse(&$input, $offset, Context $context)
37
    {
38
        $this->pushCaseSensitivityToContext($context);
39
        $pattern = $this->pattern . ($context->isCaseSensitive() ? '' : 'i');
40
        $this->popCaseSensitivityFromContext($context);
41
42
        if (preg_match($pattern, $input, $match, 0, $offset) !== false) {
43
            if (count($match) > 0 && mb_strlen($match[0]) > 0 && strpos($input, $match[0], $offset) == $offset) {
44
                return $this->success($input, $offset, mb_strlen($match[0]));
45
            }
46
        }
47
48
        return $this->failure($input, $offset);
49
    }
50
51
    public function __toString()
52
    {
53
        return (string)$this->pattern;
54
    }
55
56
}
57