Passed
Pull Request — master (#97)
by Dmitriy
06:26
created

RulesDumper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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