Passed
Pull Request — master (#222)
by Rustam
02:28
created

CallbackHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 18
dl 0
loc 36
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 27 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\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Formatter;
10
use Yiisoft\Validator\FormatterInterface;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\ValidationContext;
13
14
final class CallbackHandler implements RuleHandlerInterface
15
{
16
    private FormatterInterface $formatter;
17
18 8
    public function __construct(?FormatterInterface $formatter = null)
19
    {
20 8
        $this->formatter = $formatter ?? new Formatter();
21
    }
22
23 8
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
24
    {
25 8
        if (!$rule instanceof Callback) {
26 1
            throw new UnexpectedRuleException(Callback::class, $rule);
27
        }
28
29 7
        $callback = $rule->getCallback();
30 7
        $callbackResult = $callback($value, $context);
31
32 7
        if (!$callbackResult instanceof Result) {
33 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
34
        }
35
36 6
        $result = new Result();
37 6
        if ($callbackResult->isValid()) {
38 1
            return $result;
39
        }
40
41 5
        foreach ($callbackResult->getErrors() as $error) {
42 5
            $formattedMessage = $this->formatter->format(
43 5
                $error->getMessage(),
44 5
                ['attribute' => $context?->getAttribute(), 'value' => $value]
45
            );
46 5
            $result->addError($formattedMessage, $error->getValuePath());
47
        }
48
49 5
        return $result;
50
    }
51
}
52