Completed
Push — master ( 4ea848...577058 )
by Hannes
02:16
created

Regexp::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace hanneskod\readmetester\Expectation;
4
5
/**
6
 * Regular expression container
7
 */
8
class Regexp
9
{
10
    /**
11
     * @var string Regular expression
12
     */
13
    private $regexp;
14
15
    public function __construct($regexp)
16
    {
17
        $this->regexp = $this->isRegexp($regexp) ? $regexp : $this->makeRegexp($regexp);
18
    }
19
20
    /**
21
     * Get expression as string
22
     *
23
     * @return string
24
     */
25
    public function __toString()
26
    {
27
        return $this->regexp;
28
    }
29
30
    /**
31
     * Check if this expression matches subject
32
     *
33
     * @param  string $subject
34
     * @return bool
35
     */
36
    public function isMatch($subject)
37
    {
38
        return !!preg_match($this->regexp, $subject);
39
    }
40
41
    /**
42
     * Check if string is a regular expression
43
     *
44
     * @param  string $input
45
     * @return bool
46
     */
47
    private function isRegexp($input)
48
    {
49
        set_error_handler(function () {});
50
        $result = preg_match($input, '');
51
        restore_error_handler();
52
        return $result !== false;
53
    }
54
55
    /**
56
     * Create regular expression from string
57
     *
58
     * @param  string $input
59
     * @return string
60
     */
61
    private function makeRegexp($input)
62
    {
63
        return sprintf(
64
            '/^%s$/',
65
            preg_quote($input)
66
        );
67
    }
68
}
69