Test Setup Failed
Push — master ( e94fe5...b7ec94 )
by
unknown
02:01
created

Required::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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