Completed
Pull Request — master (#175)
by Alexander
02:53 queued 02:53
created

Regex::getOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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