Passed
Pull Request — master (#222)
by Alexander
04:47 queued 02:23
created

CallbackValidator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 4
nop 4
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 4
rs 9.9332
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Callback;
6
7
use Yiisoft\Validator\Exception\InvalidCallbackReturnTypeException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\RuleValidatorInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
13
final class CallbackValidator implements RuleValidatorInterface
14
{
15 7
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
16
    {
17 7
        $callback = $rule->callback;
18 7
        $callbackResult = $callback($value, $context);
19
20 7
        if (!$callbackResult instanceof Result) {
21 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
22
        }
23
24 6
        $result = new Result();
25 6
        if ($callbackResult->isValid()) {
26 1
            return $result;
27
        }
28
29 5
        foreach ($callbackResult->getErrors() as $error) {
30 5
            $result->merge($error);
31
        }
32
33 5
        return $result;
34
    }
35
}
36