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

Required   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 28
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validateValue() 0 9 3
A getOptions() 0 4 1
A __construct() 0 8 1
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 specified value is neither null nor empty.
17
 */
18
#[Attribute(Attribute::TARGET_PROPERTY)]
19
final class Required extends Rule
20
{
21 21
    public function __construct(
22
        private string $message = 'Value cannot be blank.',
23
        ?FormatterInterface $formatter = null,
24
        bool $skipOnEmpty = false,
25
        bool $skipOnError = false,
26
        $when = null
27
    ) {
28 21
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
29
    }
30
31 13
    protected function validateValue($value, ?ValidationContext $context = null): Result
32
    {
33 13
        $result = new Result();
34
35 13
        if ($this->isEmpty(is_string($value) ? trim($value) : $value)) {
36 3
            $result->addError($this->formatMessage($this->message));
37
        }
38
39 13
        return $result;
40
    }
41
42 4
    public function getOptions(): array
43
    {
44 4
        return array_merge(parent::getOptions(), [
45 4
            'message' => $this->formatMessage($this->message),
46
        ]);
47
    }
48
}
49