Completed
Pull Request — master (#175)
by Alexander
02:53 queued 02:53
created

RulesDumper::withFormatter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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