Passed
Pull Request — master (#222)
by Dmitriy
12:29
created

CallbackHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 13
dl 0
loc 25
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 23 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\InvalidCallbackReturnTypeException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
use Yiisoft\Validator\Exception\UnexpectedRuleException;
13
14
final class CallbackHandler implements RuleHandlerInterface
15
{
16 8
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
17
    {
18 8
        if (!$rule instanceof Callback) {
19 1
            throw new UnexpectedRuleException(Callback::class, $rule);
20
        }
21
22 7
        $callback = $rule->callback;
23 7
        $callbackResult = $callback($value, $context);
24
25 7
        if (!$callbackResult instanceof Result) {
26 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
27
        }
28
29 6
        $result = new Result();
30 6
        if ($callbackResult->isValid()) {
31 1
            return $result;
32
        }
33
34 5
        foreach ($callbackResult->getErrors() as $error) {
35 5
            $result->mergeError($error);
36
        }
37
38 5
        return $result;
39
    }
40
}
41