Passed
Pull Request — master (#99)
by Def
02:39
created

MatchRegularExpression::getRawOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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