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