Test Failed
Push — master ( 22d245...e46311 )
by Hannes
02:55
created

Regexp::isRegexp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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