Passed
Pull Request — master (#222)
by Dmitriy
02:30
created

RequiredHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 17
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 13 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Required;
6
7
use Yiisoft\Validator\Result;
8
use Yiisoft\Validator\Rule\EmptyCheckTrait;
9
use Yiisoft\Validator\Rule\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
use function is_string;
13
use Yiisoft\Validator\Exception\UnexpectedRuleException;
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 20
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
23
    {
24 20
        if (!$rule instanceof Required) {
25 1
            throw new UnexpectedRuleException(Required::class, $rule);
26
        }
27
28 19
        $result = new Result();
29
30 19
        if ($this->isEmpty(is_string($value) ? trim($value) : $value)) {
31 5
            $result->addError($rule->message);
32
        }
33
34 19
        return $result;
35
    }
36
}
37