Test Failed
Pull Request — master (#175)
by
unknown
05:56 queued 03:39
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
dl 0
loc 50
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 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 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
    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 8
    ) {
41
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
42 8
    }
43 8
44 8
    protected function validateValue($value, ?ValidationContext $context = null): Result
45
    {
46
        $result = new Result();
47 7
48
        if (!is_string($value)) {
49 7
            $result->addError($this->formatMessage($this->incorrectInputMessage));
50
51 7
            return $result;
52 4
        }
53
54 4
        if (
55
            (!$this->not && !preg_match($this->pattern, $value)) ||
56
            ($this->not && preg_match($this->pattern, $value))
57
        ) {
58 3
            $result->addError($this->formatMessage($this->message));
59 3
        }
60
61 3
        return $result;
62
    }
63
64 3
    public function getOptions(): array
65
    {
66
        return array_merge(parent::getOptions(), [
67 5
            'pattern' => $this->pattern,
68
            'not' => $this->not,
69 5
            'incorrectInputMessage' => $this->formatMessage($this->incorrectInputMessage),
70 5
            'message' => $this->formatMessage($this->message),
71 5
        ]);
72
    }
73
}
74