Passed
Pull Request — master (#222)
by Dmitriy
02:23
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
c 0
b 0
f 0
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 9.5555
cc 5
nc 5
nop 3
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\ValidationContext;
10
use Yiisoft\Validator\ValidatorInterface;
11
use Yiisoft\Validator\Exception\UnexpectedRuleException;
12
13
final class CallbackHandler implements RuleHandlerInterface
14
{
15 8
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
16
    {
17 8
        if (!$rule instanceof Callback) {
18 1
            throw new UnexpectedRuleException(Callback::class, $rule);
19
        }
20
21 7
        $callback = $rule->callback;
22 7
        $callbackResult = $callback($value, $context);
23
24 7
        if (!$callbackResult instanceof Result) {
25 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
26
        }
27
28 6
        $result = new Result();
29 6
        if ($callbackResult->isValid()) {
30 1
            return $result;
31
        }
32
33 5
        foreach ($callbackResult->getErrors() as $error) {
34 5
            $result->mergeError($error);
35
        }
36
37 5
        return $result;
38
    }
39
}
40