Passed
Pull Request — master (#320)
by Dmitriy
12:15 queued 09:25
created

RequiredHandler::validate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 10
cc 4
nc 3
nop 3
crap 4
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\Result;
9
use Yiisoft\Validator\Rule\Trait\EmptyCheckTrait;
10
use Yiisoft\Validator\RuleHandlerInterface;
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
final class RequiredHandler implements RuleHandlerInterface
19
{
20
    use EmptyCheckTrait;
21
22 28
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
23
    {
24 28
        if (!$rule instanceof Required) {
25 1
            throw new UnexpectedRuleException(Required::class, $rule);
26
        }
27
28 27
        $result = new Result();
29
30 27
        if ($this->isEmpty(is_string($value) ? trim($value) : $value)) {
31 13
            $result->addError(
32 13
                message: $rule->getMessage(),
33 13
                parameters:  ['value' => $value]
34
            );
35
        }
36
37 27
        return $result;
38
    }
39
}
40