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

MatchRegularExpression::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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