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

Regex::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
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
 * 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