Passed
Pull Request — master (#99)
by Def
02:39
created

MatchRegularExpression   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 21
c 0
b 0
f 0
dl 0
loc 51
ccs 21
cts 21
cp 1
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A not() 0 5 1
A __construct() 0 3 1
A validateValue() 0 13 6
A getRawOptions() 0 8 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\DataSetInterface;
8
use Yiisoft\Validator\ErrorMessage;
9
use Yiisoft\Validator\ErrorMessageFormatterInterface;
10
use Yiisoft\Validator\HasValidationErrorMessage;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\Rule;
13
14
/**
15
 * RegularExpressionValidator validates that the attribute value matches the specified [[pattern]].
16
 *
17
 * If the [[not]] property is set true, the validator will ensure the attribute value do NOT match the [[pattern]].
18
 */
19
class MatchRegularExpression extends Rule
20
{
21
    use HasValidationErrorMessage;
22
23
    /**
24
     * @var string the regular expression to be matched with
25
     */
26
    private string $pattern;
27
    /**
28
     * @var bool whether to invert the validation logic. Defaults to false. If set to true,
29
     * the regular expression defined via [[pattern]] should NOT match the attribute value.
30
     */
31
    private bool $not = false;
32
33
    private string $message = 'Value is invalid.';
34
35 2
    public function __construct(string $pattern)
36
    {
37 2
        $this->pattern = $pattern;
38 2
    }
39
40 1
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
41
    {
42 1
        $result = new Result();
43
44 1
        $valid = !is_array($value) &&
45 1
            ((!$this->not && preg_match($this->pattern, $value))
46 1
                || ($this->not && !preg_match($this->pattern, $value)));
47
48 1
        if (!$valid) {
49 1
            $result->addError(new ErrorMessage($this->message));
50
        }
51
52 1
        return $result;
53
    }
54
55 1
    public function not(): self
56
    {
57 1
        $new = clone $this;
58 1
        $new->not = true;
59 1
        return $new;
60
    }
61
62 2
    public function getRawOptions(): array
63
    {
64 2
        return array_merge(
65 2
            parent::getRawOptions(),
66
            [
67 2
                'message' => new ErrorMessage($this->message),
68 2
                'not' => $this->not,
69 2
                'pattern' => $this->pattern,
70
            ],
71
        );
72
    }
73
}
74