Passed
Pull Request — master (#219)
by
unknown
02:29
created

Callback::callback()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 12
    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 12
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
26
    }
27
28
    /**
29
     * @see $callback
30
     */
31 1
    public function callback(callable $value): self
32
    {
33 1
        $new = clone $this;
34 1
        $new->callback = $value;
35
36 1
        return $new;
37
    }
38
39 11
    protected function validateValue($value, ?ValidationContext $context = null): Result
40
    {
41 11
        $callback = $this->callback;
42 11
        $callbackResult = $callback($value, $context);
43
44 11
        if (!$callbackResult instanceof Result) {
45 1
            throw new InvalidCallbackReturnTypeException($callbackResult);
46
        }
47
48 10
        $result = new Result();
49 10
        if ($callbackResult->isValid()) {
50
            return $result;
51
        }
52
53 10
        foreach ($callbackResult->getErrors() as $error) {
54 10
            $result->addError($this->formatMessage($error->getMessage()), $error->getValuePath());
55
        }
56
57 10
        return $result;
58
    }
59
}
60