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

Regexp   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 46
rs 10
c 0
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A isRegexp() 0 7 1
A makeRegexp() 0 5 1
A __construct() 0 3 2
A getRegexp() 0 3 1
A isMatch() 0 3 1
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