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

Callback   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 34
ccs 12
cts 13
cp 0.9231
rs 10
c 1
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 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 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