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

CallbackHandler::validate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 9.5555
c 0
b 0
f 0
cc 5
nc 5
nop 4
crap 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