Completed
Push — master ( b1dbfd...5ad706 )
by Sebastian
03:07
created

Regex::getMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Linna Filter
5
 *
6
 * @author Sebastian Rapetti <[email protected]>
7
 * @copyright (c) 2018, Sebastian Rapetti
8
 * @license http://opensource.org/licenses/MIT MIT License
9
 */
10
declare(strict_types = 1);
11
12
namespace Linna\Filter\Rules;
13
14
/**
15
 * Check if passed string match a regex
16
 */
17
class Regex implements RuleInterface
18
{
19
    /**
20
     * @var array Rule properties
21
     */
22
    public static $config = [
23
        'class' => 'Regex',
24
        'full_class' => __CLASS__,
25
        'alias' => ['regex', 'rex', 'rx'],
26
        'args_count' => 1,
27
        'args_type' => ['string'],
28
        'has_validate' => true,
29
        'has_sanitize' => false
30
    ];
31
32
    /**
33
     * @var string Error message
34
     */
35
    private $message = '';
36
37
    /**
38
     * Validate.
39
     *
40
     * @param string $received
41
     * @param string $regex
42
     *
43
     * @return bool
44
     */
45 2
    public function validate(string $received, string $regex): bool
46
    {
47 2
        $matches = [];
48
49 2
        $result = preg_match($regex, $received, $matches);
50
51 2
        if ($result === 0) {
52 1
            $this->message = "Received value must match regex {$regex}";
53 1
            return true;
54
        }
55
56 1
        if ($result === false) {
0 ignored issues
show
introduced by
The condition $result === false is always false.
Loading history...
57
            $this->message = "Invalid regex provided {$regex}";
58
            return true;
59
        }
60
61 1
        return false;
62
    }
63
64
    /**
65
     * Return error message.
66
     *
67
     * @return string Error message
68
     */
69
    public function getMessage(): string
70
    {
71
        return $this->message;
72
    }
73
}
74