Passed
Pull Request — master (#320)
by Dmitriy
02:52
created

CallbackHandler::validate()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 31
ccs 18
cts 18
cp 1
rs 9.0777
cc 6
nc 6
nop 3
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use InvalidArgumentException;
8
use Yiisoft\Validator\Exception\InvalidCallbackReturnTypeException;
9
use Yiisoft\Validator\Exception\UnexpectedRuleException;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\RuleHandlerInterface;
12
use Yiisoft\Validator\ValidationContext;
13
14
final class CallbackHandler implements RuleHandlerInterface
15
{
16 14
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
17
    {
18 14
        if (!$rule instanceof Callback) {
19 1
            throw new UnexpectedRuleException(Callback::class, $rule);
20
        }
21
22 13
        $callback = $rule->getCallback();
23 13
        if ($callback === null) {
24 1
            throw new InvalidArgumentException('Using method outside of attribute scope is prohibited.');
25
        }
26
27 12
        $callbackResult = $callback($value, $rule, $context);
28
29 12
        if (!$callbackResult instanceof Result) {
30 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
31
        }
32
33 11
        $result = new Result();
34 11
        if ($callbackResult->isValid()) {
35 1
            return $result;
36
        }
37
38 10
        foreach ($callbackResult->getErrors() as $error) {
39 10
            $result->addError(
40 10
                message: $error->getMessage(),
41 10
                valuePath: $error->getValuePath(),
42 10
                parameters: ['value' => $value]
43
            );
44
        }
45
46 10
        return $result;
47
    }
48
}
49