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

RequiredHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 17 4
A __construct() 0 3 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