Completed
Push — master ( 5ad706...418f81 )
by Sebastian
03:53
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 RuleValidateInterface
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
     * @return bool
41
     */
42 2
    public function validate(): bool
43
    {
44 2
        $args = func_get_args();
45
46 2
        return $this->concreteValidate($args[0], $args[1]);
47
    }
48
49
    /**
50
     * Concrete validate.
51
     *
52
     * @param string $received
53
     * @param string $regex
54
     *
55
     * @return bool
56
     */
57 2
    private function concreteValidate(string $received, string $regex): bool
58
    {
59 2
        $matches = [];
60
61 2
        $result = preg_match($regex, $received, $matches);
62
63 2
        if ($result === 0) {
64 1
            $this->message = "Received value must match regex {$regex}";
65 1
            return true;
66
        }
67
68 1
        if ($result === false) {
0 ignored issues
show
introduced by
The condition $result === false is always false.
Loading history...
69
            $this->message = "Invalid regex provided {$regex}";
70
            return true;
71
        }
72
73 1
        return false;
74
    }
75
76
    /**
77
     * Return error message.
78
     *
79
     * @return string Error message
80
     */
81
    public function getMessage(): string
82
    {
83
        return $this->message;
84
    }
85
}
86