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

CallbackHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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