Passed
Pull Request — master (#97)
by Sergei
01:55
created

RulesDumper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 57.89%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 17
c 1
b 0
f 0
dl 0
loc 64
ccs 11
cts 19
cp 0.5789
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A asArray() 0 17 5
A withFormatter() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
final class RulesDumper
8
{
9
    private ?FormatterInterface $formatter;
10
11 1
    public function __construct(?FormatterInterface $formatter)
12
    {
13 1
        $this->formatter = $formatter;
14 1
    }
15
16
    /**
17
     * Return all attribute rules as array.
18
     *
19
     * For example:
20
     *
21
     * ```php
22
     * [
23
     *    'amount' => [
24
     *        [
25
     *            'number',
26
     *            'integer' => true,
27
     *            'max' => 100,
28
     *            'notANumberMessage' => 'Value must be an integer.',
29
     *            'tooBigMessage' => 'Value must be no greater than 100.'
30
     *        ],
31
     *        ['callback'],
32
     *    ],
33
     *    'name' => [
34
     *        [
35
     *            'hasLength',
36
     *            'max' => 20,
37
     *            'message' => 'Value must contain at most 20 characters.'
38
     *        ],
39
     *    ],
40
     * ]
41
     * ```
42
     *
43
     * @param iterable $rules
44
     *
45
     * @return array
46
     */
47 1
    public function asArray(iterable $rules): array
48
    {
49 1
        $rulesOfArray = [];
50 1
        foreach ($rules as $attribute => $rulesSet) {
51 1
            if (is_array($rulesSet)) {
52 1
                $rulesSet = new Rules($rulesSet);
53
            }
54 1
            if (!$rulesSet instanceof Rules) {
55
                throw new \InvalidArgumentException(sprintf(
56
                    'Value should be instance of %s or an array of rules, %s given.',
57
                    Rules::class,
58
                    is_object($rulesSet) ? get_class($rulesSet) : gettype($rulesSet)
59
                ));
60
            }
61 1
            $rulesOfArray[$attribute] = $rulesSet->withFormatter($this->formatter)->asArray();
62
        }
63 1
        return $rulesOfArray;
64
    }
65
66
    public function withFormatter(?FormatterInterface $formatter): self
67
    {
68
        $new = clone $this;
69
        $new->formatter = $formatter;
70
        return $new;
71
    }
72
}
73