Passed
Pull Request — master (#520)
by Théo
02:15
created

RegexChecker   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 40
rs 10
c 1
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validateRegex() 0 10 2
A isRegexLike() 0 26 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Humbug\PhpScoper;
6
7
use function count;
8
use function current;
9
use function preg_last_error;
10
use function preg_last_error_msg;
11
use function preg_match as native_preg_match;
12
use function Safe\sprintf;
13
use function str_contains;
14
use function strlen;
15
use function trim;
16
17
// TODO: move this under a Configuration namespace
18
final class RegexChecker
19
{
20
    public function isRegexLike(string $value): bool
21
    {
22
        $valueLength = strlen($value);
23
24
        if ($valueLength < 2) {
25
            return false;
26
        }
27
28
        $firstCharacter = $value[0];
29
        $lastCharacter = $value[$valueLength - 1];
30
31
        if ($firstCharacter !== $lastCharacter) {
32
            return false;
33
        }
34
35
        $trimmedValue = trim($value, $firstCharacter);
36
37
        if (strlen($trimmedValue) !== ($valueLength - 2)) {
38
            return false;
39
        }
40
41
        if (str_contains($trimmedValue, $firstCharacter)) {
42
            return false;
43
        }
44
45
        return true;
46
    }
47
48
    public function validateRegex(string $regex): ?string
49
    {
50
        if (@native_preg_match($regex, '') !== false) {
51
            return null;
52
        }
53
54
        return sprintf(
55
            'Invalid regex: %s (code %s)',
56
            preg_last_error_msg(),
57
            preg_last_error(),
58
        );
59
    }
60
}
61