Passed
Push — master ( ddc766...cecfbc )
by Alexander
01:30
created

MatchRegularExpression   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 77.78%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 46
ccs 14
cts 18
cp 0.7778
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

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