Passed
Pull Request — master (#81)
by Def
04:12 queued 02:54
created

MatchRegularExpression   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 63
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0
wmc 11

5 Methods

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