Passed
Pull Request — master (#65)
by Alexander
27:54 queued 12:56
created

MatchRegularExpression::message()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
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\HasValidationMessage;
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 HasValidationMessage;
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 1
31
    private string $message = 'Value is invalid.';
32 1
33
    public function __construct(string $pattern)
34
    {
35 1
        $this->pattern = $pattern;
36
    }
37 1
38
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
39 1
    {
40 1
        $result = new Result();
41 1
42
        $valid = !is_array($value) &&
43 1
            ((!$this->not && preg_match($this->pattern, $value))
44 1
                || ($this->not && !preg_match($this->pattern, $value)));
45
46
        if (!$valid) {
47 1
            $result->addError($this->translateMessage($this->message));
48
        }
49
50 1
        return $result;
51
    }
52 1
53 1
    public function not(): self
54 1
    {
55
        $new = clone $this;
56
        $new->not = true;
57
        return $new;
58
    }
59
}
60