Test Failed
Pull Request — master (#175)
by
unknown
12:57
created

MatchRegularExpression   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 50
ccs 15
cts 15
cp 1
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 1
A getOptions() 0 7 1
A validateValue() 0 18 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\FormatterInterface;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function is_string;
13
14
/**
15
 * RegularExpressionValidator validates that the attribute value matches the pattern specified in constructor.
16
 *
17
 * If the {@see MatchRegularExpression::$not} is used, the validator will ensure the attribute value do NOT match
18
 * the pattern.
19
 */
20
final class MatchRegularExpression extends Rule
21
{
22
    public function __construct(
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`, the regular
29
         * expression defined via {@see $pattern} should NOT match the attribute value.
30
         */
31
        private bool $not = false,
32
        private string $incorrectInputMessage = 'Value should be string.',
33
        private string $message = 'Value is invalid.',
34
35
        ?FormatterInterface $formatter = null,
36
        bool $skipOnEmpty = false,
37
        bool $skipOnError = false,
38
        $when = null
39
    ) {
40 8
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
41
    }
42 8
43 8
    protected function validateValue($value, ?ValidationContext $context = null): Result
44 8
    {
45
        $result = new Result();
46
47 7
        if (!is_string($value)) {
48
            $result->addError($this->formatMessage($this->incorrectInputMessage));
49 7
50
            return $result;
51 7
        }
52 4
53
        if (
54 4
            (!$this->not && !preg_match($this->pattern, $value)) ||
55
            ($this->not && preg_match($this->pattern, $value))
56
        ) {
57
            $result->addError($this->formatMessage($this->message));
58 3
        }
59 3
60
        return $result;
61 3
    }
62
63
    public function getOptions(): array
64 3
    {
65
        return array_merge(parent::getOptions(), [
66
            'pattern' => $this->pattern,
67 5
            'not' => $this->not,
68
            'incorrectInputMessage' => $this->formatMessage($this->incorrectInputMessage),
69 5
            'message' => $this->formatMessage($this->message),
70 5
        ]);
71 5
    }
72
}
73