CallbackHandler::validate()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 17
ccs 7
cts 7
cp 1
crap 4
rs 9.9666
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
/**
15
 * Validates a value using a callback.
16
 *
17
 * @see Callback
18
 */
19 17
final class CallbackHandler implements RuleHandlerInterface
20
{
21 17
    /**
22 1
     * @throws InvalidCallbackReturnTypeException
23
     */
24
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
25 16
    {
26 16
        if (!$rule instanceof Callback) {
27 1
            throw new UnexpectedRuleException(Callback::class, $rule);
28
        }
29
30 15
        $callback = $rule->getCallback();
31 15
        if ($callback === null) {
32 1
            throw new InvalidArgumentException('Using method outside of attribute scope is prohibited.');
33
        }
34
35 14
        $result = $callback($value, $rule, $context);
36
        if (!$result instanceof Result) {
37
            throw new InvalidCallbackReturnTypeException($result);
38
        }
39
40
        return $result;
41
    }
42
}
43