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

RulesDumper::asArray()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.9256

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 17
ccs 8
cts 12
cp 0.6667
crap 5.9256
rs 9.6111
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