Passed
Pull Request — master (#199)
by Alexander
02:50
created

Callback::validateValue()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 19
ccs 10
cts 11
cp 0.9091
crap 4.0119
rs 9.9332
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\FormatterInterface;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\Rule;
11
use Yiisoft\Validator\ValidationContext;
12
13
final class Callback extends Rule
14
{
15 11
    public function __construct(
16
        /**
17
         * @var callable
18
         */
19
        private $callback,
20
        ?FormatterInterface $formatter = null,
21
        bool $skipOnEmpty = false,
22
        bool $skipOnError = false,
23
        $when = null
24
    ) {
25 11
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
26
    }
27
28 10
    protected function validateValue($value, ?ValidationContext $context = null): Result
29
    {
30 10
        $callback = $this->callback;
31 10
        $callbackResult = $callback($value, $context);
32
33 10
        if (!$callbackResult instanceof Result) {
34 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
35
        }
36
37 9
        $result = new Result();
38 9
        if ($callbackResult->isValid()) {
39
            return $result;
40
        }
41
42 9
        foreach ($callbackResult->getErrors() as $error) {
43 9
            $result->addError($this->formatMessage($error->getMessage()), $error->getValuePath());
44
        }
45
46 9
        return $result;
47
    }
48
}
49