Regexp   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

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

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 matches() 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
    private string $regexp;
13
14
    public function __construct(string $regexp)
15
    {
16
        $this->regexp = $this->isRegexp($regexp) ? $regexp : $this->makeRegexp($regexp);
17
    }
18
19
    /**
20
     * Get expression as string
21
     */
22
    public function getRegexp(): string
23
    {
24
        return $this->regexp;
25
    }
26
27
    /**
28
     * Check if this expression matches subject
29
     */
30
    public function matches(string $subject): bool
31
    {
32
        return !!preg_match($this->regexp, $subject);
33
    }
34
35
    /**
36
     * Check if string is a regular expression
37
     */
38
    private function isRegexp(string $input): bool
39
    {
40
        set_error_handler(function () {
41
        });
42
        $result = preg_match($input, '');
43
        restore_error_handler();
44
        return $result !== false;
45
    }
46
47
    /**
48
     * Create regular expression from string
49
     */
50
    private function makeRegexp(string $input): string
51
    {
52
        return sprintf(
53
            '/^%s$/',
54
            preg_quote($input)
55
        );
56
    }
57
}
58