Passed
Push — master ( 5c2907...37dc07 )
by Sergei
24:35 queued 21:56
created

CallbackHandler::validate()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 34
ccs 18
cts 18
cp 1
rs 9.0444
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
    /**
17
     * @throws InvalidCallbackReturnTypeException
18
     */
19 14
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
20
    {
21 14
        if (!$rule instanceof Callback) {
22 1
            throw new UnexpectedRuleException(Callback::class, $rule);
23
        }
24
25 13
        $callback = $rule->getCallback();
26 13
        if ($callback === null) {
27 1
            throw new InvalidArgumentException('Using method outside of attribute scope is prohibited.');
28
        }
29
30 12
        $callbackResult = $callback($value, $rule, $context);
31
32 12
        if (!$callbackResult instanceof Result) {
33 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
34
        }
35
36 11
        $result = new Result();
37 11
        if ($callbackResult->isValid()) {
38 1
            return $result;
39
        }
40
41 10
        foreach ($callbackResult->getErrors() as $error) {
42 10
            $result->addError(
43 10
                $error->getMessage(),
44
                [
45 10
                    'attribute' => $context->getAttribute(),
46
                    'value' => $value,
47
                ],
48 10
                $error->getValuePath(),
49
            );
50
        }
51
52 10
        return $result;
53
    }
54
}
55