Passed
Pull Request — master (#175)
by
unknown
02:24
created

MatchRegularExpression::not()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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