Passed
Pull Request — master (#240)
by Dmitriy
03:45
created

RequiredHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Formatter;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\Rule\Trait\EmptyCheckTrait;
12
use Yiisoft\Validator\ValidationContext;
13
14
use function is_string;
15
16
/**
17
 * Validates that the specified value is neither null nor empty.
18
 */
19
final class RequiredHandler implements RuleHandlerInterface
20
{
21
    use EmptyCheckTrait;
22
23
    private FormatterInterface $formatter;
24
25 22
    public function __construct(?FormatterInterface $formatter = null)
26
    {
27 22
        $this->formatter = $formatter ?? new Formatter();
28
    }
29
30 22
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
31
    {
32 22
        if (!$rule instanceof Required) {
33 1
            throw new UnexpectedRuleException(Required::class, $rule);
34
        }
35
36 21
        $result = new Result();
37
38 21
        if ($this->isEmpty(is_string($value) ? trim($value) : $value)) {
39 6
            $formattedMessage = $this->formatter->format(
40 6
                $rule->getMessage(),
41 6
                ['attribute' => $context?->getAttribute(), 'value' => $value]
42
            );
43 6
            $result->addError($formattedMessage);
44
        }
45
46 21
        return $result;
47
    }
48
}
49