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

Callback   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 94.12%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 45
ccs 16
cts 17
cp 0.9412
rs 10
c 1
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A callback() 0 6 1
A validateValue() 0 19 4
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